diff --git a/projects/core/api/build.gradle b/projects/core/api/build.gradle index af3c02dc..44310cbd 100644 --- a/projects/core/api/build.gradle +++ b/projects/core/api/build.gradle @@ -1,13 +1,12 @@ - dependencies { - compile group: 'org.osgi', name: 'org.osgi.core', version: '4.3.1' - compile group: 'org.osgi', name: 'org.osgi.compendium', version: '4.3.1' - compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.7' + compile group: 'org.osgi', name: 'org.osgi.core', version: '4.3.1' + compile group: 'org.osgi', name: 'org.osgi.compendium', version: '4.3.1' + compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.7' } jar { - manifest { - name = "OpenMUC Core - API" - instruction 'Export-Package', '*' - } + manifest { + name = "OpenMUC Core - API" + instruction 'Export-Package', '*' + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/authentication/AuthenticationService.java b/projects/core/api/src/main/java/org/openmuc/framework/authentication/AuthenticationService.java index 40b58457..b2eb0ab4 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/authentication/AuthenticationService.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/authentication/AuthenticationService.java @@ -23,19 +23,17 @@ import java.util.Set; /** - * * Service interface to get access to the framework wide user management and authentication - * */ public interface AuthenticationService { - public boolean login(String name, String password); + public boolean login(String name, String password); - public boolean contains(String user); + public boolean contains(String user); - public void delete(String user); + public void delete(String user); - public void register(String user, String pwd); + public void register(String user, String pwd); - public Set getAllUsers(); + public Set getAllUsers(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ArgumentSyntaxException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ArgumentSyntaxException.java index f682d148..4bf6060f 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ArgumentSyntaxException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ArgumentSyntaxException.java @@ -23,14 +23,14 @@ public class ArgumentSyntaxException extends Exception { - private static final long serialVersionUID = 4793620849675542512L; + private static final long serialVersionUID = 4793620849675542512L; - public ArgumentSyntaxException(String message) { - super(message); - } + public ArgumentSyntaxException(String message) { + super(message); + } - public ArgumentSyntaxException() { - super(); - } + public ArgumentSyntaxException() { + super(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelConfig.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelConfig.java index 3937b029..c9a32d6e 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelConfig.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelConfig.java @@ -21,93 +21,93 @@ package org.openmuc.framework.config; -import java.util.List; - import org.openmuc.framework.data.ValueType; +import java.util.List; + public interface ChannelConfig { - public static final Boolean DISABLED_DEFAULT = false; - public static final String DESCRIPTION_DEFAULT = ""; - public static final String CHANNEL_ADDRESS_DEFAULT = ""; - public static final String UNIT_DEFAULT = ""; - public static final ValueType VALUE_TYPE_DEFAULT = ValueType.DOUBLE; - public static final int BYTE_ARRAY_SIZE_DEFAULT = 10; - public static final int STRING_SIZE_DEFAULT = 10; - public static final boolean LISTENING_DEFAULT = false; - public static final int SAMPLING_INTERVAL_DEFAULT = -1; - public static final int SAMPLING_TIME_OFFSET_DEFAULT = 0; - public static final String SAMPLING_GROUP_DEFAULT = ""; - public static final int LOGGING_INTERVAL_DEFAULT = -1; - public static final int LOGGING_TIME_OFFSET_DEFAULT = 0; + public static final Boolean DISABLED_DEFAULT = false; + public static final String DESCRIPTION_DEFAULT = ""; + public static final String CHANNEL_ADDRESS_DEFAULT = ""; + public static final String UNIT_DEFAULT = ""; + public static final ValueType VALUE_TYPE_DEFAULT = ValueType.DOUBLE; + public static final int BYTE_ARRAY_SIZE_DEFAULT = 10; + public static final int STRING_SIZE_DEFAULT = 10; + public static final boolean LISTENING_DEFAULT = false; + public static final int SAMPLING_INTERVAL_DEFAULT = -1; + public static final int SAMPLING_TIME_OFFSET_DEFAULT = 0; + public static final String SAMPLING_GROUP_DEFAULT = ""; + public static final int LOGGING_INTERVAL_DEFAULT = -1; + public static final int LOGGING_TIME_OFFSET_DEFAULT = 0; - public String getId(); + public String getId(); - public void setId(String id) throws IdCollisionException; + public void setId(String id) throws IdCollisionException; - public String getDescription(); + public String getDescription(); - public void setDescription(String description); + public void setDescription(String description); - public String getChannelAddress(); + public String getChannelAddress(); - public void setChannelAddress(String address); + public void setChannelAddress(String address); - public String getUnit(); + public String getUnit(); - public void setUnit(String unit); + public void setUnit(String unit); - public ValueType getValueType(); + public ValueType getValueType(); - public void setValueType(ValueType type); + public void setValueType(ValueType type); - public Integer getValueTypeLength(); + public Integer getValueTypeLength(); - public void setValueTypeLength(Integer maxLength); + public void setValueTypeLength(Integer maxLength); - public Double getScalingFactor(); + public Double getScalingFactor(); - public void setScalingFactor(Double factor); + public void setScalingFactor(Double factor); - public Double getValueOffset(); + public Double getValueOffset(); - public void setValueOffset(Double offset); + public void setValueOffset(Double offset); - public Boolean isListening(); + public Boolean isListening(); - public void setListening(Boolean listening); + public void setListening(Boolean listening); - public Integer getSamplingInterval(); + public Integer getSamplingInterval(); - public void setSamplingInterval(Integer interval); + public void setSamplingInterval(Integer interval); - public Integer getSamplingTimeOffset(); + public Integer getSamplingTimeOffset(); - public void setSamplingTimeOffset(Integer offset); + public void setSamplingTimeOffset(Integer offset); - public String getSamplingGroup(); + public String getSamplingGroup(); - public void setSamplingGroup(String group); + public void setSamplingGroup(String group); - public Integer getLoggingInterval(); + public Integer getLoggingInterval(); - public void setLoggingInterval(Integer interval); + public void setLoggingInterval(Integer interval); - public Integer getLoggingTimeOffset(); + public Integer getLoggingTimeOffset(); - public void setLoggingTimeOffset(Integer offset); + public void setLoggingTimeOffset(Integer offset); - public Boolean isDisabled(); + public Boolean isDisabled(); - public void setDisabled(Boolean disabled); + public void setDisabled(Boolean disabled); - public void delete(); + public void delete(); - public DeviceConfig getDevice(); + public DeviceConfig getDevice(); - public List getServerMappings(); + public List getServerMappings(); - public void addServerMapping(ServerMapping serverMapping); + public void addServerMapping(ServerMapping serverMapping); - public void deleteServerMappings(String id); + public void deleteServerMappings(String id); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelScanInfo.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelScanInfo.java index fc1e114a..b2c9b202 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelScanInfo.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ChannelScanInfo.java @@ -25,51 +25,51 @@ public class ChannelScanInfo { - private final String channelAddress; - private final String description; - private final ValueType valueType; - private final Integer valueTypeLength; - private final Boolean readable; - private final Boolean writable; + private final String channelAddress; + private final String description; + private final ValueType valueType; + private final Integer valueTypeLength; + private final Boolean readable; + private final Boolean writable; - public ChannelScanInfo(String channelAddress, String description, ValueType valueType, Integer valueTypeLength) { - this(channelAddress, description, valueType, valueTypeLength, true, true); - } + public ChannelScanInfo(String channelAddress, String description, ValueType valueType, Integer valueTypeLength) { + this(channelAddress, description, valueType, valueTypeLength, true, true); + } - public ChannelScanInfo(String channelAddress, String description, ValueType valueType, Integer valueTypeLength, - Boolean readable, Boolean writable) { - if (channelAddress == null || channelAddress.equals("")) { - throw new IllegalArgumentException("Channel Address may not be empty."); - } - this.channelAddress = channelAddress; - this.description = description; - this.valueType = valueType; - this.valueTypeLength = valueTypeLength; - this.readable = readable; - this.writable = writable; - } + public ChannelScanInfo(String channelAddress, String description, ValueType valueType, Integer valueTypeLength, Boolean readable, + Boolean writable) { + if (channelAddress == null || channelAddress.equals("")) { + throw new IllegalArgumentException("Channel Address may not be empty."); + } + this.channelAddress = channelAddress; + this.description = description; + this.valueType = valueType; + this.valueTypeLength = valueTypeLength; + this.readable = readable; + this.writable = writable; + } - public String getChannelAddress() { - return channelAddress; - } + public String getChannelAddress() { + return channelAddress; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public ValueType getValueType() { - return valueType; - } + public ValueType getValueType() { + return valueType; + } - public Integer getValueTypeLength() { - return valueTypeLength; - } + public Integer getValueTypeLength() { + return valueTypeLength; + } - public Boolean isReadable() { - return readable; - } + public Boolean isReadable() { + return readable; + } - public Boolean isWritable() { - return writable; - } + public Boolean isWritable() { + return writable; + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigChangeListener.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigChangeListener.java index df0c5e8b..bb4bdcf3 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigChangeListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigChangeListener.java @@ -23,5 +23,5 @@ public interface ConfigChangeListener { - public void configurationChanged(); + public void configurationChanged(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigService.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigService.java index d5a526b1..446b596a 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigService.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigService.java @@ -21,48 +21,47 @@ package org.openmuc.framework.config; +import org.openmuc.framework.dataaccess.DeviceState; + import java.io.FileNotFoundException; import java.util.List; -import org.openmuc.framework.dataaccess.DeviceState; - public interface ConfigService { - public void lock(); + public void lock(); - public boolean tryLock(); + public boolean tryLock(); - public void unlock(); + public void unlock(); - public RootConfig getConfig(); + public RootConfig getConfig(); - public RootConfig getConfig(ConfigChangeListener listener); + public RootConfig getConfig(ConfigChangeListener listener); - public void stopListeningForConfigChange(ConfigChangeListener listener); + public void stopListeningForConfigChange(ConfigChangeListener listener); - public void setConfig(RootConfig config); + public void setConfig(RootConfig config); - public void writeConfigToFile() throws ConfigWriteException; + public void writeConfigToFile() throws ConfigWriteException; - public void reloadConfigFromFile() throws FileNotFoundException, ParseException; + public void reloadConfigFromFile() throws FileNotFoundException, ParseException; - public RootConfig getEmptyConfig(); + public RootConfig getEmptyConfig(); - public List scanForDevices(String driverId, String settings) throws DriverNotAvailableException, - UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException; + public List scanForDevices(String driverId, String settings) throws DriverNotAvailableException, + UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException; - public void scanForDevices(String driverId, String settings, DeviceScanListener scanListener) - throws DriverNotAvailableException; + public void scanForDevices(String driverId, String settings, DeviceScanListener scanListener) throws DriverNotAvailableException; - public void interruptDeviceScan(String driverId) throws DriverNotAvailableException, UnsupportedOperationException; + public void interruptDeviceScan(String driverId) throws DriverNotAvailableException, UnsupportedOperationException; - public List scanForChannels(String deviceId, String settings) throws DriverNotAvailableException, - UnsupportedOperationException, ArgumentSyntaxException, ScanException; + public List scanForChannels(String deviceId, String settings) throws DriverNotAvailableException, + UnsupportedOperationException, ArgumentSyntaxException, ScanException; - public DriverInfo getDriverInfo(String driverId) throws DriverNotAvailableException; + public DriverInfo getDriverInfo(String driverId) throws DriverNotAvailableException; - public List getIdsOfRunningDrivers(); + public List getIdsOfRunningDrivers(); - public DeviceState getDeviceState(String deviceId); + public DeviceState getDeviceState(String deviceId); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigWriteException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigWriteException.java index c7654fba..594619b6 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigWriteException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ConfigWriteException.java @@ -23,22 +23,22 @@ public class ConfigWriteException extends Exception { - private static final long serialVersionUID = 3650598545898228870L; + private static final long serialVersionUID = 3650598545898228870L; - public ConfigWriteException() { - super(); - } + public ConfigWriteException() { + super(); + } - public ConfigWriteException(String s) { - super(s); - } + public ConfigWriteException(String s) { + super(s); + } - public ConfigWriteException(Throwable cause) { - super(cause); - } + public ConfigWriteException(Throwable cause) { + super(cause); + } - public ConfigWriteException(String s, Throwable cause) { - super(s, cause); - } + public ConfigWriteException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceConfig.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceConfig.java index bf6eab1c..9aaab1af 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceConfig.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceConfig.java @@ -25,47 +25,47 @@ public interface DeviceConfig { - public static final String DESCRIPTION_DEFAULT = ""; - public static final String DEVICE_ADDRESS_DEFAULT = ""; - public static final String SETTINGS_DEFAULT = ""; - public static final Boolean DISABLED_DEFAULT = false; + public static final String DESCRIPTION_DEFAULT = ""; + public static final String DEVICE_ADDRESS_DEFAULT = ""; + public static final String SETTINGS_DEFAULT = ""; + public static final Boolean DISABLED_DEFAULT = false; - public String getId(); + public String getId(); - public void setId(String id) throws IdCollisionException; + public void setId(String id) throws IdCollisionException; - public String getDescription(); + public String getDescription(); - public void setDescription(String description); + public void setDescription(String description); - public String getDeviceAddress(); + public String getDeviceAddress(); - public void setDeviceAddress(String address); + public void setDeviceAddress(String address); - public String getSettings(); + public String getSettings(); - public void setSettings(String settings); + public void setSettings(String settings); - public Integer getSamplingTimeout(); + public Integer getSamplingTimeout(); - public void setSamplingTimeout(Integer timeout); + public void setSamplingTimeout(Integer timeout); - public Integer getConnectRetryInterval(); + public Integer getConnectRetryInterval(); - public void setConnectRetryInterval(Integer interval); + public void setConnectRetryInterval(Integer interval); - public Boolean isDisabled(); + public Boolean isDisabled(); - public void setDisabled(Boolean disabled); + public void setDisabled(Boolean disabled); - public ChannelConfig addChannel(String channelId) throws IdCollisionException; + public ChannelConfig addChannel(String channelId) throws IdCollisionException; - public ChannelConfig getChannel(String channelId); + public ChannelConfig getChannel(String channelId); - public Collection getChannels(); + public Collection getChannels(); - public void delete(); + public void delete(); - public DriverConfig getDriver(); + public DriverConfig getDriver(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanInfo.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanInfo.java index 75872d1f..3ff2b383 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanInfo.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanInfo.java @@ -23,74 +23,71 @@ /** * Class holding the information of a scanned device. - * */ public class DeviceScanInfo { - private final String id; - private final String deviceAddress; - private final String settings; - private final String description; + private final String id; + private final String deviceAddress; + private final String settings; + private final String description; - public DeviceScanInfo(String deviceAddress, String settings, String description) { - if (deviceAddress == null) { - throw new IllegalArgumentException("deviceAddress must not be null."); - } + public DeviceScanInfo(String deviceAddress, String settings, String description) { + if (deviceAddress == null) { + throw new IllegalArgumentException("deviceAddress must not be null."); + } - id = deviceAddress.replaceAll("[^a-zA-Z0-9]+", ""); + id = deviceAddress.replaceAll("[^a-zA-Z0-9]+", ""); - this.deviceAddress = deviceAddress; + this.deviceAddress = deviceAddress; - if (settings == null) { - this.settings = ""; - } - else { - this.settings = settings; - } + if (settings == null) { + this.settings = ""; + } else { + this.settings = settings; + } - if (description == null) { - this.description = ""; - } - else { - this.description = description; - } + if (description == null) { + this.description = ""; + } else { + this.description = description; + } - } + } - /** - * Gets the ID. The ID is generated out of interface + device address. Special chars are omitted. - * - * @return the id - */ - public String getId() { - return id; - } + /** + * Gets the ID. The ID is generated out of interface + device address. Special chars are omitted. + * + * @return the id + */ + public String getId() { + return id; + } - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return description; - } + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } - /** - * Gets the device address - * - * @return the device address - */ - public String getDeviceAddress() { - return deviceAddress; - } + /** + * Gets the device address + * + * @return the device address + */ + public String getDeviceAddress() { + return deviceAddress; + } - /** - * Gets the settings - * - * @return the settings - */ - public String getSettings() { - return settings; - } + /** + * Gets the settings + * + * @return the settings + */ + public String getSettings() { + return settings; + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanListener.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanListener.java index be1efda1..bef58ea8 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DeviceScanListener.java @@ -23,42 +23,38 @@ /** * Interface to implement when you want to be informed about a device scan progress and results. Register your listener * with configService.scanForDevices(..., listener). - * */ public interface DeviceScanListener { - /** - * Called immediately when a new device has been found. - * - * @param scanInfo - * the information of the device found - */ - public void deviceFound(DeviceScanInfo scanInfo); + /** + * Called immediately when a new device has been found. + * + * @param scanInfo the information of the device found + */ + public void deviceFound(DeviceScanInfo scanInfo); - /** - * Called when scan is progressing. - * - * @param progress - * the scan progress in percentage - */ - public void scanProgress(int progress); + /** + * Called when scan is progressing. + * + * @param progress the scan progress in percentage + */ + public void scanProgress(int progress); - /** - * Called when scan is finished. - */ - public void scanFinished(); + /** + * Called when scan is finished. + */ + public void scanFinished(); - /** - * Called when scan was interrupted through interruptScanDevice() - */ - public void scanInterrupted(); + /** + * Called when scan was interrupted through interruptScanDevice() + */ + public void scanInterrupted(); - /** - * Called when there has been a scan error reported by the driver. - * - * @param message - * the error message - */ - public void scanError(String message); + /** + * Called when there has been a scan error reported by the driver. + * + * @param message the error message + */ + public void scanError(String message); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverChangeListener.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverChangeListener.java index dad4534d..47445c2f 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverChangeListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverChangeListener.java @@ -23,8 +23,8 @@ public interface DriverChangeListener { - public void newDriver(String driverId); + public void newDriver(String driverId); - public void driverRemoved(String driverId); + public void driverRemoved(String driverId); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverConfig.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverConfig.java index 1ac61948..43365676 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverConfig.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverConfig.java @@ -25,32 +25,32 @@ public interface DriverConfig { - public static final int SAMPLING_TIMEOUT_DEFAULT = 0; - public static final int CONNECT_RETRY_INTERVAL_DEFAULT = 60000; - public static final boolean DISABLED_DEFAULT = false; + public static final int SAMPLING_TIMEOUT_DEFAULT = 0; + public static final int CONNECT_RETRY_INTERVAL_DEFAULT = 60000; + public static final boolean DISABLED_DEFAULT = false; - public String getId(); + public String getId(); - public void setId(String id) throws IdCollisionException; + public void setId(String id) throws IdCollisionException; - public Integer getSamplingTimeout(); + public Integer getSamplingTimeout(); - public void setSamplingTimeout(Integer timeout); + public void setSamplingTimeout(Integer timeout); - public Integer getConnectRetryInterval(); + public Integer getConnectRetryInterval(); - public void setConnectRetryInterval(Integer interval); + public void setConnectRetryInterval(Integer interval); - public Boolean isDisabled(); + public Boolean isDisabled(); - public void setDisabled(Boolean disabled); + public void setDisabled(Boolean disabled); - public DeviceConfig addDevice(String deviceId) throws IdCollisionException; + public DeviceConfig addDevice(String deviceId) throws IdCollisionException; - public DeviceConfig getDevice(String deviceId); + public DeviceConfig getDevice(String deviceId); - public Collection getDevices(); + public Collection getDevices(); - public void delete(); + public void delete(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverInfo.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverInfo.java index 71dc9d1c..31b51e09 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverInfo.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverInfo.java @@ -22,51 +22,51 @@ public class DriverInfo { - private final String id; - private final String description; - private final String deviceAddressSyntax; - private final String parametersSyntax; - private final String channelAddressSyntax; - private final String deviceScanParametersSyntax; + private final String id; + private final String description; + private final String deviceAddressSyntax; + private final String parametersSyntax; + private final String channelAddressSyntax; + private final String deviceScanParametersSyntax; - public DriverInfo(String id, String description, String deviceAddressSyntax, String parametersSyntax, - String channelAddressSyntax, String deviceScanParametersSyntax) { - this.id = id; - this.description = description; - this.deviceAddressSyntax = deviceAddressSyntax; - this.parametersSyntax = parametersSyntax; - this.channelAddressSyntax = channelAddressSyntax; - this.deviceScanParametersSyntax = deviceScanParametersSyntax; - } + public DriverInfo(String id, String description, String deviceAddressSyntax, String parametersSyntax, String channelAddressSyntax, + String deviceScanParametersSyntax) { + this.id = id; + this.description = description; + this.deviceAddressSyntax = deviceAddressSyntax; + this.parametersSyntax = parametersSyntax; + this.channelAddressSyntax = channelAddressSyntax; + this.deviceScanParametersSyntax = deviceScanParametersSyntax; + } - /** - * Returns the ID of the driver. The ID may only contain ASCII letters, digits, hyphens and underscores. By - * convention the ID should be meaningful and all lower case letters (e.g. "mbus", "modbus"). - * - * @return the unique ID of the driver. - */ - public String getId() { - return id; - } + /** + * Returns the ID of the driver. The ID may only contain ASCII letters, digits, hyphens and underscores. By + * convention the ID should be meaningful and all lower case letters (e.g. "mbus", "modbus"). + * + * @return the unique ID of the driver. + */ + public String getId() { + return id; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public String getDeviceAddressSyntax() { - return deviceAddressSyntax; - } + public String getDeviceAddressSyntax() { + return deviceAddressSyntax; + } - public String getParametersSyntax() { - return parametersSyntax; - } + public String getParametersSyntax() { + return parametersSyntax; + } - public String getChannelAddressSyntax() { - return channelAddressSyntax; - } + public String getChannelAddressSyntax() { + return channelAddressSyntax; + } - public String getDeviceScanParametersSyntax() { - return deviceScanParametersSyntax; - } + public String getDeviceScanParametersSyntax() { + return deviceScanParametersSyntax; + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverNotAvailableException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverNotAvailableException.java index 42290844..1297e9e8 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/DriverNotAvailableException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/DriverNotAvailableException.java @@ -23,6 +23,6 @@ public class DriverNotAvailableException extends Exception { - private static final long serialVersionUID = -4469071016884028955L; + private static final long serialVersionUID = -4469071016884028955L; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/IdCollisionException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/IdCollisionException.java index 0f13de86..fc505849 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/IdCollisionException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/IdCollisionException.java @@ -23,22 +23,22 @@ public class IdCollisionException extends Exception { - private static final long serialVersionUID = -1887523116889727092L; + private static final long serialVersionUID = -1887523116889727092L; - public IdCollisionException() { - super(); - } + public IdCollisionException() { + super(); + } - public IdCollisionException(String s) { - super(s); - } + public IdCollisionException(String s) { + super(s); + } - public IdCollisionException(Throwable cause) { - super(cause); - } + public IdCollisionException(Throwable cause) { + super(cause); + } - public IdCollisionException(String s, Throwable cause) { - super(s, cause); - } + public IdCollisionException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ParseException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ParseException.java index d6946e38..79aabfa3 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ParseException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ParseException.java @@ -23,22 +23,22 @@ public class ParseException extends Exception { - private static final long serialVersionUID = -1629042625080748627L; + private static final long serialVersionUID = -1629042625080748627L; - public ParseException() { - super(); - } + public ParseException() { + super(); + } - public ParseException(String s) { - super(s); - } + public ParseException(String s) { + super(s); + } - public ParseException(Throwable cause) { - super(cause); - } + public ParseException(Throwable cause) { + super(cause); + } - public ParseException(String s, Throwable cause) { - super(s, cause); - } + public ParseException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/RootConfig.java b/projects/core/api/src/main/java/org/openmuc/framework/config/RootConfig.java index 28f0b510..a658d856 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/RootConfig.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/RootConfig.java @@ -25,20 +25,20 @@ public interface RootConfig { - public String getDataLogSource(); + public String getDataLogSource(); - public void setDataLogSource(String source); + public void setDataLogSource(String source); - public DriverConfig addDriver(String id) throws IdCollisionException; + public DriverConfig addDriver(String id) throws IdCollisionException; - public DriverConfig getOrAddDriver(String id); + public DriverConfig getOrAddDriver(String id); - public DriverConfig getDriver(String id); + public DriverConfig getDriver(String id); - public DeviceConfig getDevice(String id); + public DeviceConfig getDevice(String id); - public ChannelConfig getChannel(String id); + public ChannelConfig getChannel(String id); - public Collection getDrivers(); + public Collection getDrivers(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ScanException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ScanException.java index c3cf92fd..ddc853b2 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ScanException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ScanException.java @@ -23,22 +23,22 @@ public class ScanException extends Exception { - private static final long serialVersionUID = 4691826793044327594L; + private static final long serialVersionUID = 4691826793044327594L; - public ScanException() { - super(); - } + public ScanException() { + super(); + } - public ScanException(String s) { - super(s); - } + public ScanException(String s) { + super(s); + } - public ScanException(Throwable cause) { - super(cause); - } + public ScanException(Throwable cause) { + super(cause); + } - public ScanException(String s, Throwable cause) { - super(s, cause); - } + public ScanException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ScanInterruptedException.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ScanInterruptedException.java index 35391010..498d25f6 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ScanInterruptedException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ScanInterruptedException.java @@ -23,22 +23,22 @@ public class ScanInterruptedException extends Exception { - private static final long serialVersionUID = -3907598956057578830L; + private static final long serialVersionUID = -3907598956057578830L; - public ScanInterruptedException() { - super(); - } + public ScanInterruptedException() { + super(); + } - public ScanInterruptedException(String s) { - super(s); - } + public ScanInterruptedException(String s) { + super(s); + } - public ScanInterruptedException(Throwable cause) { - super(cause); - } + public ScanInterruptedException(Throwable cause) { + super(cause); + } - public ScanInterruptedException(String s, Throwable cause) { - super(s, cause); - } + public ScanInterruptedException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/config/ServerMapping.java b/projects/core/api/src/main/java/org/openmuc/framework/config/ServerMapping.java index 468cea5c..bb01dac1 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/config/ServerMapping.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/config/ServerMapping.java @@ -22,24 +22,23 @@ /** * Class containing the identifier and the address of a server configuration. - * - * @author sfey * + * @author sfey */ public class ServerMapping { - private final String id; - private final String serverAddress; + private final String id; + private final String serverAddress; - public ServerMapping(String id, String serverAddress) { - this.id = id; - this.serverAddress = serverAddress; - } + public ServerMapping(String id, String serverAddress) { + this.id = id; + this.serverAddress = serverAddress; + } - public String getId() { - return this.id; - } + public String getId() { + return this.id; + } - public String getServerAddress() { - return this.serverAddress; - } + public String getServerAddress() { + return this.serverAddress; + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/BooleanValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/BooleanValue.java index 27a8e5d6..b44a4a6f 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/BooleanValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/BooleanValue.java @@ -23,94 +23,87 @@ public class BooleanValue implements Value { - private final boolean value; + private final boolean value; - public BooleanValue(boolean value) { - this.value = value; - } + public BooleanValue(boolean value) { + this.value = value; + } - @Override - public double asDouble() { - if (value) { - return 1.0; - } - else { - return 0.0; - } - } + @Override + public double asDouble() { + if (value) { + return 1.0; + } else { + return 0.0; + } + } - @Override - public float asFloat() { - if (value) { - return 1.0f; - } - else { - return 0.0f; - } - } + @Override + public float asFloat() { + if (value) { + return 1.0f; + } else { + return 0.0f; + } + } - @Override - public long asLong() { - if (value) { - return 1; - } - else { - return 0; - } - } + @Override + public long asLong() { + if (value) { + return 1; + } else { + return 0; + } + } - @Override - public int asInt() { - if (value) { - return 1; - } - else { - return 0; - } - } + @Override + public int asInt() { + if (value) { + return 1; + } else { + return 0; + } + } - @Override - public short asShort() { - if (value) { - return 1; - } - else { - return 0; - } - } + @Override + public short asShort() { + if (value) { + return 1; + } else { + return 0; + } + } - @Override - public byte asByte() { - if (value) { - return 1; - } - else { - return 0; - } - } + @Override + public byte asByte() { + if (value) { + return 1; + } else { + return 0; + } + } - @Override - public boolean asBoolean() { - return value; - } + @Override + public boolean asBoolean() { + return value; + } - @Override - public byte[] asByteArray() { - if (value) { - return new byte[] { 1 }; - } - else { - return new byte[] { 0 }; - } - } + @Override + public byte[] asByteArray() { + if (value) { + return new byte[]{1}; + } else { + return new byte[]{0}; + } + } - @Override - public String toString() { - return Boolean.toString(value); - } + @Override + public String toString() { + return Boolean.toString(value); + } - @Override - public String asString() { - return toString(); - } + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/ByteArrayValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/ByteArrayValue.java index 788043fe..014b858c 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/ByteArrayValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/ByteArrayValue.java @@ -23,90 +23,85 @@ /** * ByteArrayValue is not immutable. - * */ public class ByteArrayValue implements Value { - private final byte[] value; + private final byte[] value; - /** - * Create a new ByteArrayValue whose internal byte array will be a reference to the value passed to - * this constructor. That means the passed byte array is not copied. Therefore you should not change the contents of - * value after calling this constructor. If you want ByteArrayValue to internally store a copy of the passed value - * then you should use the other constructor of this class instead. - * - * @param value - * the byte array value. - */ - public ByteArrayValue(byte[] value) { - this.value = value; - } + /** + * Create a new ByteArrayValue whose internal byte array will be a reference to the value passed to + * this constructor. That means the passed byte array is not copied. Therefore you should not change the contents of + * value after calling this constructor. If you want ByteArrayValue to internally store a copy of the passed value + * then you should use the other constructor of this class instead. + * + * @param value the byte array value. + */ + public ByteArrayValue(byte[] value) { + this.value = value; + } - /** - * Creates a new ByteArrayValue copying the byte array passed if copy is true. - * - * @param value - * the byte array value. - * @param copy - * if true it will internally store a copy of value, else it will store a reference to value. - */ - public ByteArrayValue(byte[] value, boolean copy) { - if (copy) { - this.value = new byte[value.length]; - System.arraycopy(value, 0, this.value, 0, value.length); - } - else { - this.value = value; - } - } + /** + * Creates a new ByteArrayValue copying the byte array passed if copy is true. + * + * @param value the byte array value. + * @param copy if true it will internally store a copy of value, else it will store a reference to value. + */ + public ByteArrayValue(byte[] value, boolean copy) { + if (copy) { + this.value = new byte[value.length]; + System.arraycopy(value, 0, this.value, 0, value.length); + } else { + this.value = value; + } + } - @Override - public double asDouble() { - throw new TypeConversionException(); - } + @Override + public double asDouble() { + throw new TypeConversionException(); + } - @Override - public float asFloat() { - throw new TypeConversionException(); - } + @Override + public float asFloat() { + throw new TypeConversionException(); + } - @Override - public long asLong() { - throw new TypeConversionException(); - } + @Override + public long asLong() { + throw new TypeConversionException(); + } - @Override - public int asInt() { - throw new TypeConversionException(); - } + @Override + public int asInt() { + throw new TypeConversionException(); + } - @Override - public short asShort() { - throw new TypeConversionException(); - } + @Override + public short asShort() { + throw new TypeConversionException(); + } - @Override - public byte asByte() { - throw new TypeConversionException(); - } + @Override + public byte asByte() { + throw new TypeConversionException(); + } - @Override - public boolean asBoolean() { - throw new TypeConversionException(); - } + @Override + public boolean asBoolean() { + throw new TypeConversionException(); + } - @Override - public byte[] asByteArray() { - return value; - } + @Override + public byte[] asByteArray() { + return value; + } - @Override - public String toString() { - return new String(value); - } + @Override + public String toString() { + return new String(value); + } - @Override - public String asString() { - return toString(); - } + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/ByteValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/ByteValue.java index be44112a..1eccd52a 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/ByteValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/ByteValue.java @@ -23,59 +23,59 @@ public class ByteValue implements Value { - private final byte value; + private final byte value; - public ByteValue(byte value) { - this.value = value; - } + public ByteValue(byte value) { + this.value = value; + } - @Override - public double asDouble() { - return value; - } + @Override + public double asDouble() { + return value; + } - @Override - public float asFloat() { - return value; - } + @Override + public float asFloat() { + return value; + } - @Override - public long asLong() { - return value; - } + @Override + public long asLong() { + return value; + } - @Override - public int asInt() { - return value; - } + @Override + public int asInt() { + return value; + } - @Override - public short asShort() { - return value; - } + @Override + public short asShort() { + return value; + } - @Override - public byte asByte() { - return value; - } + @Override + public byte asByte() { + return value; + } - @Override - public boolean asBoolean() { - return (value != 0); - } + @Override + public boolean asBoolean() { + return (value != 0); + } - @Override - public byte[] asByteArray() { - return new byte[] { value }; - } + @Override + public byte[] asByteArray() { + return new byte[]{value}; + } - @Override - public String toString() { - return Byte.toString(value); - } + @Override + public String toString() { + return Byte.toString(value); + } - @Override - public String asString() { - return toString(); - } + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/DoubleValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/DoubleValue.java index 42fb4140..3dfc68a9 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/DoubleValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/DoubleValue.java @@ -25,62 +25,62 @@ public class DoubleValue implements Value { - private final double value; - - public DoubleValue(double value) { - this.value = value; - } - - @Override - public double asDouble() { - return value; - } - - @Override - public float asFloat() { - return (float) value; - } - - @Override - public long asLong() { - return (long) value; - } - - @Override - public int asInt() { - return (int) value; - } - - @Override - public short asShort() { - return (short) value; - } - - @Override - public byte asByte() { - return (byte) value; - } - - @Override - public boolean asBoolean() { - return (value != 0.0); - } - - @Override - public byte[] asByteArray() { - byte[] bytes = new byte[8]; - ByteBuffer.wrap(bytes).putDouble(value); - return bytes; - } - - @Override - public String toString() { - return Double.toString(value); - } - - @Override - public String asString() { - return toString(); - } + private final double value; + + public DoubleValue(double value) { + this.value = value; + } + + @Override + public double asDouble() { + return value; + } + + @Override + public float asFloat() { + return (float) value; + } + + @Override + public long asLong() { + return (long) value; + } + + @Override + public int asInt() { + return (int) value; + } + + @Override + public short asShort() { + return (short) value; + } + + @Override + public byte asByte() { + return (byte) value; + } + + @Override + public boolean asBoolean() { + return (value != 0.0); + } + + @Override + public byte[] asByteArray() { + byte[] bytes = new byte[8]; + ByteBuffer.wrap(bytes).putDouble(value); + return bytes; + } + + @Override + public String toString() { + return Double.toString(value); + } + + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/Flag.java b/projects/core/api/src/main/java/org/openmuc/framework/data/Flag.java index f2475d3c..daf96d58 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/Flag.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/Flag.java @@ -23,116 +23,117 @@ public enum Flag { - VALID(1), TIMEOUT(2), UNKNOWN_ERROR(3), DEVICE_OR_INTERFACE_BUSY(5), ACCESS_METHOD_NOT_SUPPORTED(6), NO_VALUE_RECEIVED_YET( - 7), CONNECTING(8), WAITING_FOR_CONNECTION_RETRY(9), DISCONNECTING(10), DRIVER_UNAVAILABLE(11), SAMPLING_AND_LISTENING_DISABLED( - 12), DISABLED(13), CHANNEL_DELETED(14), STARTED_LATE_AND_TIMED_OUT(15), DRIVER_THREW_UNKNOWN_EXCEPTION(16), COMM_DEVICE_NOT_CONNECTED( - 17), DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID(18), DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND(19), DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE( - 20), DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE(21), DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION( - 22), INFEASIBLE_TO_SAMPLE_CHANNEL_GROUP_IN_ONE_REQUEST(23), DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND(24), DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE( - 25), DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP(26), CANNOT_WRITE_NULL_VALUE(27), DRIVER_ERROR_READ_FAILURE( - 28), CONNECTION_EXCEPTION(29), DRIVER_ERROR_TIMEOUT(30), DRIVER_ERROR_DECODING_RESPONSE_FAILED(31), DATA_LOGGING_NOT_ACTIVE( - 32), DRIVER_ERROR_UNSPECIFIED(33), CUSTOM_ERROR_0(50), CUSTOM_ERROR_1(51), CUSTOM_ERROR_2(52), CUSTOM_ERROR_3( - 53), CUSTOM_ERROR_4(54), CUSTOM_ERROR_5(55), CUSTOM_ERROR_6(56), CUSTOM_ERROR_7(57), CUSTOM_ERROR_8(58), CUSTOM_ERROR_9( - 59); + VALID(1), TIMEOUT(2), UNKNOWN_ERROR(3), DEVICE_OR_INTERFACE_BUSY(5), ACCESS_METHOD_NOT_SUPPORTED(6), NO_VALUE_RECEIVED_YET( + 7), CONNECTING(8), WAITING_FOR_CONNECTION_RETRY(9), DISCONNECTING(10), DRIVER_UNAVAILABLE(11), SAMPLING_AND_LISTENING_DISABLED( + 12), DISABLED(13), CHANNEL_DELETED(14), STARTED_LATE_AND_TIMED_OUT(15), DRIVER_THREW_UNKNOWN_EXCEPTION( + 16), COMM_DEVICE_NOT_CONNECTED(17), DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID( + 18), DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND(19), DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE( + 20), DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE(21), DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION( + 22), INFEASIBLE_TO_SAMPLE_CHANNEL_GROUP_IN_ONE_REQUEST(23), DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND( + 24), DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE(25), DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP( + 26), CANNOT_WRITE_NULL_VALUE(27), DRIVER_ERROR_READ_FAILURE(28), CONNECTION_EXCEPTION(29), DRIVER_ERROR_TIMEOUT( + 30), DRIVER_ERROR_DECODING_RESPONSE_FAILED(31), DATA_LOGGING_NOT_ACTIVE(32), DRIVER_ERROR_UNSPECIFIED(33), CUSTOM_ERROR_0( + 50), CUSTOM_ERROR_1(51), CUSTOM_ERROR_2(52), CUSTOM_ERROR_3(53), CUSTOM_ERROR_4(54), CUSTOM_ERROR_5(55), CUSTOM_ERROR_6( + 56), CUSTOM_ERROR_7(57), CUSTOM_ERROR_8(58), CUSTOM_ERROR_9(59); - private final int code; + private final int code; - private Flag(int code) { - this.code = code; - } + private Flag(int code) { + this.code = code; + } - public byte getCode() { - return (byte) code; - } + public byte getCode() { + return (byte) code; + } - public static Flag newFlag(int code) { - switch (code) { - case 1: - return Flag.VALID; - case 2: - return Flag.TIMEOUT; - case 3: - return Flag.UNKNOWN_ERROR; - case 5: - return Flag.DEVICE_OR_INTERFACE_BUSY; - case 6: - return Flag.ACCESS_METHOD_NOT_SUPPORTED; - case 7: - return Flag.NO_VALUE_RECEIVED_YET; - case 8: - return Flag.CONNECTING; - case 9: - return Flag.WAITING_FOR_CONNECTION_RETRY; - case 10: - return Flag.DISCONNECTING; - case 11: - return Flag.DRIVER_UNAVAILABLE; - case 12: - return Flag.SAMPLING_AND_LISTENING_DISABLED; - case 13: - return Flag.DISABLED; - case 14: - return Flag.CHANNEL_DELETED; - case 15: - return Flag.STARTED_LATE_AND_TIMED_OUT; - case 16: - return Flag.DRIVER_THREW_UNKNOWN_EXCEPTION; - case 17: - return Flag.COMM_DEVICE_NOT_CONNECTED; - case 18: - return Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID; - case 19: - return Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND; - case 20: - return Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - case 21: - return Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE; - case 22: - return Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION; - case 23: - return Flag.INFEASIBLE_TO_SAMPLE_CHANNEL_GROUP_IN_ONE_REQUEST; - case 24: - return Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND; - case 25: - return Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE; - case 26: - return Flag.DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP; - case 27: - return Flag.CANNOT_WRITE_NULL_VALUE; - case 28: - return Flag.DRIVER_ERROR_READ_FAILURE; - case 29: - return Flag.CONNECTION_EXCEPTION; - case 30: - return Flag.DRIVER_ERROR_TIMEOUT; - case 31: - return Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED; - case 32: - return Flag.DATA_LOGGING_NOT_ACTIVE; - case 33: - return Flag.DRIVER_ERROR_UNSPECIFIED; - case 50: - return Flag.CUSTOM_ERROR_0; - case 51: - return Flag.CUSTOM_ERROR_1; - case 52: - return Flag.CUSTOM_ERROR_2; - case 53: - return Flag.CUSTOM_ERROR_3; - case 54: - return Flag.CUSTOM_ERROR_4; - case 55: - return Flag.CUSTOM_ERROR_5; - case 56: - return Flag.CUSTOM_ERROR_6; - case 57: - return Flag.CUSTOM_ERROR_7; - case 58: - return Flag.CUSTOM_ERROR_8; - case 59: - return Flag.CUSTOM_ERROR_9; - default: - throw new IllegalArgumentException("Unknown Flag code: " + code); - } - } + public static Flag newFlag(int code) { + switch (code) { + case 1: + return Flag.VALID; + case 2: + return Flag.TIMEOUT; + case 3: + return Flag.UNKNOWN_ERROR; + case 5: + return Flag.DEVICE_OR_INTERFACE_BUSY; + case 6: + return Flag.ACCESS_METHOD_NOT_SUPPORTED; + case 7: + return Flag.NO_VALUE_RECEIVED_YET; + case 8: + return Flag.CONNECTING; + case 9: + return Flag.WAITING_FOR_CONNECTION_RETRY; + case 10: + return Flag.DISCONNECTING; + case 11: + return Flag.DRIVER_UNAVAILABLE; + case 12: + return Flag.SAMPLING_AND_LISTENING_DISABLED; + case 13: + return Flag.DISABLED; + case 14: + return Flag.CHANNEL_DELETED; + case 15: + return Flag.STARTED_LATE_AND_TIMED_OUT; + case 16: + return Flag.DRIVER_THREW_UNKNOWN_EXCEPTION; + case 17: + return Flag.COMM_DEVICE_NOT_CONNECTED; + case 18: + return Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID; + case 19: + return Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND; + case 20: + return Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + case 21: + return Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE; + case 22: + return Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION; + case 23: + return Flag.INFEASIBLE_TO_SAMPLE_CHANNEL_GROUP_IN_ONE_REQUEST; + case 24: + return Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND; + case 25: + return Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE; + case 26: + return Flag.DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP; + case 27: + return Flag.CANNOT_WRITE_NULL_VALUE; + case 28: + return Flag.DRIVER_ERROR_READ_FAILURE; + case 29: + return Flag.CONNECTION_EXCEPTION; + case 30: + return Flag.DRIVER_ERROR_TIMEOUT; + case 31: + return Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED; + case 32: + return Flag.DATA_LOGGING_NOT_ACTIVE; + case 33: + return Flag.DRIVER_ERROR_UNSPECIFIED; + case 50: + return Flag.CUSTOM_ERROR_0; + case 51: + return Flag.CUSTOM_ERROR_1; + case 52: + return Flag.CUSTOM_ERROR_2; + case 53: + return Flag.CUSTOM_ERROR_3; + case 54: + return Flag.CUSTOM_ERROR_4; + case 55: + return Flag.CUSTOM_ERROR_5; + case 56: + return Flag.CUSTOM_ERROR_6; + case 57: + return Flag.CUSTOM_ERROR_7; + case 58: + return Flag.CUSTOM_ERROR_8; + case 59: + return Flag.CUSTOM_ERROR_9; + default: + throw new IllegalArgumentException("Unknown Flag code: " + code); + } + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/FloatValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/FloatValue.java index b72ddecb..7375e51e 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/FloatValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/FloatValue.java @@ -25,61 +25,61 @@ public class FloatValue implements Value { - private final float value; + private final float value; - public FloatValue(float value) { - this.value = value; - } + public FloatValue(float value) { + this.value = value; + } - @Override - public double asDouble() { - return value; - } + @Override + public double asDouble() { + return value; + } - @Override - public float asFloat() { - return value; - } + @Override + public float asFloat() { + return value; + } - @Override - public long asLong() { - return (long) value; - } + @Override + public long asLong() { + return (long) value; + } - @Override - public int asInt() { - return (int) value; - } + @Override + public int asInt() { + return (int) value; + } - @Override - public short asShort() { - return (short) value; - } + @Override + public short asShort() { + return (short) value; + } - @Override - public byte asByte() { - return (byte) value; - } + @Override + public byte asByte() { + return (byte) value; + } - @Override - public boolean asBoolean() { - return (value != 0.0); - } + @Override + public boolean asBoolean() { + return (value != 0.0); + } - @Override - public byte[] asByteArray() { - byte[] bytes = new byte[4]; - ByteBuffer.wrap(bytes).putFloat(value); - return bytes; - } + @Override + public byte[] asByteArray() { + byte[] bytes = new byte[4]; + ByteBuffer.wrap(bytes).putFloat(value); + return bytes; + } - @Override - public String toString() { - return Float.toString(value); - } + @Override + public String toString() { + return Float.toString(value); + } - @Override - public String asString() { - return toString(); - } + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/IntValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/IntValue.java index 7ba29d5a..95563ec6 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/IntValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/IntValue.java @@ -25,61 +25,61 @@ public class IntValue implements Value { - private final int value; + private final int value; - public IntValue(int value) { - this.value = value; - } + public IntValue(int value) { + this.value = value; + } - @Override - public double asDouble() { - return value; - } + @Override + public double asDouble() { + return value; + } - @Override - public float asFloat() { - return value; - } + @Override + public float asFloat() { + return value; + } - @Override - public long asLong() { - return value; - } + @Override + public long asLong() { + return value; + } - @Override - public int asInt() { - return value; - } + @Override + public int asInt() { + return value; + } - @Override - public short asShort() { - return (short) value; - } + @Override + public short asShort() { + return (short) value; + } - @Override - public byte asByte() { - return (byte) value; - } + @Override + public byte asByte() { + return (byte) value; + } - @Override - public boolean asBoolean() { - return (value != 0); - } + @Override + public boolean asBoolean() { + return (value != 0); + } - @Override - public byte[] asByteArray() { - byte[] bytes = new byte[4]; - ByteBuffer.wrap(bytes).putInt(value); - return bytes; - } + @Override + public byte[] asByteArray() { + byte[] bytes = new byte[4]; + ByteBuffer.wrap(bytes).putInt(value); + return bytes; + } - @Override - public String toString() { - return Integer.toString(value); - } + @Override + public String toString() { + return Integer.toString(value); + } - @Override - public String asString() { - return toString(); - } + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/LongValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/LongValue.java index 2ad5df44..9fc599ce 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/LongValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/LongValue.java @@ -25,62 +25,62 @@ public class LongValue implements Value { - private final long value; - - public LongValue(long value) { - this.value = value; - } - - @Override - public double asDouble() { - return value; - } - - @Override - public float asFloat() { - return value; - } - - @Override - public long asLong() { - return value; - } - - @Override - public int asInt() { - return (int) value; - } - - @Override - public short asShort() { - return (short) value; - } - - @Override - public byte asByte() { - return (byte) value; - } - - @Override - public boolean asBoolean() { - return (value != 0); - } - - @Override - public byte[] asByteArray() { - byte[] bytes = new byte[8]; - ByteBuffer.wrap(bytes).putLong(value); - return bytes; - } - - @Override - public String toString() { - return Long.toString(value); - } - - @Override - public String asString() { - return toString(); - } + private final long value; + + public LongValue(long value) { + this.value = value; + } + + @Override + public double asDouble() { + return value; + } + + @Override + public float asFloat() { + return value; + } + + @Override + public long asLong() { + return value; + } + + @Override + public int asInt() { + return (int) value; + } + + @Override + public short asShort() { + return (short) value; + } + + @Override + public byte asByte() { + return (byte) value; + } + + @Override + public boolean asBoolean() { + return (value != 0); + } + + @Override + public byte[] asByteArray() { + byte[] bytes = new byte[8]; + ByteBuffer.wrap(bytes).putLong(value); + return bytes; + } + + @Override + public String toString() { + return Long.toString(value); + } + + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/Record.java b/projects/core/api/src/main/java/org/openmuc/framework/data/Record.java index 3d77f0db..5fcd0510 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/Record.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/Record.java @@ -27,56 +27,53 @@ */ public class Record { - private final Long timestamp; - private final Flag flag; - private final Value value; + private final Long timestamp; + private final Flag flag; + private final Value value; - public Record(Value value, Long timestamp, Flag flag) { - this.value = value; - this.timestamp = timestamp; - this.flag = flag; - } + public Record(Value value, Long timestamp, Flag flag) { + this.value = value; + this.timestamp = timestamp; + this.flag = flag; + } - /** - * Creates a valid record. - * - * @param value - * the value of the record - * @param timestamp - * the timestamp of the record - */ - public Record(Value value, Long timestamp) { - this(value, timestamp, Flag.VALID); - } + /** + * Creates a valid record. + * + * @param value the value of the record + * @param timestamp the timestamp of the record + */ + public Record(Value value, Long timestamp) { + this(value, timestamp, Flag.VALID); + } - /** - * Creates an invalid record with the given flag. The flag may not indicate valid. - * - * @param flag - * the flag of the invalid record. - */ - public Record(Flag flag) { - this(null, null, flag); - if (flag == Flag.VALID) { - throw new IllegalArgumentException("flag must indicate an error"); - } - } + /** + * Creates an invalid record with the given flag. The flag may not indicate valid. + * + * @param flag the flag of the invalid record. + */ + public Record(Flag flag) { + this(null, null, flag); + if (flag == Flag.VALID) { + throw new IllegalArgumentException("flag must indicate an error"); + } + } - public Value getValue() { - return value; - } + public Value getValue() { + return value; + } - public Long getTimestamp() { - return timestamp; - } + public Long getTimestamp() { + return timestamp; + } - public Flag getFlag() { - return flag; - } + public Flag getFlag() { + return flag; + } - @Override - public String toString() { - return "value: " + value + "; timestamp: " + timestamp + "; flag: " + flag; - } + @Override + public String toString() { + return "value: " + value + "; timestamp: " + timestamp + "; flag: " + flag; + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/ShortValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/ShortValue.java index 20ef9649..7c5a46c6 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/ShortValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/ShortValue.java @@ -25,62 +25,62 @@ public class ShortValue implements Value { - private final short value; - - public ShortValue(short value) { - this.value = value; - } - - @Override - public double asDouble() { - return value; - } - - @Override - public float asFloat() { - return value; - } - - @Override - public long asLong() { - return value; - } - - @Override - public int asInt() { - return value; - } - - @Override - public short asShort() { - return value; - } - - @Override - public byte asByte() { - return (byte) value; - } - - @Override - public boolean asBoolean() { - return (value != 0); - } - - @Override - public byte[] asByteArray() { - byte[] bytes = new byte[2]; - ByteBuffer.wrap(bytes).putShort(value); - return bytes; - } - - @Override - public String toString() { - return Short.toString(value); - } - - @Override - public String asString() { - return toString(); - } + private final short value; + + public ShortValue(short value) { + this.value = value; + } + + @Override + public double asDouble() { + return value; + } + + @Override + public float asFloat() { + return value; + } + + @Override + public long asLong() { + return value; + } + + @Override + public int asInt() { + return value; + } + + @Override + public short asShort() { + return value; + } + + @Override + public byte asByte() { + return (byte) value; + } + + @Override + public boolean asBoolean() { + return (value != 0); + } + + @Override + public byte[] asByteArray() { + byte[] bytes = new byte[2]; + ByteBuffer.wrap(bytes).putShort(value); + return bytes; + } + + @Override + public String toString() { + return Short.toString(value); + } + + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/StringValue.java b/projects/core/api/src/main/java/org/openmuc/framework/data/StringValue.java index 31e80baf..c771e4d4 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/StringValue.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/StringValue.java @@ -25,92 +25,91 @@ public class StringValue implements Value { - private final String value; - - private static final Charset charset = Charset.forName("US-ASCII"); - - public StringValue(String value) { - this.value = value; - } - - @Override - public double asDouble() { - try { - return Double.parseDouble(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public float asFloat() { - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public long asLong() { - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public int asInt() { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public short asShort() { - try { - return Short.parseShort(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public byte asByte() { - try { - return Byte.parseByte(value); - } catch (NumberFormatException e) { - throw new TypeConversionException(); - } - } - - @Override - public boolean asBoolean() { - if ("true".equals(value)) { - return true; - } - else if ("false".equals(value)) { - return false; - } - throw new TypeConversionException(); - } - - @Override - public byte[] asByteArray() { - return value.getBytes(charset); - } - - @Override - public String toString() { - return value; - } - - @Override - public String asString() { - return toString(); - } + private final String value; + + private static final Charset charset = Charset.forName("US-ASCII"); + + public StringValue(String value) { + this.value = value; + } + + @Override + public double asDouble() { + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public float asFloat() { + try { + return Float.parseFloat(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public long asLong() { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public int asInt() { + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public short asShort() { + try { + return Short.parseShort(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public byte asByte() { + try { + return Byte.parseByte(value); + } catch (NumberFormatException e) { + throw new TypeConversionException(); + } + } + + @Override + public boolean asBoolean() { + if ("true".equals(value)) { + return true; + } else if ("false".equals(value)) { + return false; + } + throw new TypeConversionException(); + } + + @Override + public byte[] asByteArray() { + return value.getBytes(charset); + } + + @Override + public String toString() { + return value; + } + + @Override + public String asString() { + return toString(); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/TypeConversionException.java b/projects/core/api/src/main/java/org/openmuc/framework/data/TypeConversionException.java index d1bdbbdf..8983a8f0 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/TypeConversionException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/TypeConversionException.java @@ -23,14 +23,14 @@ public final class TypeConversionException extends RuntimeException { - private static final long serialVersionUID = 968407618209609707L; + private static final long serialVersionUID = 968407618209609707L; - public TypeConversionException() { - super(); - } + public TypeConversionException() { + super(); + } - public TypeConversionException(String s) { - super(s); - } + public TypeConversionException(String s) { + super(s); + } } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/Value.java b/projects/core/api/src/main/java/org/openmuc/framework/data/Value.java index a1993951..4fd9804d 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/Value.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/Value.java @@ -23,81 +23,74 @@ public interface Value { - /** - * Returns the value as a double. - * - * @return the value as a double - * @throws TypeConversionException - * if the stored value cannot be converted to a double - */ - public double asDouble(); + /** + * Returns the value as a double. + * + * @return the value as a double + * @throws TypeConversionException if the stored value cannot be converted to a double + */ + public double asDouble(); - /** - * Returns the value as a float. - * - * @return the value as a float - * @throws TypeConversionException - * if the stored value cannot be converted to a float - */ - public float asFloat(); + /** + * Returns the value as a float. + * + * @return the value as a float + * @throws TypeConversionException if the stored value cannot be converted to a float + */ + public float asFloat(); - /** - * Returns the value as a long. - * - * @return the value as a long - * @throws TypeConversionException - * if the stored value cannot be converted to a long - */ - public long asLong(); + /** + * Returns the value as a long. + * + * @return the value as a long + * @throws TypeConversionException if the stored value cannot be converted to a long + */ + public long asLong(); - /** - * Returns the value as an integer. - * - * @return the value as an integer - * @throws TypeConversionException - * if the stored value cannot be converted to an integer - */ - public int asInt(); + /** + * Returns the value as an integer. + * + * @return the value as an integer + * @throws TypeConversionException if the stored value cannot be converted to an integer + */ + public int asInt(); - /** - * Returns the value as a short. - * - * @return the value as a short - * @throws TypeConversionException - * if the stored value cannot be converted to a short - */ - public short asShort(); + /** + * Returns the value as a short. + * + * @return the value as a short + * @throws TypeConversionException if the stored value cannot be converted to a short + */ + public short asShort(); - /** - * Returns the value as a byte. - * - * @return the value as a byte - * @throws TypeConversionException - * if the stored value cannot be converted to a byte - */ - public byte asByte(); + /** + * Returns the value as a byte. + * + * @return the value as a byte + * @throws TypeConversionException if the stored value cannot be converted to a byte + */ + public byte asByte(); - /** - * Returns the value as a boolean. - * - * @return the value as a boolean - * @throws TypeConversionException - * if the stored value cannot be converted to a boolean - */ - public boolean asBoolean(); + /** + * Returns the value as a boolean. + * + * @return the value as a boolean + * @throws TypeConversionException if the stored value cannot be converted to a boolean + */ + public boolean asBoolean(); - /** - * Returns the value as a byte array. - * - * @return the value as a byte array - */ - public byte[] asByteArray(); + /** + * Returns the value as a byte array. + * + * @return the value as a byte array + */ + public byte[] asByteArray(); - /** - * Returns the value as a string. - * - * @return the value as a string - */ - public String asString(); + /** + * Returns the value as a string. + * + * @return the value as a string + */ + public String asString(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/data/ValueType.java b/projects/core/api/src/main/java/org/openmuc/framework/data/ValueType.java index 4113ad9d..e3fcf492 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/data/ValueType.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/data/ValueType.java @@ -22,5 +22,5 @@ package org.openmuc.framework.data; public enum ValueType { - DOUBLE, FLOAT, LONG, INTEGER, SHORT, BYTE, BOOLEAN, BYTE_ARRAY, STRING; + DOUBLE, FLOAT, LONG, INTEGER, SHORT, BYTE, BOOLEAN, BYTE_ARRAY, STRING; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/Channel.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/Channel.java index 08660a40..8badd9d5 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/Channel.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/Channel.java @@ -21,14 +21,14 @@ package org.openmuc.framework.dataaccess; -import java.io.IOException; -import java.util.List; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; import org.openmuc.framework.data.ValueType; +import java.io.IOException; +import java.util.List; + /** * The Channel class is used to access a single data field of a communication device. A desired channel can * be obtained using the DataAccessService. A channel instance can be used to @@ -39,297 +39,281 @@ *
  • Access historical data that was stored by a data logger such as SlotsDB.
  • *
  • Get configuration information about this channel such as its unit.
  • * - *

    + *

    * Note that only the call of the read or write functions will actually result in a corresponding read or write request * being sent to the communication device. */ public interface Channel { - /** - * Returns the ID of this channel. The ID is usually a meaningful string. It is used to get Channel objects using - * the DataAccessService. - * - * @return the ID of this channel. - */ - public String getId(); - - /** - * Returns the address of this channel. Returns the empty string if not configured. - * - * @return the address of this channel. - */ - public String getChannelAddress(); - - /** - * Returns the description of this channel. Returns the empty string if not configured. - * - * @return the description of this channel. - */ - public String getDescription(); - - /** - * Returns the unit of this channel. Returns the empty string if not configured. The unit is used for informational - * purposes only. Neither the framework nor any driver does value conversions based on the configured unit. - * - * @return the unit of this channel. - */ - public String getUnit(); - - /** - * Returns the value type of this channel. The value type specifies how the value of the latest record of a channel - * is stored. A data logger is encouraged to store values using the configured value type if it supports that value - * type. - *

    - * Usually an application does not need to know the value type of the channel because it can use the value type of - * its choice by using the corresponding function of {@link Value} (e.g. {@link Value#asDouble()}). Necessary - * conversions will be done transparently. - *

    - * If no value type was configured, the default {@link ValueType#DOUBLE} is used. - * - * @return the value type of this channel. - */ - public ValueType getValueType(); - - /** - * Returns the scaling factor. Returns 1.0 if the scaling factor is not configured. - *

    - * The scaling factor is applied in the following cases: - *

      - *
    • Values received by this channel's driver or from apps through {@link #setLatestRecord(Record)} are multiplied - * with the scaling factor before they are stored in the latest record.
    • - *
    • Values written (e.g. using {@link #write(Value)}) are divided by the scaling factor before they are handed to - * the driver for transmission.
    • - *
    - * - * @return the scaling factor - */ - public double getScalingFactor(); - - /** - * Returns the channel's configured sampling interval in milliseconds. Returns -1 if not configured. - * - * @return the channel's configured sampling interval in milliseconds. - */ - public int getSamplingInterval(); - - /** - * Returns the channel's configured sampling time offset in milliseconds. Returns the default of 0 if not - * configured. - * - * @return the channel's configured sampling time offset in milliseconds. - */ - public int getSamplingTimeOffset(); - - /** - * Returns the channel's configured logging interval in milliseconds. Returns -1 if not configured. - * - * @return the channel's configured logging interval in milliseconds. - */ - public int getLoggingInterval(); - - /** - * Returns the channel's configured logging time offset in milliseconds. Returns the default of 0 if not configured. - * - * @return the channel's configured logging time offset in milliseconds. - */ - public int getLoggingTimeOffset(); - - /** - * Returns the unique name of the communication driver that is used by this channel to read/write data. - * - * @return the unique name of the communication driver that is used by this channel to read/write data. - */ - public String getDriverName(); - - /** - * Returns the channel's device address. - * - * @return the channel's device address. - */ - public String getDeviceAddress(); - - /** - * Returns the name of the communication device that this channel belongs to. The empty string if not configured. - * - * @return the name of the communication device that this channel belongs to. - */ - public String getDeviceName(); - - /** - * Returns the description of the communication device that this channel belongs to. The empty string if not - * configured. - * - * @return the description of the communication device that this channel belongs to. - */ - public String getDeviceDescription(); - - /** - * Returns the current channel state. - * - * @return the current channel state. - */ - public ChannelState getChannelState(); - - /** - * Returns the current state of the communication device that this channel belongs to. - * - * @return the current state of the communication device that this channel belongs to. - */ - public DeviceState getDeviceState(); - - /** - * Adds a listener that is notified of new records received by sampling or listening. - * - * @param listener - * the record listener that is notified of new records. - */ - public void addListener(RecordListener listener); - - /** - * Removes a record listener. - * - * @param listener - * the listener shall be removed. - */ - public void removeListener(RecordListener listener); - - /** - * Returns true if a connection to the channel's communication device exist. - * - * @return true if a connection to the channel's communication device exist. - */ - public boolean isConnected(); - - /** - * Returns the latest record of this channel. Every channel holds its latest record in memory. There exist three - * possible source for the latest record: - *
      - *
    • It may be provided by a communication driver that was configured to sample or listen on the channel. In this - * case the timestamp of the record represents the moment in time that the value was received by the driver.
    • - *
    • An application may also set the latest record using setLatestRecord.
    • - *
    • Finally values written using write are also stored as the latest record
    • - *
    - * - * Note that the latest record is never NULL. When a channel is first created its latest record is - * automatically initialized with a flag that indicates that its value is not valid. - * - * @return the latest record. - */ - public Record getLatestRecord(); - - /** - * Sets the latest record of this channel. This function should only be used with channels that are neither sampling - * nor listening. Using this function it is possible to realize "virtual" channels that get their data not from - * drivers but from applications in the framework. - *

    - * Note that the framework treats the passed record in exactly the same way as if it had been received from a - * driver. In particular that means: - *

      - *
    • If data logging is enabled for this channel the latest record is being logged by the registered loggers.
    • - *
    • Other applications can access the value set by this function using getLatestRecord.
    • - *
    • Applications are notified of the new record if they registered as listeners using addListener. - *
    • If a scaling factor has been configured for this channel then the value passed to this function is scaled.
    • - *
    - * - * @param record - * the record to be set. - */ - public void setLatestRecord(Record record); - - /** - * Writes the given value to the channel's corresponding data field in the connected communication device. If an - * error occurs, the returned Flag will indicate this. - * - * @param value - * the value that is to be written - * @return the flag indicating whether the value was successfully written ( Flag.VALID) or not (any - * other flag). - */ - public Flag write(Value value); - - /** - * Schedules a List<records> with future timestamps as write tasks
    - * This function will schedule single write tasks to the provided timestamps.
    - * Once this function is called, previously scheduled write tasks will be erased.
    - * - * @param records - * each record contains the value that is to be written and the timestamp indicating when it should be - * written. The flag of the record is ignored. - */ - public void write(List records); - - /** - * Returns a WriteValueContainer that corresponds to this channel. This container can be passed to the - * write function of DataAccessService to write several values in one transaction. - * - * @return a WriteValueContainer that corresponds to this channel. - */ - public WriteValueContainer getWriteContainer(); - - /** - * Actively reads a value from the channel's corresponding data field in the connected communication device. If an - * error occurs it will be indicated in the returned record's flag. - * - * @return the record containing the value read, the time the value was received and a flag indicating success ( - * Flag.VALID) or a an error (any other flag). - */ - public Record read(); - - /** - * Returns a ReadRecordContainer that corresponds to this channel. This container can be passed to the - * read function of DataAccessService to read several values in one transaction. - * - * @return a ReadRecordContainer that corresponds to this channel. - */ - public ReadRecordContainer getReadContainer(); - - /** - * Returns the logged data record whose timestamp equals the given time. Note that it is the data - * logger's choice whether it stores values using the timestamp that the driver recorded when it received it or the - * timestamp at which the value is to be logged. If the former is the case then this function is not useful because - * it is impossible for an application to know the exact time at which a value was received. In this case use - * getLoggedRecords instead. - * - * @param time - * the time in milliseconds since midnight, January 1, 1970 UTC. - * @return the record that has been stored by the framework's data logger at the given timestamp. - * Returns null if no record exists for this point in time. - * @throws DataLoggerNotAvailableException - * if no data logger is installed and therefore no logged data can be accessed. - * @throws IOException - * if any kind of error occurs accessing the logged data. - */ - public Record getLoggedRecord(long time) throws DataLoggerNotAvailableException, IOException; - - /** - * Returns a list of all logged data records with timestamps from startTime up until now. - * - * @param startTime - * the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive - * @return a list of all logged data records with timestamps from startTime up until now. - * @throws DataLoggerNotAvailableException - * if no data logger is installed and therefore no logged data can be accessed. - * @throws IOException - * if any kind of error occurs accessing the logged data. - */ - public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException; - - /** - * Returns a list of all logged data records with timestamps from startTime to endTime - * inclusive. - * - * @param startTime - * the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive - * @param endTime - * the ending time in milliseconds since midnight, January 1, 1970 UTC. inclusive - * @return a list of all logged data records with timestamps from startTime to endTime - * inclusive. - * @throws DataLoggerNotAvailableException - * if no data logger is installed and therefore no logged data can be accessed. - * @throws IOException - * if any kind of error occurs accessing the logged data. - */ - public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, - IOException; + /** + * Returns the ID of this channel. The ID is usually a meaningful string. It is used to get Channel objects using + * the DataAccessService. + * + * @return the ID of this channel. + */ + public String getId(); + + /** + * Returns the address of this channel. Returns the empty string if not configured. + * + * @return the address of this channel. + */ + public String getChannelAddress(); + + /** + * Returns the description of this channel. Returns the empty string if not configured. + * + * @return the description of this channel. + */ + public String getDescription(); + + /** + * Returns the unit of this channel. Returns the empty string if not configured. The unit is used for informational + * purposes only. Neither the framework nor any driver does value conversions based on the configured unit. + * + * @return the unit of this channel. + */ + public String getUnit(); + + /** + * Returns the value type of this channel. The value type specifies how the value of the latest record of a channel + * is stored. A data logger is encouraged to store values using the configured value type if it supports that value + * type. + *

    + * Usually an application does not need to know the value type of the channel because it can use the value type of + * its choice by using the corresponding function of {@link Value} (e.g. {@link Value#asDouble()}). Necessary + * conversions will be done transparently. + *

    + * If no value type was configured, the default {@link ValueType#DOUBLE} is used. + * + * @return the value type of this channel. + */ + public ValueType getValueType(); + + /** + * Returns the scaling factor. Returns 1.0 if the scaling factor is not configured. + *

    + * The scaling factor is applied in the following cases: + *

      + *
    • Values received by this channel's driver or from apps through {@link #setLatestRecord(Record)} are multiplied + * with the scaling factor before they are stored in the latest record.
    • + *
    • Values written (e.g. using {@link #write(Value)}) are divided by the scaling factor before they are handed to + * the driver for transmission.
    • + *
    + * + * @return the scaling factor + */ + public double getScalingFactor(); + + /** + * Returns the channel's configured sampling interval in milliseconds. Returns -1 if not configured. + * + * @return the channel's configured sampling interval in milliseconds. + */ + public int getSamplingInterval(); + + /** + * Returns the channel's configured sampling time offset in milliseconds. Returns the default of 0 if not + * configured. + * + * @return the channel's configured sampling time offset in milliseconds. + */ + public int getSamplingTimeOffset(); + + /** + * Returns the channel's configured logging interval in milliseconds. Returns -1 if not configured. + * + * @return the channel's configured logging interval in milliseconds. + */ + public int getLoggingInterval(); + + /** + * Returns the channel's configured logging time offset in milliseconds. Returns the default of 0 if not configured. + * + * @return the channel's configured logging time offset in milliseconds. + */ + public int getLoggingTimeOffset(); + + /** + * Returns the unique name of the communication driver that is used by this channel to read/write data. + * + * @return the unique name of the communication driver that is used by this channel to read/write data. + */ + public String getDriverName(); + + /** + * Returns the channel's device address. + * + * @return the channel's device address. + */ + public String getDeviceAddress(); + + /** + * Returns the name of the communication device that this channel belongs to. The empty string if not configured. + * + * @return the name of the communication device that this channel belongs to. + */ + public String getDeviceName(); + + /** + * Returns the description of the communication device that this channel belongs to. The empty string if not + * configured. + * + * @return the description of the communication device that this channel belongs to. + */ + public String getDeviceDescription(); + + /** + * Returns the current channel state. + * + * @return the current channel state. + */ + public ChannelState getChannelState(); + + /** + * Returns the current state of the communication device that this channel belongs to. + * + * @return the current state of the communication device that this channel belongs to. + */ + public DeviceState getDeviceState(); + + /** + * Adds a listener that is notified of new records received by sampling or listening. + * + * @param listener the record listener that is notified of new records. + */ + public void addListener(RecordListener listener); + + /** + * Removes a record listener. + * + * @param listener the listener shall be removed. + */ + public void removeListener(RecordListener listener); + + /** + * Returns true if a connection to the channel's communication device exist. + * + * @return true if a connection to the channel's communication device exist. + */ + public boolean isConnected(); + + /** + * Returns the latest record of this channel. Every channel holds its latest record in memory. There exist three + * possible source for the latest record: + *
      + *
    • It may be provided by a communication driver that was configured to sample or listen on the channel. In this + * case the timestamp of the record represents the moment in time that the value was received by the driver.
    • + *
    • An application may also set the latest record using setLatestRecord.
    • + *
    • Finally values written using write are also stored as the latest record
    • + *
    + *

    + * Note that the latest record is never NULL. When a channel is first created its latest record is + * automatically initialized with a flag that indicates that its value is not valid. + * + * @return the latest record. + */ + public Record getLatestRecord(); + + /** + * Sets the latest record of this channel. This function should only be used with channels that are neither sampling + * nor listening. Using this function it is possible to realize "virtual" channels that get their data not from + * drivers but from applications in the framework. + *

    + * Note that the framework treats the passed record in exactly the same way as if it had been received from a + * driver. In particular that means: + *

      + *
    • If data logging is enabled for this channel the latest record is being logged by the registered loggers.
    • + *
    • Other applications can access the value set by this function using getLatestRecord.
    • + *
    • Applications are notified of the new record if they registered as listeners using addListener. + *
    • If a scaling factor has been configured for this channel then the value passed to this function is scaled.
    • + *
    + * + * @param record the record to be set. + */ + public void setLatestRecord(Record record); + + /** + * Writes the given value to the channel's corresponding data field in the connected communication device. If an + * error occurs, the returned Flag will indicate this. + * + * @param value the value that is to be written + * @return the flag indicating whether the value was successfully written ( Flag.VALID) or not (any + * other flag). + */ + public Flag write(Value value); + + /** + * Schedules a List<records> with future timestamps as write tasks
    + * This function will schedule single write tasks to the provided timestamps.
    + * Once this function is called, previously scheduled write tasks will be erased.
    + * + * @param records each record contains the value that is to be written and the timestamp indicating when it should be + * written. The flag of the record is ignored. + */ + public void write(List records); + + /** + * Returns a WriteValueContainer that corresponds to this channel. This container can be passed to the + * write function of DataAccessService to write several values in one transaction. + * + * @return a WriteValueContainer that corresponds to this channel. + */ + public WriteValueContainer getWriteContainer(); + + /** + * Actively reads a value from the channel's corresponding data field in the connected communication device. If an + * error occurs it will be indicated in the returned record's flag. + * + * @return the record containing the value read, the time the value was received and a flag indicating success ( + * Flag.VALID) or a an error (any other flag). + */ + public Record read(); + + /** + * Returns a ReadRecordContainer that corresponds to this channel. This container can be passed to the + * read function of DataAccessService to read several values in one transaction. + * + * @return a ReadRecordContainer that corresponds to this channel. + */ + public ReadRecordContainer getReadContainer(); + + /** + * Returns the logged data record whose timestamp equals the given time. Note that it is the data + * logger's choice whether it stores values using the timestamp that the driver recorded when it received it or the + * timestamp at which the value is to be logged. If the former is the case then this function is not useful because + * it is impossible for an application to know the exact time at which a value was received. In this case use + * getLoggedRecords instead. + * + * @param time the time in milliseconds since midnight, January 1, 1970 UTC. + * @return the record that has been stored by the framework's data logger at the given timestamp. + * Returns null if no record exists for this point in time. + * @throws DataLoggerNotAvailableException if no data logger is installed and therefore no logged data can be accessed. + * @throws IOException if any kind of error occurs accessing the logged data. + */ + public Record getLoggedRecord(long time) throws DataLoggerNotAvailableException, IOException; + + /** + * Returns a list of all logged data records with timestamps from startTime up until now. + * + * @param startTime the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive + * @return a list of all logged data records with timestamps from startTime up until now. + * @throws DataLoggerNotAvailableException if no data logger is installed and therefore no logged data can be accessed. + * @throws IOException if any kind of error occurs accessing the logged data. + */ + public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException; + + /** + * Returns a list of all logged data records with timestamps from startTime to endTime + * inclusive. + * + * @param startTime the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive + * @param endTime the ending time in milliseconds since midnight, January 1, 1970 UTC. inclusive + * @return a list of all logged data records with timestamps from startTime to endTime + * inclusive. + * @throws DataLoggerNotAvailableException if no data logger is installed and therefore no logged data can be accessed. + * @throws IOException if any kind of error occurs accessing the logged data. + */ + public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, IOException; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelChangeListener.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelChangeListener.java index 287601cd..9c7fcfc3 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelChangeListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelChangeListener.java @@ -23,8 +23,8 @@ public interface ChannelChangeListener { - public void channelModified(Channel channel); + public void channelModified(Channel channel); - public void channelDeleted(Channel channel); + public void channelDeleted(Channel channel); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelState.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelState.java index 21956f18..3d41bc29 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelState.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ChannelState.java @@ -22,5 +22,5 @@ package org.openmuc.framework.dataaccess; public enum ChannelState { - LISTENING, SAMPLING, CONNECTED, CONNECTING, WAITING_FOR_CONNECTION_RETRY, DISCONNECTING, DRIVER_UNAVAILABLE, DISABLED, DELETED; + LISTENING, SAMPLING, CONNECTED, CONNECTING, WAITING_FOR_CONNECTION_RETRY, DISCONNECTING, DRIVER_UNAVAILABLE, DISABLED, DELETED; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataAccessService.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataAccessService.java index a95fc5c3..5f76af9e 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataAccessService.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataAccessService.java @@ -24,24 +24,22 @@ import java.util.List; /** - * * Service interface to get access to the measurement and control data of connected communication devices. - * */ public interface DataAccessService { - public Channel getChannel(String id); + public Channel getChannel(String id); - public Channel getChannel(String id, ChannelChangeListener channelChangeListener); + public Channel getChannel(String id, ChannelChangeListener channelChangeListener); - public List getAllIds(); + public List getAllIds(); - public List getLogicalDevices(String type); + public List getLogicalDevices(String type); - public List getLogicalDevices(String type, LogicalDeviceChangeListener logicalDeviceChangeListener); + public List getLogicalDevices(String type, LogicalDeviceChangeListener logicalDeviceChangeListener); - public void read(List values); + public void read(List values); - public void write(List values); + public void write(List values); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataLoggerNotAvailableException.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataLoggerNotAvailableException.java index dc21d550..9682c1fa 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataLoggerNotAvailableException.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DataLoggerNotAvailableException.java @@ -23,6 +23,6 @@ public class DataLoggerNotAvailableException extends Exception { - private static final long serialVersionUID = 8154261296935773357L; + private static final long serialVersionUID = 8154261296935773357L; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DeviceState.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DeviceState.java index c47e6593..429f6442 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DeviceState.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/DeviceState.java @@ -22,5 +22,6 @@ package org.openmuc.framework.dataaccess; public enum DeviceState { - READING, WRITING, STARTING_TO_LISTEN, SCANNING_FOR_CHANNELS, CONNECTED, CONNECTING, WAITING_FOR_CONNECTION_RETRY, DISCONNECTING, DRIVER_UNAVAILABLE, DISABLED, DELETED; + READING, WRITING, STARTING_TO_LISTEN, SCANNING_FOR_CHANNELS, CONNECTED, CONNECTING, WAITING_FOR_CONNECTION_RETRY, DISCONNECTING, + DRIVER_UNAVAILABLE, DISABLED, DELETED; } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDevice.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDevice.java index 4cf2fe69..3fd3d384 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDevice.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDevice.java @@ -23,8 +23,8 @@ public interface LogicalDevice { - public Channel getChannel(String parameterName); + public Channel getChannel(String parameterName); - public Channel getChannel(String parameterName, ChannelChangeListener channelChangeListener); + public Channel getChannel(String parameterName, ChannelChangeListener channelChangeListener); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDeviceChangeListener.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDeviceChangeListener.java index 83a4b4ed..82c2fa5d 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDeviceChangeListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/LogicalDeviceChangeListener.java @@ -23,10 +23,10 @@ public interface LogicalDeviceChangeListener { - public void logicalDeviceModified(LogicalDevice logicalDevice); + public void logicalDeviceModified(LogicalDevice logicalDevice); - public void logicalDeviceDeleted(LogicalDevice logicalDevice); + public void logicalDeviceDeleted(LogicalDevice logicalDevice); - public void logicalDeviceAdded(LogicalDevice logicalDevice); + public void logicalDeviceAdded(LogicalDevice logicalDevice); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ReadRecordContainer.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ReadRecordContainer.java index bff77ea9..adc9c34d 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ReadRecordContainer.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/ReadRecordContainer.java @@ -25,8 +25,8 @@ public interface ReadRecordContainer { - public Record getRecord(); + public Record getRecord(); - public Channel getChannel(); + public Channel getChannel(); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/RecordListener.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/RecordListener.java index 8048b5e0..5c38796e 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/RecordListener.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/RecordListener.java @@ -25,5 +25,5 @@ public interface RecordListener { - public void newRecord(Record record); + public void newRecord(Record record); } diff --git a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/WriteValueContainer.java b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/WriteValueContainer.java index 180d947f..2650d8f3 100644 --- a/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/WriteValueContainer.java +++ b/projects/core/api/src/main/java/org/openmuc/framework/dataaccess/WriteValueContainer.java @@ -26,12 +26,12 @@ public interface WriteValueContainer { - public void setValue(Value value); + public void setValue(Value value); - public Value getValue(); + public Value getValue(); - public Flag getFlag(); + public Flag getFlag(); - public Channel getChannel(); + public Channel getChannel(); } diff --git a/projects/core/datamanager/build.gradle b/projects/core/datamanager/build.gradle index 742be888..64cc50b6 100644 --- a/projects/core/datamanager/build.gradle +++ b/projects/core/datamanager/build.gradle @@ -1,12 +1,11 @@ - dependencies { - compile project(':openmuc-core-spi') + compile project(':openmuc-core-spi') } jar { - manifest { - name = "OpenMUC Core - Data Manager" - instruction 'Service-Component', 'OSGI-INF/components.xml', 'OSGI-INF/authentication.xml' - instruction 'Export-Package', '' - } + manifest { + name = "OpenMUC Core - Data Manager" + instruction 'Service-Component', 'OSGI-INF/components.xml', 'OSGI-INF/authentication.xml' + instruction 'Export-Package', '' + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/authentication/Authentication.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/authentication/Authentication.java index c72c908f..02dca781 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/authentication/Authentication.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/authentication/Authentication.java @@ -21,13 +21,9 @@ package org.openmuc.framework.core.authentication; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; +import org.openmuc.framework.authentication.AuthenticationService; + +import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; @@ -35,137 +31,134 @@ import java.util.HashSet; import java.util.Set; -import org.openmuc.framework.authentication.AuthenticationService; - public final class Authentication implements AuthenticationService { - public String path; - HashMap shadow = new HashMap();; - - public Authentication() { - path = System.getProperty("bundles.configuration.location"); - if (path == null) { - path = "conf/shadow"; - } - else { - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - path += "/shadow"; - } - File file = new File(path); - if (!file.exists()) { - register("admin", "admin"); - } - else { - getShadow(); - } - } - - @Override - public void register(String user, String pwd) { - pwd += generateHash(user); // use the hash of the username as salt - - String hash = generateHash(pwd); - - setUser(user, hash); - } - - @Override - public boolean login(String user, String pwd) { - - pwd += generateHash(user); // use the hash of the username as salt - String hash = generateHash(pwd); - if (shadow.containsKey(user)) { - String storedHash = shadow.get(user); - if (hash.equals(storedHash)) { - return true; - } - } - - return false; - } - - @Override - public void delete(String user) { - shadow.remove(user); - - writeShadow(shadow); - } - - @Override - public boolean contains(String user) { - return shadow.containsKey(user); - } - - @Override - public Set getAllUsers() { - Set registeredUsers = new HashSet(); - registeredUsers.addAll(Collections.unmodifiableSet(shadow.keySet())); - - return registeredUsers; - } - - private String generateHash(String pwd) { - StringBuilder hash = new StringBuilder(); - - MessageDigest sha; - try { - sha = MessageDigest.getInstance("SHA-256"); - byte[] hashedBytes = sha.digest(pwd.getBytes()); - char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - for (byte hashedByte : hashedBytes) { - hash.append(digits[(hashedByte & 0xf0) >> 4]); - hash.append(digits[(hashedByte & 0x0f)]); - } - - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return hash.toString(); - } - - private void setUser(String user, String hash) { - shadow.put(user, hash); - - writeShadow(shadow); - } - - private void writeShadow(HashMap shadow) { - String text = ""; - - for (String key : shadow.keySet()) { - text += key + ":" + shadow.get(key) + "\n"; - } - try { - Writer output = new BufferedWriter(new FileWriter(new File(path))); - output.write(text); - output.flush(); - output.close(); - } catch (IOException e) { - } - - } - - private void getShadow() { - try { - BufferedReader reader = new BufferedReader(new FileReader(path)); - try { - String line = ""; - - while ((line = reader.readLine()) != null) { - String[] temp = line.split(":"); - - shadow.put(temp[0], temp[1]); - } - } finally { - reader.close(); - } - - } catch (Exception e) { - } - } + public String path; + HashMap shadow = new HashMap(); + ; + + public Authentication() { + path = System.getProperty("bundles.configuration.location"); + if (path == null) { + path = "conf/shadow"; + } else { + if (path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + path += "/shadow"; + } + File file = new File(path); + if (!file.exists()) { + register("admin", "admin"); + } else { + getShadow(); + } + } + + @Override + public void register(String user, String pwd) { + pwd += generateHash(user); // use the hash of the username as salt + + String hash = generateHash(pwd); + + setUser(user, hash); + } + + @Override + public boolean login(String user, String pwd) { + + pwd += generateHash(user); // use the hash of the username as salt + String hash = generateHash(pwd); + if (shadow.containsKey(user)) { + String storedHash = shadow.get(user); + if (hash.equals(storedHash)) { + return true; + } + } + + return false; + } + + @Override + public void delete(String user) { + shadow.remove(user); + + writeShadow(shadow); + } + + @Override + public boolean contains(String user) { + return shadow.containsKey(user); + } + + @Override + public Set getAllUsers() { + Set registeredUsers = new HashSet(); + registeredUsers.addAll(Collections.unmodifiableSet(shadow.keySet())); + + return registeredUsers; + } + + private String generateHash(String pwd) { + StringBuilder hash = new StringBuilder(); + + MessageDigest sha; + try { + sha = MessageDigest.getInstance("SHA-256"); + byte[] hashedBytes = sha.digest(pwd.getBytes()); + char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + for (byte hashedByte : hashedBytes) { + hash.append(digits[(hashedByte & 0xf0) >> 4]); + hash.append(digits[(hashedByte & 0x0f)]); + } + + } catch (NoSuchAlgorithmException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return hash.toString(); + } + + private void setUser(String user, String hash) { + shadow.put(user, hash); + + writeShadow(shadow); + } + + private void writeShadow(HashMap shadow) { + String text = ""; + + for (String key : shadow.keySet()) { + text += key + ":" + shadow.get(key) + "\n"; + } + try { + Writer output = new BufferedWriter(new FileWriter(new File(path))); + output.write(text); + output.flush(); + output.close(); + } catch (IOException e) { + } + + } + + private void getShadow() { + try { + BufferedReader reader = new BufferedReader(new FileReader(path)); + try { + String line = ""; + + while ((line = reader.readLine()) != null) { + String[] temp = line.split(":"); + + shadow.put(temp[0], temp[1]); + } + } finally { + reader.close(); + } + + } catch (Exception e) { + } + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Action.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Action.java index 913a4f37..79a41407 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Action.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Action.java @@ -25,15 +25,15 @@ public final class Action { - long startTime; + long startTime; - List samplingCollections = null; - List timeouts = null; - List loggingCollections = null; - List connectionRetryDevices = null; + List samplingCollections = null; + List timeouts = null; + List loggingCollections = null; + List connectionRetryDevices = null; - public Action(long startTime) { - this.startTime = startTime; - } + public Action(long startTime) { + this.startTime = startTime; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelCollection.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelCollection.java index 39105ae2..47c01492 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelCollection.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelCollection.java @@ -26,22 +26,22 @@ public final class ChannelCollection { - List channels = new LinkedList(); - int interval; - int timeOffset; - String samplingGroup; - Device device; - Action action; + List channels = new LinkedList(); + int interval; + int timeOffset; + String samplingGroup; + Device device; + Action action; - public ChannelCollection(Integer interval, Integer timeOffset, String samplingGroup, Device device) { - this.interval = interval; - this.timeOffset = timeOffset; - this.samplingGroup = samplingGroup; - this.device = device; - } + public ChannelCollection(Integer interval, Integer timeOffset, String samplingGroup, Device device) { + this.interval = interval; + this.timeOffset = timeOffset; + this.samplingGroup = samplingGroup; + this.device = device; + } - public long calculateNextActionTime(long timestamp) { - return ((interval - (((timestamp % (24 * 60 * 60 * 1000)) - timeOffset) % interval)) + timestamp); - } + public long calculateNextActionTime(long timestamp) { + return ((interval - (((timestamp % (24 * 60 * 60 * 1000)) - timeOffset) % interval)) + timestamp); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelConfigImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelConfigImpl.java index 3739bbe3..c40ba29b 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelConfigImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelConfigImpl.java @@ -21,729 +21,671 @@ package org.openmuc.framework.core.datamanager; -import java.util.ArrayList; -import java.util.List; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.ParseException; -import org.openmuc.framework.config.ServerMapping; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.dataaccess.ChannelState; import org.openmuc.framework.datalogger.spi.LogChannel; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; + +import java.util.ArrayList; +import java.util.List; public final class ChannelConfigImpl implements ChannelConfig, LogChannel { - String id; - String channelAddress = null; - String description = null; - String unit = null; - ValueType valueType = null; - Integer valueTypeLength = null; - Double scalingFactor = null; - Double valueOffset = null; - Boolean listening = null; - Integer samplingInterval = null; - Integer samplingTimeOffset = null; - String samplingGroup = null; - Integer loggingInterval = null; - Integer loggingTimeOffset = null; - Boolean disabled = null; - List serverMappings = null; - - ChannelImpl channel; - DeviceConfigImpl deviceParent; - - ChannelState state; - - ChannelConfigImpl(String id, DeviceConfigImpl deviceParent) { - this.id = id; - this.deviceParent = deviceParent; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) throws IdCollisionException { - if (id == null) { - throw new IllegalArgumentException("The channel ID may not be null"); - } - ChannelConfigImpl.checkIdSyntax(id); - - if (deviceParent.driverParent.rootConfigParent.channelConfigsById.containsKey(id)) { - throw new IdCollisionException("Collision with channel ID:" + id); - } - - deviceParent.channelConfigsById.put(id, deviceParent.channelConfigsById.remove(this.id)); - deviceParent.driverParent.rootConfigParent.channelConfigsById.put(id, - deviceParent.driverParent.rootConfigParent.channelConfigsById.remove(this.id)); - - this.id = id; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getChannelAddress() { - return channelAddress; - } - - @Override - public void setChannelAddress(String address) { - channelAddress = address; - } - - @Override - public String getUnit() { - return unit; - } - - @Override - public void setUnit(String unit) { - this.unit = unit; - } - - @Override - public ValueType getValueType() { - return valueType; - } - - @Override - public void setValueType(ValueType valueType) { - this.valueType = valueType; - } - - @Override - public Integer getValueTypeLength() { - return valueTypeLength; - } - - @Override - public void setValueTypeLength(Integer length) { - valueTypeLength = length; - } - - @Override - public Double getScalingFactor() { - return scalingFactor; - } - - @Override - public void setScalingFactor(Double factor) { - scalingFactor = factor; - } - - @Override - public Double getValueOffset() { - return valueOffset; - } - - @Override - public void setValueOffset(Double offset) { - valueOffset = offset; - } - - @Override - public Boolean isListening() { - return listening; - } - - @Override - public void setListening(Boolean listening) { - if (samplingInterval != null && listening != null && listening && samplingInterval > 0) { - throw new IllegalStateException("Listening may not be enabled while sampling is enabled."); - } - this.listening = listening; - } - - @Override - public Integer getSamplingInterval() { - return samplingInterval; - } - - @Override - public void setSamplingInterval(Integer samplingInterval) { - if (listening != null && samplingInterval != null && listening && samplingInterval > 0) { - throw new IllegalStateException("Sampling may not be enabled while listening is enabled."); - } - this.samplingInterval = samplingInterval; - } - - @Override - public Integer getSamplingTimeOffset() { - return samplingTimeOffset; - } - - @Override - public void setSamplingTimeOffset(Integer samplingTimeOffset) { - if (samplingTimeOffset != null && samplingTimeOffset < 0) { - throw new IllegalArgumentException("The sampling time offset may not be negative."); - } - this.samplingTimeOffset = samplingTimeOffset; - } - - @Override - public String getSamplingGroup() { - return samplingGroup; - } - - @Override - public void setSamplingGroup(String group) { - samplingGroup = group; - } - - @Override - public Integer getLoggingInterval() { - return loggingInterval; - } - - @Override - public void setLoggingInterval(Integer loggingInterval) { - this.loggingInterval = loggingInterval; - } - - @Override - public Integer getLoggingTimeOffset() { - return loggingTimeOffset; - } - - @Override - public void setLoggingTimeOffset(Integer loggingTimeOffset) { - if (loggingTimeOffset != null && loggingTimeOffset < 0) { - throw new IllegalArgumentException("The logging time offset may not be negative."); - } - this.loggingTimeOffset = loggingTimeOffset; - } - - @Override - public Boolean isDisabled() { - return disabled; - } - - @Override - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } - - @Override - public void delete() { - deviceParent.channelConfigsById.remove(id); - clear(); - } - - @Override - public List getServerMappings() { - if (serverMappings != null) { - return this.serverMappings; - } - else { - return new ArrayList(); - } - } - - void clear() { - deviceParent.driverParent.rootConfigParent.channelConfigsById.remove(id); - deviceParent = null; - } - - @Override - public DeviceConfig getDevice() { - return deviceParent; - } - - static void addChannelFromDomNode(Node channelConfigNode, DeviceConfig parentConfig) throws ParseException { - - String id = ChannelConfigImpl.getAttributeValue(channelConfigNode, "id"); - if (id == null) { - throw new ParseException("channel has no id attribute"); - } - - ChannelConfigImpl config; - - try { - config = (ChannelConfigImpl) parentConfig.addChannel(id); - } catch (Exception e) { - throw new ParseException(e); - } - - NodeList channelChildren = channelConfigNode.getChildNodes(); - - try { - for (int i = 0; i < channelChildren.getLength(); i++) { - Node childNode = channelChildren.item(i); - String childName = childNode.getNodeName(); - - if (childName.equals("#text")) { - continue; - } - else if (childName.equals("description")) { - config.setDescription(childNode.getTextContent()); - } - else if (childName.equals("channelAddress")) { - config.setChannelAddress(childNode.getTextContent()); - } - else if (childName.equals("serverMapping")) { - NamedNodeMap attributes = childNode.getAttributes(); - Node nameAttribute = attributes.getNamedItem("id"); - - if (nameAttribute != null) { - config.addServerMapping(new ServerMapping(nameAttribute.getTextContent(), childNode - .getTextContent())); - } - else { - throw new ParseException("No id attribute specified for serverMapping."); - } - } - else if (childName.equals("unit")) { - config.setUnit(childNode.getTextContent()); - } - else if (childName.equals("valueType")) { - String valueTypeString = childNode.getTextContent().toUpperCase(); - - try { - config.valueType = ValueType.valueOf(valueTypeString); - } catch (IllegalArgumentException e) { - throw new ParseException("found unknown channel value type:" + valueTypeString); - } - - if (config.valueType == ValueType.BYTE_ARRAY || config.valueType == ValueType.STRING) { - String valueTypeLengthString = getAttributeValue(childNode, "length"); - if (valueTypeLengthString == null) { - throw new ParseException("length of " + config.valueType.toString() - + " value type was not specified"); - } - config.valueTypeLength = timeStringToMillis(valueTypeLengthString); - } - - } - else if (childName.equals("scalingFactor")) { - config.setScalingFactor(Double.parseDouble(childNode.getTextContent())); - } - else if (childName.equals("valueOffset")) { - config.setValueOffset(Double.parseDouble(childNode.getTextContent())); - } - else if (childName.equals("listening")) { - String listeningString = childNode.getTextContent().toLowerCase(); - if (listeningString.equals("true")) { - config.setListening(true); - } - else if (listeningString.equals("false")) { - config.setListening(false); - } - else { - throw new ParseException("\"listening\" tag contains neither \"true\" nor \"false\""); - } - } - else if (childName.equals("samplingInterval")) { - config.setSamplingInterval(timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("samplingTimeOffset")) { - config.setSamplingTimeOffset(timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("samplingGroup")) { - config.setSamplingGroup(childNode.getTextContent()); - } - else if (childName.equals("loggingInterval")) { - config.setLoggingInterval(timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("loggingTimeOffset")) { - config.setLoggingTimeOffset(timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("disabled")) { - String disabledString = childNode.getTextContent().toLowerCase(); - if (disabledString.equals("true")) { - config.setDisabled(true); - } - else if (disabledString.equals("false")) { - config.setDisabled(false); - } - else { - throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); - } - } - else { - throw new ParseException("found unknown tag:" + childName); - } - } - } catch (IllegalArgumentException e) { - throw new ParseException(e); - } catch (IllegalStateException e) { - throw new ParseException(e); - } - } - - Element getDomElement(Document document) { - Element parentElement = document.createElement("channel"); - parentElement.setAttribute("id", id); - - Element childElement; - - if (description != null) { - childElement = document.createElement("description"); - childElement.setTextContent(description); - parentElement.appendChild(childElement); - } - - if (channelAddress != null) { - childElement = document.createElement("channelAddress"); - childElement.setTextContent(channelAddress); - parentElement.appendChild(childElement); - } - - if (serverMappings != null) { - for (ServerMapping serverMapping : serverMappings) { - childElement = document.createElement("serverMapping"); - childElement.setAttribute("id", serverMapping.getId()); - childElement.setTextContent(serverMapping.getServerAddress()); - parentElement.appendChild(childElement); - } - } - - if (unit != null) { - childElement = document.createElement("unit"); - childElement.setTextContent(unit); - parentElement.appendChild(childElement); - } - - if (valueType != null) { - childElement = document.createElement("valueType"); - childElement.setTextContent(valueType.toString()); - - if (valueType == ValueType.BYTE_ARRAY || valueType == ValueType.STRING) { - childElement.setAttribute("length", valueTypeLength.toString()); - } - parentElement.appendChild(childElement); - } - - if (scalingFactor != null) { - childElement = document.createElement("scalingFactor"); - childElement.setTextContent(Double.toString(scalingFactor)); - parentElement.appendChild(childElement); - } - - if (valueOffset != null) { - childElement = document.createElement("valueOffset"); - childElement.setTextContent(Double.toString(valueOffset)); - parentElement.appendChild(childElement); - } - - if (listening != null) { - childElement = document.createElement("listening"); - if (listening) { - childElement.setTextContent("true"); - } - else { - childElement.setTextContent("false"); - } - parentElement.appendChild(childElement); - } - - if (samplingInterval != null) { - childElement = document.createElement("samplingInterval"); - childElement.setTextContent(millisToTimeString(samplingInterval)); - parentElement.appendChild(childElement); - } - - if (samplingTimeOffset != null) { - childElement = document.createElement("samplingTimeOffset"); - childElement.setTextContent(millisToTimeString(samplingTimeOffset)); - parentElement.appendChild(childElement); - } - - if (samplingGroup != null) { - childElement = document.createElement("samplingGroup"); - childElement.setTextContent(samplingGroup); - parentElement.appendChild(childElement); - } - - if (loggingInterval != null) { - childElement = document.createElement("loggingInterval"); - childElement.setTextContent(millisToTimeString(loggingInterval)); - parentElement.appendChild(childElement); - } - - if (loggingTimeOffset != null) { - childElement = document.createElement("loggingTimeOffset"); - childElement.setTextContent(millisToTimeString(loggingTimeOffset)); - parentElement.appendChild(childElement); - } - - if (disabled != null) { - childElement = document.createElement("disabled"); - if (disabled) { - childElement.setTextContent("true"); - } - else { - childElement.setTextContent("false"); - } - parentElement.appendChild(childElement); - } - - return parentElement; - } - - ChannelConfigImpl clone(DeviceConfigImpl clonedParentConfig) { - ChannelConfigImpl configClone = new ChannelConfigImpl(id, clonedParentConfig); - - configClone.description = description; - configClone.channelAddress = channelAddress; - configClone.serverMappings = serverMappings; - configClone.unit = unit; - configClone.valueType = valueType; - configClone.valueTypeLength = valueTypeLength; - configClone.scalingFactor = scalingFactor; - configClone.valueOffset = valueOffset; - configClone.listening = listening; - configClone.samplingInterval = samplingInterval; - configClone.samplingTimeOffset = samplingTimeOffset; - configClone.samplingGroup = samplingGroup; - configClone.loggingInterval = loggingInterval; - configClone.loggingTimeOffset = loggingTimeOffset; - configClone.disabled = disabled; - - return configClone; - } - - ChannelConfigImpl cloneWithDefaults(DeviceConfigImpl clonedParentConfig) { - ChannelConfigImpl configClone = new ChannelConfigImpl(id, clonedParentConfig); - - if (description == null) { - configClone.description = ChannelConfig.DESCRIPTION_DEFAULT; - } - else { - configClone.description = description; - } - - if (channelAddress == null) { - configClone.channelAddress = CHANNEL_ADDRESS_DEFAULT; - } - else { - configClone.channelAddress = channelAddress; - } - - if (serverMappings == null) { - configClone.serverMappings = new ArrayList(); - } - else { - configClone.serverMappings = serverMappings; - } - - if (unit == null) { - configClone.unit = ChannelConfig.UNIT_DEFAULT; - } - else { - configClone.unit = unit; - } - - if (valueType == null) { - configClone.valueType = ChannelConfig.VALUE_TYPE_DEFAULT; - } - else { - configClone.valueType = valueType; - } - - if (valueTypeLength == null) { - if (valueType == ValueType.DOUBLE) { - configClone.valueTypeLength = 8; - } - else if (valueType == ValueType.BYTE_ARRAY) { - configClone.valueTypeLength = ChannelConfig.BYTE_ARRAY_SIZE_DEFAULT; - } - else if (valueType == ValueType.STRING) { - configClone.valueTypeLength = ChannelConfig.STRING_SIZE_DEFAULT; - } - else if (valueType == ValueType.BYTE) { - configClone.valueTypeLength = 1; - } - else if (valueType == ValueType.BYTE) { - configClone.valueTypeLength = 1; - } - else if (valueType == ValueType.FLOAT) { - configClone.valueTypeLength = 4; - } - else if (valueType == ValueType.SHORT) { - configClone.valueTypeLength = 2; - } - else if (valueType == ValueType.INTEGER) { - configClone.valueTypeLength = 4; - } - else if (valueType == ValueType.LONG) { - configClone.valueTypeLength = 8; - } - else if (valueType == ValueType.BOOLEAN) { - configClone.valueTypeLength = 1; - } - } - else { - configClone.valueTypeLength = valueTypeLength; - } - - configClone.scalingFactor = scalingFactor; - configClone.valueOffset = valueOffset; - - if (listening == null) { - configClone.listening = ChannelConfig.LISTENING_DEFAULT; - } - else { - configClone.listening = listening; - } - - if (samplingInterval == null) { - configClone.samplingInterval = ChannelConfig.SAMPLING_INTERVAL_DEFAULT; - } - else { - configClone.samplingInterval = samplingInterval; - } - - if (samplingTimeOffset == null) { - configClone.samplingTimeOffset = ChannelConfig.SAMPLING_TIME_OFFSET_DEFAULT; - } - else { - configClone.samplingTimeOffset = samplingTimeOffset; - } - - if (samplingGroup == null) { - configClone.samplingGroup = ChannelConfig.SAMPLING_GROUP_DEFAULT; - } - else { - configClone.samplingGroup = samplingGroup; - } - - if (loggingInterval == null) { - configClone.loggingInterval = ChannelConfig.LOGGING_INTERVAL_DEFAULT; - } - else { - configClone.loggingInterval = loggingInterval; - } - - if (loggingTimeOffset == null) { - configClone.loggingTimeOffset = ChannelConfig.LOGGING_TIME_OFFSET_DEFAULT; - } - else { - configClone.loggingTimeOffset = loggingTimeOffset; - } - - if (disabled == null) { - configClone.disabled = clonedParentConfig.disabled; - } - else { - if (clonedParentConfig.disabled) { - configClone.disabled = false; - } - else { - configClone.disabled = disabled; - } - } - - return configClone; - } - - static String getAttributeValue(Node element, String attributeName) { - NamedNodeMap attributes = element.getAttributes(); - - Node nameAttribute = attributes.getNamedItem(attributeName); - - if (nameAttribute == null) { - return null; - } - return nameAttribute.getTextContent(); - } - - static String millisToTimeString(Integer time) { - if (time == 0) { - return "0"; - } - if ((time % 1000) == 0) { - time /= 1000; - if ((time % 60) == 0) { - time /= 60; - if ((time % 60) == 0) { - return time.toString().concat("h"); - } - return time.toString().concat("m"); - } - return time.toString().concat("s"); - } - return time.toString().concat("ms"); - } - - static int timeStringToMillis(String timeString) throws ParseException { - try { - - char lastChar = timeString.charAt(timeString.length() - 1); - - if (Character.isDigit(lastChar)) { - return Integer.parseInt(timeString); - } - - switch (lastChar) { - case 's': - if (timeString.charAt(timeString.length() - 2) == 'm') { - return Integer.parseInt(timeString.substring(0, timeString.length() - 2)); - } - return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 1000; - case 'm': - return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 60000; - case 'h': - return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 3600000; - default: - throw new ParseException("unknown time string: " + timeString); - } - - } catch (NumberFormatException e) { - throw new ParseException(e); - } - - } - - static void checkIdSyntax(String id) { - if (!id.matches("[a-zA-Z0-9_-]+")) { - throw new IllegalArgumentException( - "Invalid ID: \"" - + id - + "\". An ID may not be the empty string and must contain only ASCII letters, digits, hyphens and underscores."); - } - } - - public boolean isSampling() { - return !disabled && samplingInterval != null && samplingInterval > 0; - } - - @Override - public void addServerMapping(ServerMapping serverMapping) { - if (serverMappings == null) { - serverMappings = new ArrayList(); - } - serverMappings.add(serverMapping); - } - - @Override - public void deleteServerMappings(String id) { - if (serverMappings != null) { - List newMappings = new ArrayList(); - for (ServerMapping serverMapping : serverMappings) { - if (!serverMapping.getId().equals(id)) { - newMappings.add(serverMapping); - } - } - serverMappings = newMappings; - } - } + String id; + String channelAddress = null; + String description = null; + String unit = null; + ValueType valueType = null; + Integer valueTypeLength = null; + Double scalingFactor = null; + Double valueOffset = null; + Boolean listening = null; + Integer samplingInterval = null; + Integer samplingTimeOffset = null; + String samplingGroup = null; + Integer loggingInterval = null; + Integer loggingTimeOffset = null; + Boolean disabled = null; + List serverMappings = null; + + ChannelImpl channel; + DeviceConfigImpl deviceParent; + + ChannelState state; + + ChannelConfigImpl(String id, DeviceConfigImpl deviceParent) { + this.id = id; + this.deviceParent = deviceParent; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) throws IdCollisionException { + if (id == null) { + throw new IllegalArgumentException("The channel ID may not be null"); + } + ChannelConfigImpl.checkIdSyntax(id); + + if (deviceParent.driverParent.rootConfigParent.channelConfigsById.containsKey(id)) { + throw new IdCollisionException("Collision with channel ID:" + id); + } + + deviceParent.channelConfigsById.put(id, deviceParent.channelConfigsById.remove(this.id)); + deviceParent.driverParent.rootConfigParent.channelConfigsById + .put(id, deviceParent.driverParent.rootConfigParent.channelConfigsById.remove(this.id)); + + this.id = id; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getChannelAddress() { + return channelAddress; + } + + @Override + public void setChannelAddress(String address) { + channelAddress = address; + } + + @Override + public String getUnit() { + return unit; + } + + @Override + public void setUnit(String unit) { + this.unit = unit; + } + + @Override + public ValueType getValueType() { + return valueType; + } + + @Override + public void setValueType(ValueType valueType) { + this.valueType = valueType; + } + + @Override + public Integer getValueTypeLength() { + return valueTypeLength; + } + + @Override + public void setValueTypeLength(Integer length) { + valueTypeLength = length; + } + + @Override + public Double getScalingFactor() { + return scalingFactor; + } + + @Override + public void setScalingFactor(Double factor) { + scalingFactor = factor; + } + + @Override + public Double getValueOffset() { + return valueOffset; + } + + @Override + public void setValueOffset(Double offset) { + valueOffset = offset; + } + + @Override + public Boolean isListening() { + return listening; + } + + @Override + public void setListening(Boolean listening) { + if (samplingInterval != null && listening != null && listening && samplingInterval > 0) { + throw new IllegalStateException("Listening may not be enabled while sampling is enabled."); + } + this.listening = listening; + } + + @Override + public Integer getSamplingInterval() { + return samplingInterval; + } + + @Override + public void setSamplingInterval(Integer samplingInterval) { + if (listening != null && samplingInterval != null && listening && samplingInterval > 0) { + throw new IllegalStateException("Sampling may not be enabled while listening is enabled."); + } + this.samplingInterval = samplingInterval; + } + + @Override + public Integer getSamplingTimeOffset() { + return samplingTimeOffset; + } + + @Override + public void setSamplingTimeOffset(Integer samplingTimeOffset) { + if (samplingTimeOffset != null && samplingTimeOffset < 0) { + throw new IllegalArgumentException("The sampling time offset may not be negative."); + } + this.samplingTimeOffset = samplingTimeOffset; + } + + @Override + public String getSamplingGroup() { + return samplingGroup; + } + + @Override + public void setSamplingGroup(String group) { + samplingGroup = group; + } + + @Override + public Integer getLoggingInterval() { + return loggingInterval; + } + + @Override + public void setLoggingInterval(Integer loggingInterval) { + this.loggingInterval = loggingInterval; + } + + @Override + public Integer getLoggingTimeOffset() { + return loggingTimeOffset; + } + + @Override + public void setLoggingTimeOffset(Integer loggingTimeOffset) { + if (loggingTimeOffset != null && loggingTimeOffset < 0) { + throw new IllegalArgumentException("The logging time offset may not be negative."); + } + this.loggingTimeOffset = loggingTimeOffset; + } + + @Override + public Boolean isDisabled() { + return disabled; + } + + @Override + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + @Override + public void delete() { + deviceParent.channelConfigsById.remove(id); + clear(); + } + + @Override + public List getServerMappings() { + if (serverMappings != null) { + return this.serverMappings; + } else { + return new ArrayList(); + } + } + + void clear() { + deviceParent.driverParent.rootConfigParent.channelConfigsById.remove(id); + deviceParent = null; + } + + @Override + public DeviceConfig getDevice() { + return deviceParent; + } + + static void addChannelFromDomNode(Node channelConfigNode, DeviceConfig parentConfig) throws ParseException { + + String id = ChannelConfigImpl.getAttributeValue(channelConfigNode, "id"); + if (id == null) { + throw new ParseException("channel has no id attribute"); + } + + ChannelConfigImpl config; + + try { + config = (ChannelConfigImpl) parentConfig.addChannel(id); + } catch (Exception e) { + throw new ParseException(e); + } + + NodeList channelChildren = channelConfigNode.getChildNodes(); + + try { + for (int i = 0; i < channelChildren.getLength(); i++) { + Node childNode = channelChildren.item(i); + String childName = childNode.getNodeName(); + + if (childName.equals("#text")) { + continue; + } else if (childName.equals("description")) { + config.setDescription(childNode.getTextContent()); + } else if (childName.equals("channelAddress")) { + config.setChannelAddress(childNode.getTextContent()); + } else if (childName.equals("serverMapping")) { + NamedNodeMap attributes = childNode.getAttributes(); + Node nameAttribute = attributes.getNamedItem("id"); + + if (nameAttribute != null) { + config.addServerMapping(new ServerMapping(nameAttribute.getTextContent(), childNode.getTextContent())); + } else { + throw new ParseException("No id attribute specified for serverMapping."); + } + } else if (childName.equals("unit")) { + config.setUnit(childNode.getTextContent()); + } else if (childName.equals("valueType")) { + String valueTypeString = childNode.getTextContent().toUpperCase(); + + try { + config.valueType = ValueType.valueOf(valueTypeString); + } catch (IllegalArgumentException e) { + throw new ParseException("found unknown channel value type:" + valueTypeString); + } + + if (config.valueType == ValueType.BYTE_ARRAY || config.valueType == ValueType.STRING) { + String valueTypeLengthString = getAttributeValue(childNode, "length"); + if (valueTypeLengthString == null) { + throw new ParseException("length of " + config.valueType.toString() + " value type was not specified"); + } + config.valueTypeLength = timeStringToMillis(valueTypeLengthString); + } + + } else if (childName.equals("scalingFactor")) { + config.setScalingFactor(Double.parseDouble(childNode.getTextContent())); + } else if (childName.equals("valueOffset")) { + config.setValueOffset(Double.parseDouble(childNode.getTextContent())); + } else if (childName.equals("listening")) { + String listeningString = childNode.getTextContent().toLowerCase(); + if (listeningString.equals("true")) { + config.setListening(true); + } else if (listeningString.equals("false")) { + config.setListening(false); + } else { + throw new ParseException("\"listening\" tag contains neither \"true\" nor \"false\""); + } + } else if (childName.equals("samplingInterval")) { + config.setSamplingInterval(timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("samplingTimeOffset")) { + config.setSamplingTimeOffset(timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("samplingGroup")) { + config.setSamplingGroup(childNode.getTextContent()); + } else if (childName.equals("loggingInterval")) { + config.setLoggingInterval(timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("loggingTimeOffset")) { + config.setLoggingTimeOffset(timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("disabled")) { + String disabledString = childNode.getTextContent().toLowerCase(); + if (disabledString.equals("true")) { + config.setDisabled(true); + } else if (disabledString.equals("false")) { + config.setDisabled(false); + } else { + throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); + } + } else { + throw new ParseException("found unknown tag:" + childName); + } + } + } catch (IllegalArgumentException e) { + throw new ParseException(e); + } catch (IllegalStateException e) { + throw new ParseException(e); + } + } + + Element getDomElement(Document document) { + Element parentElement = document.createElement("channel"); + parentElement.setAttribute("id", id); + + Element childElement; + + if (description != null) { + childElement = document.createElement("description"); + childElement.setTextContent(description); + parentElement.appendChild(childElement); + } + + if (channelAddress != null) { + childElement = document.createElement("channelAddress"); + childElement.setTextContent(channelAddress); + parentElement.appendChild(childElement); + } + + if (serverMappings != null) { + for (ServerMapping serverMapping : serverMappings) { + childElement = document.createElement("serverMapping"); + childElement.setAttribute("id", serverMapping.getId()); + childElement.setTextContent(serverMapping.getServerAddress()); + parentElement.appendChild(childElement); + } + } + + if (unit != null) { + childElement = document.createElement("unit"); + childElement.setTextContent(unit); + parentElement.appendChild(childElement); + } + + if (valueType != null) { + childElement = document.createElement("valueType"); + childElement.setTextContent(valueType.toString()); + + if (valueType == ValueType.BYTE_ARRAY || valueType == ValueType.STRING) { + childElement.setAttribute("length", valueTypeLength.toString()); + } + parentElement.appendChild(childElement); + } + + if (scalingFactor != null) { + childElement = document.createElement("scalingFactor"); + childElement.setTextContent(Double.toString(scalingFactor)); + parentElement.appendChild(childElement); + } + + if (valueOffset != null) { + childElement = document.createElement("valueOffset"); + childElement.setTextContent(Double.toString(valueOffset)); + parentElement.appendChild(childElement); + } + + if (listening != null) { + childElement = document.createElement("listening"); + if (listening) { + childElement.setTextContent("true"); + } else { + childElement.setTextContent("false"); + } + parentElement.appendChild(childElement); + } + + if (samplingInterval != null) { + childElement = document.createElement("samplingInterval"); + childElement.setTextContent(millisToTimeString(samplingInterval)); + parentElement.appendChild(childElement); + } + + if (samplingTimeOffset != null) { + childElement = document.createElement("samplingTimeOffset"); + childElement.setTextContent(millisToTimeString(samplingTimeOffset)); + parentElement.appendChild(childElement); + } + + if (samplingGroup != null) { + childElement = document.createElement("samplingGroup"); + childElement.setTextContent(samplingGroup); + parentElement.appendChild(childElement); + } + + if (loggingInterval != null) { + childElement = document.createElement("loggingInterval"); + childElement.setTextContent(millisToTimeString(loggingInterval)); + parentElement.appendChild(childElement); + } + + if (loggingTimeOffset != null) { + childElement = document.createElement("loggingTimeOffset"); + childElement.setTextContent(millisToTimeString(loggingTimeOffset)); + parentElement.appendChild(childElement); + } + + if (disabled != null) { + childElement = document.createElement("disabled"); + if (disabled) { + childElement.setTextContent("true"); + } else { + childElement.setTextContent("false"); + } + parentElement.appendChild(childElement); + } + + return parentElement; + } + + ChannelConfigImpl clone(DeviceConfigImpl clonedParentConfig) { + ChannelConfigImpl configClone = new ChannelConfigImpl(id, clonedParentConfig); + + configClone.description = description; + configClone.channelAddress = channelAddress; + configClone.serverMappings = serverMappings; + configClone.unit = unit; + configClone.valueType = valueType; + configClone.valueTypeLength = valueTypeLength; + configClone.scalingFactor = scalingFactor; + configClone.valueOffset = valueOffset; + configClone.listening = listening; + configClone.samplingInterval = samplingInterval; + configClone.samplingTimeOffset = samplingTimeOffset; + configClone.samplingGroup = samplingGroup; + configClone.loggingInterval = loggingInterval; + configClone.loggingTimeOffset = loggingTimeOffset; + configClone.disabled = disabled; + + return configClone; + } + + ChannelConfigImpl cloneWithDefaults(DeviceConfigImpl clonedParentConfig) { + ChannelConfigImpl configClone = new ChannelConfigImpl(id, clonedParentConfig); + + if (description == null) { + configClone.description = ChannelConfig.DESCRIPTION_DEFAULT; + } else { + configClone.description = description; + } + + if (channelAddress == null) { + configClone.channelAddress = CHANNEL_ADDRESS_DEFAULT; + } else { + configClone.channelAddress = channelAddress; + } + + if (serverMappings == null) { + configClone.serverMappings = new ArrayList(); + } else { + configClone.serverMappings = serverMappings; + } + + if (unit == null) { + configClone.unit = ChannelConfig.UNIT_DEFAULT; + } else { + configClone.unit = unit; + } + + if (valueType == null) { + configClone.valueType = ChannelConfig.VALUE_TYPE_DEFAULT; + } else { + configClone.valueType = valueType; + } + + if (valueTypeLength == null) { + if (valueType == ValueType.DOUBLE) { + configClone.valueTypeLength = 8; + } else if (valueType == ValueType.BYTE_ARRAY) { + configClone.valueTypeLength = ChannelConfig.BYTE_ARRAY_SIZE_DEFAULT; + } else if (valueType == ValueType.STRING) { + configClone.valueTypeLength = ChannelConfig.STRING_SIZE_DEFAULT; + } else if (valueType == ValueType.BYTE) { + configClone.valueTypeLength = 1; + } else if (valueType == ValueType.BYTE) { + configClone.valueTypeLength = 1; + } else if (valueType == ValueType.FLOAT) { + configClone.valueTypeLength = 4; + } else if (valueType == ValueType.SHORT) { + configClone.valueTypeLength = 2; + } else if (valueType == ValueType.INTEGER) { + configClone.valueTypeLength = 4; + } else if (valueType == ValueType.LONG) { + configClone.valueTypeLength = 8; + } else if (valueType == ValueType.BOOLEAN) { + configClone.valueTypeLength = 1; + } + } else { + configClone.valueTypeLength = valueTypeLength; + } + + configClone.scalingFactor = scalingFactor; + configClone.valueOffset = valueOffset; + + if (listening == null) { + configClone.listening = ChannelConfig.LISTENING_DEFAULT; + } else { + configClone.listening = listening; + } + + if (samplingInterval == null) { + configClone.samplingInterval = ChannelConfig.SAMPLING_INTERVAL_DEFAULT; + } else { + configClone.samplingInterval = samplingInterval; + } + + if (samplingTimeOffset == null) { + configClone.samplingTimeOffset = ChannelConfig.SAMPLING_TIME_OFFSET_DEFAULT; + } else { + configClone.samplingTimeOffset = samplingTimeOffset; + } + + if (samplingGroup == null) { + configClone.samplingGroup = ChannelConfig.SAMPLING_GROUP_DEFAULT; + } else { + configClone.samplingGroup = samplingGroup; + } + + if (loggingInterval == null) { + configClone.loggingInterval = ChannelConfig.LOGGING_INTERVAL_DEFAULT; + } else { + configClone.loggingInterval = loggingInterval; + } + + if (loggingTimeOffset == null) { + configClone.loggingTimeOffset = ChannelConfig.LOGGING_TIME_OFFSET_DEFAULT; + } else { + configClone.loggingTimeOffset = loggingTimeOffset; + } + + if (disabled == null) { + configClone.disabled = clonedParentConfig.disabled; + } else { + if (clonedParentConfig.disabled) { + configClone.disabled = false; + } else { + configClone.disabled = disabled; + } + } + + return configClone; + } + + static String getAttributeValue(Node element, String attributeName) { + NamedNodeMap attributes = element.getAttributes(); + + Node nameAttribute = attributes.getNamedItem(attributeName); + + if (nameAttribute == null) { + return null; + } + return nameAttribute.getTextContent(); + } + + static String millisToTimeString(Integer time) { + if (time == 0) { + return "0"; + } + if ((time % 1000) == 0) { + time /= 1000; + if ((time % 60) == 0) { + time /= 60; + if ((time % 60) == 0) { + return time.toString().concat("h"); + } + return time.toString().concat("m"); + } + return time.toString().concat("s"); + } + return time.toString().concat("ms"); + } + + static int timeStringToMillis(String timeString) throws ParseException { + try { + + char lastChar = timeString.charAt(timeString.length() - 1); + + if (Character.isDigit(lastChar)) { + return Integer.parseInt(timeString); + } + + switch (lastChar) { + case 's': + if (timeString.charAt(timeString.length() - 2) == 'm') { + return Integer.parseInt(timeString.substring(0, timeString.length() - 2)); + } + return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 1000; + case 'm': + return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 60000; + case 'h': + return Integer.parseInt(timeString.substring(0, timeString.length() - 1)) * 3600000; + default: + throw new ParseException("unknown time string: " + timeString); + } + + } catch (NumberFormatException e) { + throw new ParseException(e); + } + + } + + static void checkIdSyntax(String id) { + if (!id.matches("[a-zA-Z0-9_-]+")) { + throw new IllegalArgumentException( + "Invalid ID: \"" + id + "\". An ID may not be the empty string and must contain only ASCII letters, digits, hyphens and underscores."); + } + } + + public boolean isSampling() { + return !disabled && samplingInterval != null && samplingInterval > 0; + } + + @Override + public void addServerMapping(ServerMapping serverMapping) { + if (serverMappings == null) { + serverMappings = new ArrayList(); + } + serverMappings.add(serverMapping); + } + + @Override + public void deleteServerMappings(String id) { + if (serverMappings != null) { + List newMappings = new ArrayList(); + for (ServerMapping serverMapping : serverMappings) { + if (!serverMapping.getId().equals(id)) { + newMappings.add(serverMapping); + } + } + serverMappings = newMappings; + } + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelImpl.java index 8a773bc6..ea00cbdd 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelImpl.java @@ -21,459 +21,414 @@ package org.openmuc.framework.core.datamanager; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.CountDownLatch; - import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.TypeConversionException; -import org.openmuc.framework.data.Value; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.dataaccess.Channel; -import org.openmuc.framework.dataaccess.ChannelState; -import org.openmuc.framework.dataaccess.DataLoggerNotAvailableException; -import org.openmuc.framework.dataaccess.DeviceState; -import org.openmuc.framework.dataaccess.ReadRecordContainer; -import org.openmuc.framework.dataaccess.RecordListener; -import org.openmuc.framework.dataaccess.WriteValueContainer; +import org.openmuc.framework.data.*; +import org.openmuc.framework.dataaccess.*; import org.openmuc.framework.datalogger.spi.LogChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.CountDownLatch; + public final class ChannelImpl implements Channel { - private final static Logger logger = LoggerFactory.getLogger(ChannelImpl.class); - - volatile Record latestRecord; - ChannelRecordContainerImpl driverChannel; - volatile ChannelConfigImpl config; - ChannelCollection samplingCollection; - ChannelCollection loggingCollection; - private final Set listeners = new LinkedHashSet(); - private final DataManager dataManager; - volatile Object handle; - private Timer timer = null; - private List futureValues; - - public ChannelImpl(DataManager dataManager, ChannelConfigImpl config, ChannelState initState, Flag initFlag, - long currentTime, List logChannels) { - this.dataManager = dataManager; - this.config = config; - this.futureValues = new ArrayList(); - - if (config.disabled) { - config.state = ChannelState.DISABLED; - latestRecord = new Record(Flag.DISABLED); - } - else if (!config.isListening() && config.samplingInterval < 0) { - config.state = initState; - latestRecord = new Record(Flag.SAMPLING_AND_LISTENING_DISABLED); - } - else { - config.state = initState; - latestRecord = new Record(null, null, initFlag); - } - - if (config.loggingInterval != ChannelConfig.LOGGING_INTERVAL_DEFAULT) { - dataManager.addToLoggingCollections(this, currentTime); - logChannels.add(config); - } - } - - @Override - public String getId() { - return config.id; - } - - @Override - public String getChannelAddress() { - return config.channelAddress; - } - - @Override - public String getDescription() { - return config.description; - } - - @Override - public String getUnit() { - return config.unit; - } - - @Override - public ValueType getValueType() { - return config.valueType; - } - - @Override - public double getScalingFactor() { - if (config.scalingFactor == null) { - return 1; - } - return config.scalingFactor; - } - - @Override - public int getSamplingInterval() { - return config.samplingInterval; - } - - @Override - public int getSamplingTimeOffset() { - return config.samplingTimeOffset; - } - - @Override - public int getLoggingInterval() { - return config.loggingInterval; - } - - @Override - public int getLoggingTimeOffset() { - return config.loggingTimeOffset; - } - - @Override - public String getDriverName() { - return config.deviceParent.driverParent.id; - } - - @Override - public String getDeviceAddress() { - return config.deviceParent.deviceAddress; - } - - @Override - public String getDeviceName() { - return config.deviceParent.id; - } - - @Override - public String getDeviceDescription() { - return config.deviceParent.description; - } - - @Override - public ChannelState getChannelState() { - return config.state; - } - - @Override - public DeviceState getDeviceState() { - return config.deviceParent.device.state; - } - - @Override - public void addListener(RecordListener listener) { - synchronized (listeners) { - listeners.add(listener); - } - } - - @Override - public void removeListener(RecordListener listener) { - synchronized (listeners) { - listeners.remove(listener); - } - } - - @Override - public Record getLatestRecord() { - return latestRecord; - } - - @Override - public void setLatestRecord(Record record) { - setNewRecord(record); - } - - @Override - public Record getLoggedRecord(long timestamp) throws DataLoggerNotAvailableException, IOException { - List records = dataManager.getDataLogger().getRecords(config.id, timestamp, timestamp); - if (records.size() > 0) { - return records.get(0); - } - else { - return null; - } - } - - @Override - public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException { - return dataManager.getDataLogger().getRecords(config.id, startTime, System.currentTimeMillis()); - } - - @Override - public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, - IOException { - Long currentTime = System.currentTimeMillis(); - List toReturn = dataManager.getDataLogger().getRecords(config.id, startTime, endTime); - for (Record record : futureValues) { - if (record.getTimestamp() >= currentTime) { - if (record.getTimestamp() <= endTime) { - toReturn.add(record); - } - else { - break; - } - } - } - return toReturn; - } - - Record setNewRecord(Record record) { - - Record convertedRecord = null; - - if (record.getFlag() == Flag.VALID) { - Double scalingFactor = config.scalingFactor; - Double scalingOffset = config.valueOffset; - - if (scalingFactor != null) { - try { - record = new Record(new DoubleValue(record.getValue().asDouble() * scalingFactor), - record.getTimestamp(), record.getFlag()); - } catch (TypeConversionException e) { - logger.error("Unable to apply scaling factor because a TypeConversionError occured.", e); - } - } - if (scalingOffset != null) { - try { - record = new Record(new DoubleValue(record.getValue().asDouble() + scalingOffset), - record.getTimestamp(), record.getFlag()); - } catch (TypeConversionException e) { - logger.error("Unable to apply scaling offset because a TypeConversionError occured.", e); - } - } - - try { - switch (config.valueType) { - case BOOLEAN: - convertedRecord = new Record(new BooleanValue(record.getValue().asBoolean()), - record.getTimestamp(), record.getFlag()); - break; - case BYTE: - convertedRecord = new Record(new ByteValue(record.getValue().asByte()), record.getTimestamp(), - record.getFlag()); - break; - case SHORT: - convertedRecord = new Record(new ShortValue(record.getValue().asShort()), record.getTimestamp(), - record.getFlag()); - break; - case INTEGER: - convertedRecord = new Record(new IntValue(record.getValue().asInt()), record.getTimestamp(), - record.getFlag()); - break; - case LONG: - convertedRecord = new Record(new LongValue(record.getValue().asLong()), record.getTimestamp(), - record.getFlag()); - break; - case FLOAT: - convertedRecord = new Record(new FloatValue(record.getValue().asFloat()), record.getTimestamp(), - record.getFlag()); - break; - case DOUBLE: - convertedRecord = new Record(new DoubleValue(record.getValue().asDouble()), record.getTimestamp(), - record.getFlag()); - break; - case BYTE_ARRAY: - convertedRecord = new Record(new ByteArrayValue(record.getValue().asByteArray()), - record.getTimestamp(), record.getFlag()); - break; - case STRING: - convertedRecord = new Record(new StringValue(record.getValue().toString()), record.getTimestamp(), - record.getFlag()); - break; - } - } catch (TypeConversionException e) { - logger.error("Unable to convert value to configured value type because a TypeConversionError occured.", - e); - convertedRecord = record; - } - - } - else { - convertedRecord = new Record(latestRecord.getValue(), latestRecord.getTimestamp(), record.getFlag()); - } - - latestRecord = convertedRecord; - notifyListeners(); - - return convertedRecord; - } - - private void notifyListeners() { - if (listeners.size() != 0) { - synchronized (listeners) { - for (RecordListener listener : listeners) { - config.deviceParent.device.dataManager.executor - .execute(new ListenerNotifier(listener, latestRecord)); - } - } - } - } - - ChannelRecordContainerImpl createChannelRecordContainer() { - return new ChannelRecordContainerImpl(this); - } - - void setFlag(Flag flag) { - if (flag != latestRecord.getFlag()) { - latestRecord = new Record(latestRecord.getValue(), latestRecord.getTimestamp(), flag); - notifyListeners(); - } - } - - public void setNewDeviceState(ChannelState state, Flag flag) { - if (config.disabled) { - config.state = ChannelState.DISABLED; - setFlag(Flag.DISABLED); - } - else if (!config.isListening() && config.samplingInterval < 0) { - config.state = state; - setFlag(Flag.SAMPLING_AND_LISTENING_DISABLED); - } - else { - config.state = state; - setFlag(flag); - } - } - - @Override - public Flag write(Value value) { - - if (config.deviceParent.driverParent.getId().equals("virtual")) { - setLatestRecord(new Record(value, System.currentTimeMillis())); - return Flag.VALID; - } - - CountDownLatch writeTaskFinishedSignal = new CountDownLatch(1); - WriteValueContainerImpl writeValueContainer = new WriteValueContainerImpl(this); - - Value adjustedValue = value; - - Double valueOffset = config.valueOffset; - Double scalingFactor = config.scalingFactor; - - if (valueOffset != null) { - adjustedValue = new DoubleValue(adjustedValue.asDouble() - valueOffset); - } - if (scalingFactor != null) { - adjustedValue = new DoubleValue(adjustedValue.asDouble() / scalingFactor); - } - writeValueContainer.setValue(adjustedValue); - - List writeValueContainerList = new ArrayList(1); - writeValueContainerList.add(writeValueContainer); - WriteTask writeTask = new WriteTask(dataManager, config.deviceParent.device, writeValueContainerList, - writeTaskFinishedSignal); - synchronized (dataManager.newWriteTasks) { - dataManager.newWriteTasks.add(writeTask); - } - dataManager.interrupt(); - try { - writeTaskFinishedSignal.await(); - } catch (InterruptedException e) { - } - - latestRecord = new Record(value, System.currentTimeMillis(), writeValueContainer.getFlag()); - notifyListeners(); - - return writeValueContainer.getFlag(); - } - - @Override - public synchronized void write(List values) { - this.futureValues = values; - - Collections.sort(values, new Comparator() { - @Override - public int compare(Record o1, Record o2) { - return o1.getTimestamp().compareTo(o2.getTimestamp()); - } - }); - - if (timer != null) { - timer.cancel(); - } - - timer = new Timer("Timer ChannelImpl " + config.getId()); - - long currentTimestamp = System.currentTimeMillis(); - - for (final Record value : futureValues) { - - if ((currentTimestamp - value.getTimestamp()) < 1000l) { - - timer.schedule(new TimerTask() { - @Override - public void run() { - write(value.getValue()); - } - }, new Date(value.getTimestamp())); - } - } - } - - @Override - public Record read() { - CountDownLatch readTaskFinishedSignal = new CountDownLatch(1); - - ChannelRecordContainerImpl readValueContainer = new ChannelRecordContainerImpl(this); - List readValueContainerList = new ArrayList(1); - readValueContainerList.add(readValueContainer); - - ReadTask readTask = new ReadTask(dataManager, config.deviceParent.device, readValueContainerList, - readTaskFinishedSignal); - synchronized (dataManager.newReadTasks) { - dataManager.newReadTasks.add(readTask); - } - dataManager.interrupt(); - - try { - readTaskFinishedSignal.await(); - } catch (InterruptedException e) { - } - - return setNewRecord(readValueContainer.record); - } - - @Override - public boolean isConnected() { - if (config.state == ChannelState.CONNECTED || config.state == ChannelState.SAMPLING - || config.state == ChannelState.LISTENING) { - return true; - } - return false; - } - - @Override - public WriteValueContainer getWriteContainer() { - return new WriteValueContainerImpl(this); - } - - @Override - public ReadRecordContainer getReadContainer() { - return new ChannelRecordContainerImpl(this); - } + private final static Logger logger = LoggerFactory.getLogger(ChannelImpl.class); + + volatile Record latestRecord; + ChannelRecordContainerImpl driverChannel; + volatile ChannelConfigImpl config; + ChannelCollection samplingCollection; + ChannelCollection loggingCollection; + private final Set listeners = new LinkedHashSet(); + private final DataManager dataManager; + volatile Object handle; + private Timer timer = null; + private List futureValues; + + public ChannelImpl(DataManager dataManager, ChannelConfigImpl config, ChannelState initState, Flag initFlag, long currentTime, + List logChannels) { + this.dataManager = dataManager; + this.config = config; + this.futureValues = new ArrayList(); + + if (config.disabled) { + config.state = ChannelState.DISABLED; + latestRecord = new Record(Flag.DISABLED); + } else if (!config.isListening() && config.samplingInterval < 0) { + config.state = initState; + latestRecord = new Record(Flag.SAMPLING_AND_LISTENING_DISABLED); + } else { + config.state = initState; + latestRecord = new Record(null, null, initFlag); + } + + if (config.loggingInterval != ChannelConfig.LOGGING_INTERVAL_DEFAULT) { + dataManager.addToLoggingCollections(this, currentTime); + logChannels.add(config); + } + } + + @Override + public String getId() { + return config.id; + } + + @Override + public String getChannelAddress() { + return config.channelAddress; + } + + @Override + public String getDescription() { + return config.description; + } + + @Override + public String getUnit() { + return config.unit; + } + + @Override + public ValueType getValueType() { + return config.valueType; + } + + @Override + public double getScalingFactor() { + if (config.scalingFactor == null) { + return 1; + } + return config.scalingFactor; + } + + @Override + public int getSamplingInterval() { + return config.samplingInterval; + } + + @Override + public int getSamplingTimeOffset() { + return config.samplingTimeOffset; + } + + @Override + public int getLoggingInterval() { + return config.loggingInterval; + } + + @Override + public int getLoggingTimeOffset() { + return config.loggingTimeOffset; + } + + @Override + public String getDriverName() { + return config.deviceParent.driverParent.id; + } + + @Override + public String getDeviceAddress() { + return config.deviceParent.deviceAddress; + } + + @Override + public String getDeviceName() { + return config.deviceParent.id; + } + + @Override + public String getDeviceDescription() { + return config.deviceParent.description; + } + + @Override + public ChannelState getChannelState() { + return config.state; + } + + @Override + public DeviceState getDeviceState() { + return config.deviceParent.device.state; + } + + @Override + public void addListener(RecordListener listener) { + synchronized (listeners) { + listeners.add(listener); + } + } + + @Override + public void removeListener(RecordListener listener) { + synchronized (listeners) { + listeners.remove(listener); + } + } + + @Override + public Record getLatestRecord() { + return latestRecord; + } + + @Override + public void setLatestRecord(Record record) { + setNewRecord(record); + } + + @Override + public Record getLoggedRecord(long timestamp) throws DataLoggerNotAvailableException, IOException { + List records = dataManager.getDataLogger().getRecords(config.id, timestamp, timestamp); + if (records.size() > 0) { + return records.get(0); + } else { + return null; + } + } + + @Override + public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException { + return dataManager.getDataLogger().getRecords(config.id, startTime, System.currentTimeMillis()); + } + + @Override + public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, IOException { + Long currentTime = System.currentTimeMillis(); + List toReturn = dataManager.getDataLogger().getRecords(config.id, startTime, endTime); + for (Record record : futureValues) { + if (record.getTimestamp() >= currentTime) { + if (record.getTimestamp() <= endTime) { + toReturn.add(record); + } else { + break; + } + } + } + return toReturn; + } + + Record setNewRecord(Record record) { + + Record convertedRecord = null; + + if (record.getFlag() == Flag.VALID) { + Double scalingFactor = config.scalingFactor; + Double scalingOffset = config.valueOffset; + + if (scalingFactor != null) { + try { + record = new Record(new DoubleValue(record.getValue().asDouble() * scalingFactor), record.getTimestamp(), + record.getFlag()); + } catch (TypeConversionException e) { + logger.error("Unable to apply scaling factor because a TypeConversionError occured.", e); + } + } + if (scalingOffset != null) { + try { + record = new Record(new DoubleValue(record.getValue().asDouble() + scalingOffset), record.getTimestamp(), + record.getFlag()); + } catch (TypeConversionException e) { + logger.error("Unable to apply scaling offset because a TypeConversionError occured.", e); + } + } + + try { + switch (config.valueType) { + case BOOLEAN: + convertedRecord = new Record(new BooleanValue(record.getValue().asBoolean()), record.getTimestamp(), + record.getFlag()); + break; + case BYTE: + convertedRecord = new Record(new ByteValue(record.getValue().asByte()), record.getTimestamp(), record.getFlag()); + break; + case SHORT: + convertedRecord = new Record(new ShortValue(record.getValue().asShort()), record.getTimestamp(), record.getFlag()); + break; + case INTEGER: + convertedRecord = new Record(new IntValue(record.getValue().asInt()), record.getTimestamp(), record.getFlag()); + break; + case LONG: + convertedRecord = new Record(new LongValue(record.getValue().asLong()), record.getTimestamp(), record.getFlag()); + break; + case FLOAT: + convertedRecord = new Record(new FloatValue(record.getValue().asFloat()), record.getTimestamp(), record.getFlag()); + break; + case DOUBLE: + convertedRecord = new Record(new DoubleValue(record.getValue().asDouble()), record.getTimestamp(), + record.getFlag()); + break; + case BYTE_ARRAY: + convertedRecord = new Record(new ByteArrayValue(record.getValue().asByteArray()), record.getTimestamp(), + record.getFlag()); + break; + case STRING: + convertedRecord = new Record(new StringValue(record.getValue().toString()), record.getTimestamp(), + record.getFlag()); + break; + } + } catch (TypeConversionException e) { + logger.error("Unable to convert value to configured value type because a TypeConversionError occured.", e); + convertedRecord = record; + } + + } else { + convertedRecord = new Record(latestRecord.getValue(), latestRecord.getTimestamp(), record.getFlag()); + } + + latestRecord = convertedRecord; + notifyListeners(); + + return convertedRecord; + } + + private void notifyListeners() { + if (listeners.size() != 0) { + synchronized (listeners) { + for (RecordListener listener : listeners) { + config.deviceParent.device.dataManager.executor.execute(new ListenerNotifier(listener, latestRecord)); + } + } + } + } + + ChannelRecordContainerImpl createChannelRecordContainer() { + return new ChannelRecordContainerImpl(this); + } + + void setFlag(Flag flag) { + if (flag != latestRecord.getFlag()) { + latestRecord = new Record(latestRecord.getValue(), latestRecord.getTimestamp(), flag); + notifyListeners(); + } + } + + public void setNewDeviceState(ChannelState state, Flag flag) { + if (config.disabled) { + config.state = ChannelState.DISABLED; + setFlag(Flag.DISABLED); + } else if (!config.isListening() && config.samplingInterval < 0) { + config.state = state; + setFlag(Flag.SAMPLING_AND_LISTENING_DISABLED); + } else { + config.state = state; + setFlag(flag); + } + } + + @Override + public Flag write(Value value) { + + if (config.deviceParent.driverParent.getId().equals("virtual")) { + setLatestRecord(new Record(value, System.currentTimeMillis())); + return Flag.VALID; + } + + CountDownLatch writeTaskFinishedSignal = new CountDownLatch(1); + WriteValueContainerImpl writeValueContainer = new WriteValueContainerImpl(this); + + Value adjustedValue = value; + + Double valueOffset = config.valueOffset; + Double scalingFactor = config.scalingFactor; + + if (valueOffset != null) { + adjustedValue = new DoubleValue(adjustedValue.asDouble() - valueOffset); + } + if (scalingFactor != null) { + adjustedValue = new DoubleValue(adjustedValue.asDouble() / scalingFactor); + } + writeValueContainer.setValue(adjustedValue); + + List writeValueContainerList = new ArrayList(1); + writeValueContainerList.add(writeValueContainer); + WriteTask writeTask = new WriteTask(dataManager, config.deviceParent.device, writeValueContainerList, writeTaskFinishedSignal); + synchronized (dataManager.newWriteTasks) { + dataManager.newWriteTasks.add(writeTask); + } + dataManager.interrupt(); + try { + writeTaskFinishedSignal.await(); + } catch (InterruptedException e) { + } + + latestRecord = new Record(value, System.currentTimeMillis(), writeValueContainer.getFlag()); + notifyListeners(); + + return writeValueContainer.getFlag(); + } + + @Override + public synchronized void write(List values) { + this.futureValues = values; + + Collections.sort(values, new Comparator() { + @Override + public int compare(Record o1, Record o2) { + return o1.getTimestamp().compareTo(o2.getTimestamp()); + } + }); + + if (timer != null) { + timer.cancel(); + } + + timer = new Timer("Timer ChannelImpl " + config.getId()); + + long currentTimestamp = System.currentTimeMillis(); + + for (final Record value : futureValues) { + + if ((currentTimestamp - value.getTimestamp()) < 1000l) { + + timer.schedule(new TimerTask() { + @Override + public void run() { + write(value.getValue()); + } + }, new Date(value.getTimestamp())); + } + } + } + + @Override + public Record read() { + CountDownLatch readTaskFinishedSignal = new CountDownLatch(1); + + ChannelRecordContainerImpl readValueContainer = new ChannelRecordContainerImpl(this); + List readValueContainerList = new ArrayList(1); + readValueContainerList.add(readValueContainer); + + ReadTask readTask = new ReadTask(dataManager, config.deviceParent.device, readValueContainerList, readTaskFinishedSignal); + synchronized (dataManager.newReadTasks) { + dataManager.newReadTasks.add(readTask); + } + dataManager.interrupt(); + + try { + readTaskFinishedSignal.await(); + } catch (InterruptedException e) { + } + + return setNewRecord(readValueContainer.record); + } + + @Override + public boolean isConnected() { + if (config.state == ChannelState.CONNECTED || config.state == ChannelState.SAMPLING || config.state == ChannelState.LISTENING) { + return true; + } + return false; + } + + @Override + public WriteValueContainer getWriteContainer() { + return new WriteValueContainerImpl(this); + } + + @Override + public ReadRecordContainer getReadContainer() { + return new ChannelRecordContainerImpl(this); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelRecordContainerImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelRecordContainerImpl.java index d06dc413..ade3c034 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelRecordContainerImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ChannelRecordContainerImpl.java @@ -28,58 +28,58 @@ public final class ChannelRecordContainerImpl implements ChannelRecordContainer { - private static final Record DEFAULT_RECORD = new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); + private static final Record DEFAULT_RECORD = new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); - ChannelImpl channel; - Record record = DEFAULT_RECORD; - Object channelHandle; - String channelAddress; + ChannelImpl channel; + Record record = DEFAULT_RECORD; + Object channelHandle; + String channelAddress; - public ChannelRecordContainerImpl(ChannelImpl channel) { - this.channel = channel; - channelAddress = channel.config.channelAddress; - channelHandle = channel.handle; - } + public ChannelRecordContainerImpl(ChannelImpl channel) { + this.channel = channel; + channelAddress = channel.config.channelAddress; + channelHandle = channel.handle; + } - private ChannelRecordContainerImpl(ChannelImpl channel, Record record) { - this.channel = channel; - channelAddress = channel.config.channelAddress; - channelHandle = channel.handle; - this.record = record; - } + private ChannelRecordContainerImpl(ChannelImpl channel, Record record) { + this.channel = channel; + channelAddress = channel.config.channelAddress; + channelHandle = channel.handle; + this.record = record; + } - @Override - public String getChannelAddress() { - return channelAddress; - } + @Override + public String getChannelAddress() { + return channelAddress; + } - @Override - public Object getChannelHandle() { - return channelHandle; - } + @Override + public Object getChannelHandle() { + return channelHandle; + } - @Override - public void setChannelHandle(Object handle) { - channelHandle = handle; - } + @Override + public void setChannelHandle(Object handle) { + channelHandle = handle; + } - @Override - public void setRecord(Record record) { - this.record = record; - } + @Override + public void setRecord(Record record) { + this.record = record; + } - @Override - public ChannelRecordContainer copy() { - return new ChannelRecordContainerImpl(channel, record); - } + @Override + public ChannelRecordContainer copy() { + return new ChannelRecordContainerImpl(channel, record); + } - @Override - public Channel getChannel() { - return channel; - } + @Override + public Channel getChannel() { + return channel; + } - @Override - public Record getRecord() { - return record; - } + @Override + public Record getRecord() { + return record; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ConnectTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ConnectTask.java index 6006c960..b4d49b5c 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ConnectTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ConnectTask.java @@ -30,69 +30,68 @@ public final class ConnectTask extends DeviceTask { - private final static Logger logger = LoggerFactory.getLogger(ConnectTask.class); + private final static Logger logger = LoggerFactory.getLogger(ConnectTask.class); - public ConnectTask(DriverService driver, Device device, DataManager dataManager) { - this.driver = driver; - this.device = device; - this.dataManager = dataManager; - } + public ConnectTask(DriverService driver, Device device, DataManager dataManager) { + this.driver = driver; + this.device = device; + this.dataManager = dataManager; + } - @Override - public void run() { + @Override + public void run() { - try { - device.connection = driver.connect(device.deviceConfig.deviceAddress, device.deviceConfig.settings); - } catch (ConnectionException e) { - logger.warn("Unable to connect to device {} because {}. Will try again in {}ms.", device.deviceConfig.id, - e.getMessage(), device.deviceConfig.connectRetryInterval); - synchronized (dataManager.connectionFailures) { - dataManager.connectionFailures.add(device); - } - dataManager.interrupt(); - return; - } catch (ArgumentSyntaxException e) { - logger.warn( - "Unable to connect to device {} because the address or settings syntax is incorrect: {}. Will try again in {}ms.", - device.deviceConfig.id, e.getMessage(), device.deviceConfig.connectRetryInterval); - synchronized (dataManager.connectionFailures) { - dataManager.connectionFailures.add(device); - } - dataManager.interrupt(); - return; - } catch (Exception e) { - logger.warn("unexpected exception thrown by connect funtion of driver", e); - synchronized (dataManager.connectionFailures) { - dataManager.connectionFailures.add(device); - } - dataManager.interrupt(); - return; - } + try { + device.connection = driver.connect(device.deviceConfig.deviceAddress, device.deviceConfig.settings); + } catch (ConnectionException e) { + logger.warn("Unable to connect to device {} because {}. Will try again in {}ms.", device.deviceConfig.id, e.getMessage(), + device.deviceConfig.connectRetryInterval); + synchronized (dataManager.connectionFailures) { + dataManager.connectionFailures.add(device); + } + dataManager.interrupt(); + return; + } catch (ArgumentSyntaxException e) { + logger.warn("Unable to connect to device {} because the address or settings syntax is incorrect: {}. Will try again in {}ms.", + device.deviceConfig.id, e.getMessage(), device.deviceConfig.connectRetryInterval); + synchronized (dataManager.connectionFailures) { + dataManager.connectionFailures.add(device); + } + dataManager.interrupt(); + return; + } catch (Exception e) { + logger.warn("unexpected exception thrown by connect funtion of driver", e); + synchronized (dataManager.connectionFailures) { + dataManager.connectionFailures.add(device); + } + dataManager.interrupt(); + return; + } - if (device.connection == null) { - logger.error("Drivers connect() function returned null"); - synchronized (dataManager.connectionFailures) { - dataManager.connectionFailures.add(device); - } - dataManager.interrupt(); - return; - } + if (device.connection == null) { + logger.error("Drivers connect() function returned null"); + synchronized (dataManager.connectionFailures) { + dataManager.connectionFailures.add(device); + } + dataManager.interrupt(); + return; + } - synchronized (dataManager.connected) { - dataManager.connected.add(device); - } - dataManager.interrupt(); + synchronized (dataManager.connected) { + dataManager.connected.add(device); + } + dataManager.interrupt(); - } + } - @Override - public DeviceTaskType getType() { - return DeviceTaskType.CONNECT; - } + @Override + public DeviceTaskType getType() { + return DeviceTaskType.CONNECT; + } - @Override - public void setDeviceState() { - device.state = DeviceState.CONNECTING; - } + @Override + public void setDeviceState() { + device.state = DeviceState.CONNECTING; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DataManager.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DataManager.java index e18ffd29..91db44cb 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DataManager.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DataManager.java @@ -21,1271 +21,1202 @@ package org.openmuc.framework.core.datamanager; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.locks.ReentrantLock; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactoryConfigurationError; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.ConfigChangeListener; -import org.openmuc.framework.config.ConfigService; -import org.openmuc.framework.config.ConfigWriteException; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DeviceScanListener; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.DriverNotAvailableException; -import org.openmuc.framework.config.ParseException; -import org.openmuc.framework.config.RootConfig; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; -import org.openmuc.framework.config.ServerMapping; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.Flag; -import org.openmuc.framework.dataaccess.Channel; -import org.openmuc.framework.dataaccess.ChannelChangeListener; -import org.openmuc.framework.dataaccess.ChannelState; -import org.openmuc.framework.dataaccess.DataAccessService; -import org.openmuc.framework.dataaccess.DataLoggerNotAvailableException; -import org.openmuc.framework.dataaccess.DeviceState; -import org.openmuc.framework.dataaccess.LogicalDevice; -import org.openmuc.framework.dataaccess.LogicalDeviceChangeListener; -import org.openmuc.framework.dataaccess.ReadRecordContainer; -import org.openmuc.framework.dataaccess.WriteValueContainer; +import org.openmuc.framework.dataaccess.*; import org.openmuc.framework.datalogger.spi.DataLoggerService; import org.openmuc.framework.datalogger.spi.LogChannel; import org.openmuc.framework.datalogger.spi.LogRecordContainer; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.DriverDeviceScanListener; -import org.openmuc.framework.driver.spi.DriverService; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; +import org.openmuc.framework.driver.spi.*; import org.openmuc.framework.server.spi.ServerMappingContainer; import org.openmuc.framework.server.spi.ServerService; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.locks.ReentrantLock; + public final class DataManager extends Thread implements DataAccessService, ConfigService, RecordsReceivedListener { - private final static Logger logger = LoggerFactory.getLogger(DataManager.class); + private final static Logger logger = LoggerFactory.getLogger(DataManager.class); - private volatile boolean stopFlag = false; + private volatile boolean stopFlag = false; - private final HashMap newDrivers = new LinkedHashMap(); - private final HashMap serverServices = new HashMap(); - // does not need to be a list because RemovedService() for driver services - // are never called in parallel: - private volatile String driverToBeRemovedId = null; - private volatile DataLoggerService dataLoggerToBeRemoved = null; + private final HashMap newDrivers = new LinkedHashMap(); + private final HashMap serverServices = new HashMap(); + // does not need to be a list because RemovedService() for driver services + // are never called in parallel: + private volatile String driverToBeRemovedId = null; + private volatile DataLoggerService dataLoggerToBeRemoved = null; - final List connected = new LinkedList(); - final List disconnected = new LinkedList(); - final List connectionFailures = new LinkedList(); - final List samplingTaskFinished = new LinkedList(); - final List newWriteTasks = new LinkedList(); - final List newReadTasks = new LinkedList(); - final List tasksFinished = new LinkedList(); - private volatile RootConfigImpl newRootConfigWithoutDefaults = null; - private final HashMap activeDrivers = new LinkedHashMap(); + final List connected = new LinkedList(); + final List disconnected = new LinkedList(); + final List connectionFailures = new LinkedList(); + final List samplingTaskFinished = new LinkedList(); + final List newWriteTasks = new LinkedList(); + final List newReadTasks = new LinkedList(); + final List tasksFinished = new LinkedList(); + private volatile RootConfigImpl newRootConfigWithoutDefaults = null; + private final HashMap activeDrivers = new LinkedHashMap(); - private final List actions = new LinkedList(); - private final List configChangeListeners = new LinkedList(); + private final List actions = new LinkedList(); + private final List configChangeListeners = new LinkedList(); - CountDownLatch dataLoggerRemovedSignal; - private final List newDataLoggers = new LinkedList(); - private final Deque activeDataLoggers = new LinkedBlockingDeque(); + CountDownLatch dataLoggerRemovedSignal; + private final List newDataLoggers = new LinkedList(); + private final Deque activeDataLoggers = new LinkedBlockingDeque(); - private final List> receivedRecordContainers = new LinkedList>(); + private final List> receivedRecordContainers = new LinkedList>(); - volatile int activeDeviceCountDown; + volatile int activeDeviceCountDown; - private volatile RootConfigImpl rootConfig; - private volatile RootConfigImpl rootConfigWithoutDefaults; - - private File configFile; - - ExecutorService executor = null; - - private volatile Boolean dataManagerActivated = false; - - CountDownLatch driverRemovedSignal; - - private CountDownLatch newConfigSignal; - - private final ReentrantLock configLock = new ReentrantLock(); - - protected void activate(ComponentContext context) throws TransformerFactoryConfigurationError, IOException, - ParserConfigurationException, TransformerException, ParseException { - logger.info("Activating Data Manager"); - - executor = Executors.newCachedThreadPool(); - - String configFileName = System.getProperty("org.openmuc.framework.channelconfig"); - if (configFileName == null) { - configFileName = "conf/channels.xml"; - } - configFile = new File(configFileName); - - try { - rootConfigWithoutDefaults = RootConfigImpl.createFromFile(configFile); - } catch (FileNotFoundException e) { - // create an empty configuration and store it in a file - rootConfigWithoutDefaults = new RootConfigImpl(); - rootConfigWithoutDefaults.writeToFile(configFile); - logger.info("No configuration file found. Created an empty config file at: " + configFile.getAbsolutePath()); - } catch (ParseException e) { - throw new ParseException("Error parsing openmuc config file: " + e.getMessage()); - } - - rootConfig = new RootConfigImpl(); - - applyConfiguration(rootConfigWithoutDefaults, System.currentTimeMillis()); - - start(); - - dataManagerActivated = true; - } - - protected void deactivate(ComponentContext context) { - logger.info("Deactivating Data Manager"); - - stopFlag = true; - interrupt(); - try { - this.join(); - executor.shutdown(); - } catch (InterruptedException e) { - } - dataManagerActivated = false; - } - - @Override - public void run() { - - setName("OpenMUC Data Manager"); - handleInterruptEvent(); - - while (!stopFlag) { - - if (interrupted()) { - handleInterruptEvent(); - continue; - } - - if (actions.size() == 0) { - try { - while (true) { - Thread.sleep(Long.MAX_VALUE); - } - } catch (InterruptedException e) { - handleInterruptEvent(); - continue; - } - } - - long sleepTime = 0; - Action currentAction = actions.get(0); - - long currentTime = System.currentTimeMillis(); - - if ((currentTime - currentAction.startTime) > 1000l) { - actions.remove(0); - logger.error("Action was scheduled for unix time " - + currentAction.startTime - + ". But current time is already " - + currentTime - + ". Will calculate new action time because the action has timed out. Has the system clock jumped?"); - if (currentAction.timeouts != null && currentAction.timeouts.size() > 0) { - for (SamplingTask samplingTask : currentAction.timeouts) { - samplingTask.timeout(); - } - } - if (currentAction.loggingCollections != null) { - for (ChannelCollection loggingCollection : currentAction.loggingCollections) { - addLoggingCollectionToActions(loggingCollection, - loggingCollection.calculateNextActionTime(currentTime)); - } - } - if (currentAction.samplingCollections != null) { - for (ChannelCollection samplingCollection : currentAction.samplingCollections) { - addSamplingCollectionToActions(samplingCollection, - samplingCollection.calculateNextActionTime(currentTime)); - } - } - if (currentAction.connectionRetryDevices != null) { - for (Device device : currentAction.connectionRetryDevices) { - addReconnectDeviceToActions(device, currentTime + device.deviceConfig.getConnectRetryInterval()); - } - } - continue; - } - - sleepTime = currentAction.startTime - currentTime; - if (sleepTime > 0) { - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e1) { - handleInterruptEvent(); - continue; - } - } - actions.remove(0); - - if (currentAction.timeouts != null && currentAction.timeouts.size() > 0) { - for (SamplingTask samplingTask : currentAction.timeouts) { - samplingTask.timeout(); - } - } - - if (currentAction.loggingCollections != null && currentAction.loggingCollections.size() > 0) { - - List logContainers = new LinkedList(); - List toRemove = new LinkedList(); - - for (ChannelCollection loggingCollection : currentAction.loggingCollections) { - toRemove.clear(); - for (ChannelImpl channel : loggingCollection.channels) { - if (channel.config.state == ChannelState.DELETED) { - toRemove.add(channel); - } - else if (!channel.config.isDisabled()) { - logContainers.add(new LogRecordContainerImpl(channel.config.id, channel.latestRecord)); - } - } - - for (ChannelImpl channel : toRemove) { - loggingCollection.channels.remove(channel); - } - - if (loggingCollection.channels.size() > 0) { - addLoggingCollectionToActions(loggingCollection, currentAction.startTime - + loggingCollection.interval); - } - } - for (DataLoggerService dataLogger : activeDataLoggers) { - dataLogger.log(logContainers, currentAction.startTime); - } - } - - if (currentAction.connectionRetryDevices != null && currentAction.connectionRetryDevices.size() > 0) { - for (Device device : currentAction.connectionRetryDevices) { - device.connectRetrySignal(); - } - } - - if (currentAction.samplingCollections != null && currentAction.samplingCollections.size() > 0) { - - for (ChannelCollection samplingCollection : currentAction.samplingCollections) { - List selectedChannels = new ArrayList( - samplingCollection.channels.size()); - for (ChannelImpl channel : samplingCollection.channels) { - selectedChannels.add(channel.createChannelRecordContainer()); - } - SamplingTask samplingTask = new SamplingTask(this, samplingCollection.device, selectedChannels, - samplingCollection.samplingGroup); - - int timeout = samplingCollection.device.deviceConfig.samplingTimeout; - - if (samplingCollection.device.addSamplingTask(samplingTask, samplingCollection.interval) - && timeout > 0) { - addSamplingWorkerTimeoutToActions(samplingTask, currentAction.startTime - + samplingCollection.device.deviceConfig.samplingTimeout); - } - - addSamplingCollectionToActions(samplingCollection, currentAction.startTime - + samplingCollection.interval); - } - - } - } - } - - private void addSamplingCollectionToActions(ChannelCollection channelCollection, long startTimestamp) { - - Action fittingAction = null; - - ListIterator actionIterator = actions.listIterator(); - while (actionIterator.hasNext()) { - Action currentAction = actionIterator.next(); - if (currentAction.startTime == startTimestamp) { - fittingAction = currentAction; - if (fittingAction.samplingCollections == null) { - fittingAction.samplingCollections = new LinkedList(); - } - break; - } - else if (currentAction.startTime > startTimestamp) { - fittingAction = new Action(startTimestamp); - fittingAction.samplingCollections = new LinkedList(); - actionIterator.previous(); - actionIterator.add(fittingAction); - break; - } - } - - if (fittingAction == null) { - fittingAction = new Action(startTimestamp); - fittingAction.samplingCollections = new LinkedList(); - actions.add(fittingAction); - } - - fittingAction.samplingCollections.add(channelCollection); - channelCollection.action = fittingAction; - - } - - private void addLoggingCollectionToActions(ChannelCollection channelCollection, long startTimestamp) { - - Action fittingAction = null; - - ListIterator actionIterator = actions.listIterator(); - while (actionIterator.hasNext()) { - Action currentAction = actionIterator.next(); - if (currentAction.startTime == startTimestamp) { - fittingAction = currentAction; - if (fittingAction.loggingCollections == null) { - fittingAction.loggingCollections = new LinkedList(); - } - break; - } - else if (currentAction.startTime > startTimestamp) { - fittingAction = new Action(startTimestamp); - fittingAction.loggingCollections = new LinkedList(); - actionIterator.previous(); - actionIterator.add(fittingAction); - break; - } - } - - if (fittingAction == null) { - fittingAction = new Action(startTimestamp); - fittingAction.loggingCollections = new LinkedList(); - actions.add(fittingAction); - } - - fittingAction.loggingCollections.add(channelCollection); - channelCollection.action = fittingAction; - } - - void addReconnectDeviceToActions(Device device, long startTimestamp) { - Action fittingAction = null; - - ListIterator actionIterator = actions.listIterator(); - while (actionIterator.hasNext()) { - Action currentAction = actionIterator.next(); - if (currentAction.startTime == startTimestamp) { - fittingAction = currentAction; - if (fittingAction.connectionRetryDevices == null) { - fittingAction.connectionRetryDevices = new LinkedList(); - } - break; - } - else if (currentAction.startTime > startTimestamp) { - fittingAction = new Action(startTimestamp); - fittingAction.connectionRetryDevices = new LinkedList(); - actionIterator.previous(); - actionIterator.add(fittingAction); - break; - } - } - - if (fittingAction == null) { - fittingAction = new Action(startTimestamp); - fittingAction.connectionRetryDevices = new LinkedList(); - actions.add(fittingAction); - } - - fittingAction.connectionRetryDevices.add(device); - } - - private void addSamplingWorkerTimeoutToActions(SamplingTask readWorker, long timeout) { - - Action fittingAction = null; - - ListIterator actionIterator = actions.listIterator(); - while (actionIterator.hasNext()) { - Action currentAction = actionIterator.next(); - if (currentAction.startTime == timeout) { - fittingAction = currentAction; - if (fittingAction.timeouts == null) { - fittingAction.timeouts = new LinkedList(); - } - break; - } - else if (currentAction.startTime > timeout) { - fittingAction = new Action(timeout); - fittingAction.timeouts = new LinkedList(); - actionIterator.previous(); - actionIterator.add(fittingAction); - break; - } - } - - if (fittingAction == null) { - fittingAction = new Action(timeout); - fittingAction.timeouts = new LinkedList(); - actions.add(fittingAction); - } - - fittingAction.timeouts.add(readWorker); - } - - private void handleInterruptEvent() { - - if (stopFlag) { - prepareStop(); - return; - } - - long currentTime = 0; - - if (newRootConfigWithoutDefaults != null) { - currentTime = System.currentTimeMillis(); - applyConfiguration(newRootConfigWithoutDefaults, currentTime); - newRootConfigWithoutDefaults = null; - newConfigSignal.countDown(); - } - - synchronized (receivedRecordContainers) { - if (receivedRecordContainers.size() != 0) { - for (List recordContainers : receivedRecordContainers) { - for (ChannelRecordContainer container : recordContainers) { - ChannelRecordContainerImpl containerImpl = (ChannelRecordContainerImpl) container; - if (containerImpl.channel.config.state == ChannelState.LISTENING) { - containerImpl.channel.setNewRecord(containerImpl.record); - } - } - } - } - receivedRecordContainers.clear(); - } - - synchronized (samplingTaskFinished) { - if (samplingTaskFinished.size() != 0) { - for (SamplingTask samplingTask : samplingTaskFinished) { - samplingTask.storeValues(); - samplingTask.device.taskFinished(); - } - samplingTaskFinished.clear(); - } - } - - synchronized (tasksFinished) { - if (tasksFinished.size() != 0) { - for (DeviceTask deviceTask : tasksFinished) { - deviceTask.device.taskFinished(); - } - tasksFinished.clear(); - } - } - - synchronized (newDrivers) { - if (newDrivers.size() != 0) { - // needed to synchronize with getRunningDrivers - synchronized (activeDrivers) { - activeDrivers.putAll(newDrivers); - } - for (Entry newDriverEntry : newDrivers.entrySet()) { - logger.info("Driver registered: " + newDriverEntry.getKey()); - DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(newDriverEntry.getKey()); - if (driverConfig != null) { - driverConfig.activeDriver = newDriverEntry.getValue(); - for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { - deviceConfig.device.driverRegisteredSignal(); - } - } - } - newDrivers.clear(); - } - } - - synchronized (newDataLoggers) { - if (newDataLoggers.size() != 0) { - activeDataLoggers.addAll(newDataLoggers); - for (DataLoggerService dataLogger : newDataLoggers) { - logger.info("Data logger registered: " + dataLogger.getId()); - dataLogger.setChannelsToLog(rootConfig.logChannels); - } - newDataLoggers.clear(); - } - } - - if (driverToBeRemovedId != null) { - - DriverService removedDriverService; - synchronized (activeDrivers) { - removedDriverService = activeDrivers.remove(driverToBeRemovedId); - } - - if (removedDriverService == null) { - // drivers was removed before it was added to activeDrivers - newDrivers.remove(driverToBeRemovedId); - driverRemovedSignal.countDown(); - } - else { - DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(driverToBeRemovedId); - - if (driverConfig != null) { - activeDeviceCountDown = driverConfig.deviceConfigsById.size(); - if (activeDeviceCountDown > 0) { - - // all devices have to be given a chance to finish their current task and disconnect: - for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { - deviceConfig.device.driverDeregisteredSignal(); - } - synchronized (driverRemovedSignal) { - if (activeDeviceCountDown == 0) { - driverRemovedSignal.countDown(); - } - } - } - else { - driverRemovedSignal.countDown(); - } - } - else { - driverRemovedSignal.countDown(); - } - } - driverToBeRemovedId = null; - } - - if (dataLoggerToBeRemoved != null) { - if (activeDataLoggers.remove(dataLoggerToBeRemoved) == false) { - newDataLoggers.remove(dataLoggerToBeRemoved); - } - dataLoggerToBeRemoved = null; - dataLoggerRemovedSignal.countDown(); - } - - synchronized (connectionFailures) { - if (connectionFailures.size() != 0) { - if (currentTime == 0) { - currentTime = System.currentTimeMillis(); - } - for (Device connectionFailureDevice : connectionFailures) { - connectionFailureDevice.connectFailureSignal(currentTime); - } - connectionFailures.clear(); - } - } - - synchronized (connected) { - if (connected.size() != 0) { - if (currentTime == 0) { - currentTime = System.currentTimeMillis(); - } - for (Device connectedDevice : connected) { - connectedDevice.connectedSignal(currentTime); - } - connected.clear(); - } - } - - synchronized (newWriteTasks) { - if (newWriteTasks.size() != 0) { - for (WriteTask newWriteTask : newWriteTasks) { - newWriteTask.device.addWriteTask(newWriteTask); - } - newWriteTasks.clear(); - } - } - - synchronized (newReadTasks) { - if (newReadTasks.size() != 0) { - for (ReadTask newReadTask : newReadTasks) { - newReadTask.device.addReadTask(newReadTask); - } - newReadTasks.clear(); - } - } - - synchronized (disconnected) { - if (disconnected.size() != 0) { - for (Device connectedDevice : disconnected) { - connectedDevice.disconnectedSignal(); - } - disconnected.clear(); - } - } - - } - - private void applyConfiguration(RootConfigImpl configWithoutDefaults, long currentTime) { - - RootConfigImpl newRootConfig = configWithoutDefaults.cloneWithDefaults(); - - List logChannels = new LinkedList(); - - for (DriverConfigImpl oldDriverConfig : rootConfig.driverConfigsById.values()) { - DriverConfigImpl newDriverConfig = newRootConfig.driverConfigsById.get(oldDriverConfig.id); - if (newDriverConfig != null) { - newDriverConfig.activeDriver = oldDriverConfig.activeDriver; - } - for (DeviceConfigImpl oldDeviceConfig : oldDriverConfig.deviceConfigsById.values()) { - DeviceConfigImpl newDeviceConfig = null; - if (newDriverConfig != null) { - newDeviceConfig = newDriverConfig.deviceConfigsById.get(oldDeviceConfig.id); - } - if (newDeviceConfig == null) { - // Device was deleted in new config - oldDeviceConfig.device.deleteSignal(); - } - else { - // Device exists in new and old config - oldDeviceConfig.device.configChangedSignal(newDeviceConfig, currentTime, logChannels); - } - } - } - - for (DriverConfigImpl newDriverConfig : newRootConfig.driverConfigsById.values()) { - DriverConfigImpl oldDriverConfig = rootConfig.driverConfigsById.get(newDriverConfig.id); - if (oldDriverConfig == null) { - newDriverConfig.activeDriver = activeDrivers.get(newDriverConfig.id); - } - for (DeviceConfigImpl newDeviceConfig : newDriverConfig.deviceConfigsById.values()) { - - DeviceConfigImpl oldDeviceConfig = null; - if (oldDriverConfig != null) { - oldDeviceConfig = oldDriverConfig.deviceConfigsById.get(newDeviceConfig.id); - } - - if (oldDeviceConfig == null) { - // Device is new - newDeviceConfig.device = new Device(this, newDeviceConfig, currentTime, logChannels); - if (newDeviceConfig.device.state == DeviceState.CONNECTING) { - newDeviceConfig.device.connectRetrySignal(); - } - } - } - } - - for (ChannelConfigImpl oldChannelConfig : rootConfig.channelConfigsById.values()) { - ChannelConfigImpl newChannelConfig = newRootConfig.channelConfigsById.get(oldChannelConfig.getId()); - if (newChannelConfig == null) { - // oldChannelConfig does not exist in the new configuration - if (oldChannelConfig.state == ChannelState.SAMPLING) { - removeFromSamplingCollections(oldChannelConfig.channel); - } - oldChannelConfig.state = ChannelState.DELETED; - oldChannelConfig.channel.setFlag(Flag.CHANNEL_DELETED); - // note: disabling SampleTasks and such has to be done at the - // Device level - } - - } - - for (DataLoggerService dataLogger : activeDataLoggers) { - dataLogger.setChannelsToLog(logChannels); - } - - newRootConfig.logChannels = logChannels; - - synchronized (configChangeListeners) { - - rootConfig = newRootConfig; - rootConfigWithoutDefaults = configWithoutDefaults; - - for (ConfigChangeListener configChangeListener : configChangeListeners) { - if (configChangeListener != null) { - // TODO this should be done in a separate thread - configChangeListener.configurationChanged(); - } - } - } - - notifyServers(); - } - - void addToSamplingCollections(ChannelImpl channel, Long time) { - - ChannelCollection fittingSamplingCollection = null; - for (Action action : actions) { - if (action.samplingCollections != null) { - for (ChannelCollection samplingCollection : action.samplingCollections) { - if (samplingCollection.interval == channel.config.samplingInterval - && samplingCollection.timeOffset == channel.config.samplingTimeOffset - && samplingCollection.samplingGroup.equals(channel.config.samplingGroup) - && samplingCollection.device == channel.config.deviceParent.device) { - fittingSamplingCollection = samplingCollection; - break; - } - } - } - } - - if (fittingSamplingCollection == null) { - fittingSamplingCollection = new ChannelCollection(channel.config.samplingInterval, - channel.config.samplingTimeOffset, channel.config.samplingGroup, channel.config.deviceParent.device); - addSamplingCollectionToActions(fittingSamplingCollection, - fittingSamplingCollection.calculateNextActionTime(time)); - } - - if (channel.samplingCollection != null) { - if (channel.samplingCollection != fittingSamplingCollection) { - removeFromSamplingCollections(channel); - } - else { - return; - } - } - fittingSamplingCollection.channels.add(channel); - channel.samplingCollection = fittingSamplingCollection; - } - - void addToLoggingCollections(ChannelImpl channel, Long time) { - ChannelCollection fittingLoggingCollection = null; - for (Action action : actions) { - if (action.loggingCollections != null) { - for (ChannelCollection loggingCollection : action.loggingCollections) { - if (loggingCollection.interval == channel.config.loggingInterval - && loggingCollection.timeOffset == channel.config.loggingTimeOffset) { - fittingLoggingCollection = loggingCollection; - break; - } - } - } - } - if (fittingLoggingCollection == null) { - fittingLoggingCollection = new ChannelCollection(channel.config.loggingInterval, - channel.config.loggingTimeOffset, null, null); - addLoggingCollectionToActions(fittingLoggingCollection, - fittingLoggingCollection.calculateNextActionTime(time)); - } - - if (channel.loggingCollection != null) { - if (channel.loggingCollection != fittingLoggingCollection) { - removeFromLoggingCollections(channel); - } - else { - return; - } - } - - fittingLoggingCollection.channels.add(channel); - channel.loggingCollection = fittingLoggingCollection; - } - - void removeFromLoggingCollections(ChannelImpl channel) { - channel.loggingCollection.channels.remove(channel); - if (channel.loggingCollection.channels.size() == 0) { - channel.loggingCollection.action.loggingCollections.remove(channel.loggingCollection); - } - channel.loggingCollection = null; - } - - void removeFromSamplingCollections(ChannelImpl channel) { - channel.samplingCollection.channels.remove(channel); - if (channel.samplingCollection.channels.size() == 0) { - channel.samplingCollection.action.samplingCollections.remove(channel.samplingCollection); - } - channel.samplingCollection = null; - } - - void removeFromConnectionRetry(Device device) { - for (Action action : actions) { - if (action.connectionRetryDevices != null && action.connectionRetryDevices.remove(device)) { - break; - } - } - } - - protected void setDriverService(DriverService driver) { - - String driverId = driver.getInfo().getId(); - - synchronized (newDrivers) { - if (activeDrivers.get(driverId) != null || newDrivers.get(driverId) != null) { - logger.error("Unable to register driver: a driver with the ID " + driverId + " is already registered."); - return; - } - newDrivers.put(driverId, driver); - interrupt(); - } - } - - /** - * Registeres a new ServerService. - * - * @param serverService - */ - protected void setServerService(ServerService serverService) { - String serverId = serverService.getId(); - serverServices.put(serverId, serverService); - - if (dataManagerActivated) { - notifyServer(serverService); - } - - logger.info("Registered Server: " + serverId); - } - - /** - * Removes a registered ServerService. - */ - protected void unsetServerService(ServerService serverService) { - serverServices.remove(serverService.getId()); - } - - /** - * Updates all ServerServices with mapped channels. - */ - protected void notifyServers() { - if (serverServices != null) { - for (ServerService serverService : serverServices.values()) { - notifyServer(serverService); - } - } - } - - /** - * Updates a specified ServerService with mapped channels. - * - * @param serverService - */ - protected void notifyServer(ServerService serverService) { - List relatedServerMappings = new ArrayList(); - - for (ChannelConfig config : rootConfig.channelConfigsById.values()) { - for (ServerMapping serverMapping : config.getServerMappings()) { - if (serverMapping.getId().equals(serverService.getId())) { - relatedServerMappings - .add(new ServerMappingContainer(this.getChannel(config.getId()), serverMapping)); - } - } - } - serverService.serverMappings(relatedServerMappings); - } - - protected void unsetDriverService(DriverService driver) { - - String driverId = driver.getInfo().getId(); - logger.info("Deregistering driver: " + driverId); - - // note: no synchronization needed here because this function and the - // deactivate function are always called sequentially: - if (dataManagerActivated) { - driverToBeRemovedId = driverId; - driverRemovedSignal = new CountDownLatch(1); - interrupt(); - try { - driverRemovedSignal.await(); - } catch (InterruptedException e) { - } - } - else { - if (activeDrivers.remove(driverId) == null) { - newDrivers.remove(driverId); - } - } - logger.info("Driver deregistered: " + driverId); - } - - protected void setDataLoggerService(DataLoggerService dataLogger) { - synchronized (newDataLoggers) { - newDataLoggers.add(dataLogger); - interrupt(); - } - } - - protected void unsetDataLoggerService(DataLoggerService dataLogger) { - - String dataLoggerId = dataLogger.getId(); - logger.info("Deregistering data logger: " + dataLoggerId); - - if (dataManagerActivated) { - dataLoggerRemovedSignal = new CountDownLatch(1); - dataLoggerToBeRemoved = dataLogger; - interrupt(); - try { - dataLoggerRemovedSignal.await(); - } catch (InterruptedException e) { - } - } - else { - if (activeDataLoggers.remove(dataLogger) == false) { - newDataLoggers.remove(dataLogger); - } - } - - logger.info("Data logger deregistered: " + dataLoggerId); - - } - - private void prepareStop() { - // TODO tell all drivers to stop listening - // Do I have to wait for all threads (such as SamplingTasks) to finish? - executor.shutdown(); - } - - @Override - public Channel getChannel(String id) { - ChannelConfigImpl channelConfig = rootConfig.channelConfigsById.get(id); - if (channelConfig == null) { - return null; - } - return channelConfig.channel; - } - - @Override - public Channel getChannel(String id, ChannelChangeListener channelChangeListener) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getLogicalDevices(String type) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getLogicalDevices(String type, LogicalDeviceChangeListener logicalDeviceChangeListener) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void newRecords(List recordContainers) { - List recordContainersCopy = new ArrayList( - recordContainers.size()); - for (ChannelRecordContainer container : recordContainers) { - recordContainersCopy.add(container.copy()); - } - synchronized (receivedRecordContainers) { - receivedRecordContainers.add(recordContainersCopy); - } - - interrupt(); - - } - - @Override - public void connectionInterrupted(String driverId, Connection connection) { - // TODO synchronize here - DriverConfig driverConfig = rootConfig.getDriver(driverId); - if (driverConfig == null) { - return; - } - for (DeviceConfig deviceConfig : driverConfig.getDevices()) { - if (((DeviceConfigImpl) deviceConfig).device.connection == connection) { - Device device = ((DeviceConfigImpl) deviceConfig).device; - logger.info("Connection to device " + device.deviceConfig.id + " was interrupted."); - device.disconnectedSignal(); - return; - } - } - } - - @Override - public void lock() { - configLock.lock(); - } - - @Override - public boolean tryLock() { - return configLock.tryLock(); - } - - @Override - public void unlock() { - configLock.unlock(); - } - - @Override - public RootConfig getConfig() { - return rootConfigWithoutDefaults.clone(); - } - - @Override - public RootConfig getConfig(ConfigChangeListener listener) { - synchronized (configChangeListeners) { - for (ConfigChangeListener weakChangeListener : configChangeListeners) { - configChangeListeners.remove(weakChangeListener); - } - configChangeListeners.add(listener); - return getConfig(); - } - } - - @Override - public void stopListeningForConfigChange(ConfigChangeListener listener) { - synchronized (configChangeListeners) { - for (ConfigChangeListener weakChangeListener : configChangeListeners) { - if (weakChangeListener == listener) { - configChangeListeners.remove(weakChangeListener); - } - } - } - } - - @Override - public void setConfig(RootConfig config) { - configLock.lock(); - try { - RootConfigImpl newConfigCopy = ((RootConfigImpl) config).clone(); - setNewConfig(newConfigCopy); - } finally { - configLock.unlock(); - } - - } - - @Override - public void reloadConfigFromFile() throws FileNotFoundException, ParseException { - configLock.lock(); - try { - RootConfigImpl newConfigCopy = RootConfigImpl.createFromFile(configFile); - setNewConfig(newConfigCopy); - } finally { - configLock.unlock(); - } - - } - - private void setNewConfig(RootConfigImpl newConfigCopy) { - synchronized (this) { - newConfigSignal = new CountDownLatch(1); - newRootConfigWithoutDefaults = newConfigCopy; - interrupt(); - } - while (true) { - try { - newConfigSignal.await(); - break; - } catch (InterruptedException e) { - } - } - - } - - @Override - public RootConfig getEmptyConfig() { - return new RootConfigImpl(); - } - - @Override - public void writeConfigToFile() throws ConfigWriteException { - try { - rootConfigWithoutDefaults.writeToFile(configFile); - } catch (Exception e) { - throw new ConfigWriteException(e); - } - } - - class BlockingScanListener implements DriverDeviceScanListener { - List scanInfos = new ArrayList(); - - @Override - public void scanProgressUpdate(int progress) { - } - - @Override - public void deviceFound(DeviceScanInfo scanInfo) { - if (!scanInfos.contains(scanInfo)) { - scanInfos.add(scanInfo); - } - } - - } - - @Override - public List scanForDevices(String driverId, String settings) throws DriverNotAvailableException, - UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - - DriverService driver = activeDrivers.get(driverId); - if (driver == null) { - throw new DriverNotAvailableException(); - } - - BlockingScanListener blockingScanListener = new BlockingScanListener(); - - driver.scanForDevices(settings, blockingScanListener); - - return blockingScanListener.scanInfos; - - } - - @Override - public void scanForDevices(String driverId, String settings, DeviceScanListener scanListener) - throws DriverNotAvailableException { - DriverService driver = activeDrivers.get(driverId); - if (driver == null) { - throw new DriverNotAvailableException(); - } - executor.execute(new ScanForDevicesTask(driver, settings, scanListener)); - } - - @Override - public void interruptDeviceScan(String driverId) throws DriverNotAvailableException, UnsupportedOperationException { - DriverService driver = activeDrivers.get(driverId); - if (driver == null) { - throw new DriverNotAvailableException(); - } - driver.interruptDeviceScan(); - } - - @Override - public List scanForChannels(String deviceId, String settings) throws DriverNotAvailableException, - UnsupportedOperationException, ArgumentSyntaxException, ScanException { - // TODO this function is probably not thread safe - - DeviceConfigImpl config = (DeviceConfigImpl) rootConfig.getDevice(deviceId); - if (config == null) { - throw new ScanException("No device with ID \"" + deviceId + "\" found."); - } - DriverService activeDriver = activeDrivers.get(config.driverParent.id); - if (activeDriver == null) { - throw new DriverNotAvailableException(); - } - try { - return config.device.connection.scanForChannels(settings); - } catch (ConnectionException e) { - config.device.disconnectedSignal(); - throw new ScanException(e.getMessage(), e); - } - } - - @Override - public List getIdsOfRunningDrivers() { - List availableDrivers; - synchronized (activeDrivers) { - availableDrivers = new ArrayList(activeDrivers.size()); - for (String activeDriverName : activeDrivers.keySet()) { - availableDrivers.add(activeDriverName); - } - } - return availableDrivers; - } - - @Override - public void write(List values) { - HashMap> containersByDevice = new LinkedHashMap>(); - - for (WriteValueContainer value : values) { - if (value.getValue() == null) { - ((WriteValueContainerImpl) value).setFlag(Flag.CANNOT_WRITE_NULL_VALUE); - continue; - } - WriteValueContainerImpl valueContainerImpl = (WriteValueContainerImpl) value; - Device device = valueContainerImpl.channel.config.deviceParent.device; - List writeValueContainers = containersByDevice.get(device); - if (writeValueContainers == null) { - writeValueContainers = new LinkedList(); - containersByDevice.put(device, writeValueContainers); - } - writeValueContainers.add(valueContainerImpl); - } - CountDownLatch writeTasksFinishedSignal = new CountDownLatch(containersByDevice.size()); - - synchronized (newWriteTasks) { - for (Entry> writeValueContainers : containersByDevice.entrySet()) { - WriteTask writeTask = new WriteTask(this, writeValueContainers.getKey(), - writeValueContainers.getValue(), writeTasksFinishedSignal); - newWriteTasks.add(writeTask); - } - } - interrupt(); - - try { - writeTasksFinishedSignal.await(); - } catch (InterruptedException e) { - } - - } - - @Override - public void read(List readContainers) { - Map> containersByDevice = new HashMap>(); - - for (ReadRecordContainer container : readContainers) { - if (container instanceof ChannelRecordContainerImpl == false) { - throw new IllegalArgumentException("Only use ReadRecordContainer created by Channel.getReadContainer()"); - } - - ChannelImpl channel = (ChannelImpl) container.getChannel(); - List containersOfDevice = containersByDevice - .get(channel.config.deviceParent.device); - if (containersOfDevice == null) { - containersOfDevice = new LinkedList(); - containersByDevice.put(channel.config.deviceParent.device, containersOfDevice); - } - containersOfDevice.add((ChannelRecordContainerImpl) container); - } - CountDownLatch readTasksFinishedSignal = new CountDownLatch(containersByDevice.size()); - - synchronized (newReadTasks) { - for (Entry> channelRecordContainers : containersByDevice - .entrySet()) { - ReadTask readTask = new ReadTask(this, channelRecordContainers.getKey(), - channelRecordContainers.getValue(), readTasksFinishedSignal); - newReadTasks.add(readTask); - } - } - interrupt(); - - try { - readTasksFinishedSignal.await(); - } catch (InterruptedException e) { - } - } - - @Override - public List getAllIds() { - List ids = new ArrayList(rootConfig.channelConfigsById.size()); - for (String id : rootConfig.channelConfigsById.keySet()) { - ids.add(id); - } - return ids; - } - - DataLoggerService getDataLogger() throws DataLoggerNotAvailableException { - DataLoggerService dataLogger = activeDataLoggers.peekFirst(); - if (dataLogger == null) { - throw new DataLoggerNotAvailableException(); - } - logger.debug("Accessing logged values using " + dataLogger.getId()); - return dataLogger; - } - - @Override - public DriverInfo getDriverInfo(String driverId) throws DriverNotAvailableException { - DriverService driver = activeDrivers.get(driverId); - if (driver == null) { - throw new DriverNotAvailableException(); - } - - return driver.getInfo(); - } - - @Override - public DeviceState getDeviceState(String deviceId) { - DeviceConfigImpl deviceConfig = (DeviceConfigImpl) rootConfig.getDevice(deviceId); - if (deviceConfig == null) { - return null; - } - return deviceConfig.device.state; - } + private volatile RootConfigImpl rootConfig; + private volatile RootConfigImpl rootConfigWithoutDefaults; + + private File configFile; + + ExecutorService executor = null; + + private volatile Boolean dataManagerActivated = false; + + CountDownLatch driverRemovedSignal; + + private CountDownLatch newConfigSignal; + + private final ReentrantLock configLock = new ReentrantLock(); + + protected void activate(ComponentContext context) throws TransformerFactoryConfigurationError, IOException, + ParserConfigurationException, TransformerException, ParseException { + logger.info("Activating Data Manager"); + + executor = Executors.newCachedThreadPool(); + + String configFileName = System.getProperty("org.openmuc.framework.channelconfig"); + if (configFileName == null) { + configFileName = "conf/channels.xml"; + } + configFile = new File(configFileName); + + try { + rootConfigWithoutDefaults = RootConfigImpl.createFromFile(configFile); + } catch (FileNotFoundException e) { + // create an empty configuration and store it in a file + rootConfigWithoutDefaults = new RootConfigImpl(); + rootConfigWithoutDefaults.writeToFile(configFile); + logger.info("No configuration file found. Created an empty config file at: " + configFile.getAbsolutePath()); + } catch (ParseException e) { + throw new ParseException("Error parsing openmuc config file: " + e.getMessage()); + } + + rootConfig = new RootConfigImpl(); + + applyConfiguration(rootConfigWithoutDefaults, System.currentTimeMillis()); + + start(); + + dataManagerActivated = true; + } + + protected void deactivate(ComponentContext context) { + logger.info("Deactivating Data Manager"); + + stopFlag = true; + interrupt(); + try { + this.join(); + executor.shutdown(); + } catch (InterruptedException e) { + } + dataManagerActivated = false; + } + + @Override + public void run() { + + setName("OpenMUC Data Manager"); + handleInterruptEvent(); + + while (!stopFlag) { + + if (interrupted()) { + handleInterruptEvent(); + continue; + } + + if (actions.size() == 0) { + try { + while (true) { + Thread.sleep(Long.MAX_VALUE); + } + } catch (InterruptedException e) { + handleInterruptEvent(); + continue; + } + } + + long sleepTime = 0; + Action currentAction = actions.get(0); + + long currentTime = System.currentTimeMillis(); + + if ((currentTime - currentAction.startTime) > 1000l) { + actions.remove(0); + logger.error( + "Action was scheduled for unix time " + currentAction.startTime + ". But current time is already " + currentTime + + ". Will calculate new action time because the action has timed out. Has the system clock jumped?"); + if (currentAction.timeouts != null && currentAction.timeouts.size() > 0) { + for (SamplingTask samplingTask : currentAction.timeouts) { + samplingTask.timeout(); + } + } + if (currentAction.loggingCollections != null) { + for (ChannelCollection loggingCollection : currentAction.loggingCollections) { + addLoggingCollectionToActions(loggingCollection, loggingCollection.calculateNextActionTime(currentTime)); + } + } + if (currentAction.samplingCollections != null) { + for (ChannelCollection samplingCollection : currentAction.samplingCollections) { + addSamplingCollectionToActions(samplingCollection, samplingCollection.calculateNextActionTime(currentTime)); + } + } + if (currentAction.connectionRetryDevices != null) { + for (Device device : currentAction.connectionRetryDevices) { + addReconnectDeviceToActions(device, currentTime + device.deviceConfig.getConnectRetryInterval()); + } + } + continue; + } + + sleepTime = currentAction.startTime - currentTime; + if (sleepTime > 0) { + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e1) { + handleInterruptEvent(); + continue; + } + } + actions.remove(0); + + if (currentAction.timeouts != null && currentAction.timeouts.size() > 0) { + for (SamplingTask samplingTask : currentAction.timeouts) { + samplingTask.timeout(); + } + } + + if (currentAction.loggingCollections != null && currentAction.loggingCollections.size() > 0) { + + List logContainers = new LinkedList(); + List toRemove = new LinkedList(); + + for (ChannelCollection loggingCollection : currentAction.loggingCollections) { + toRemove.clear(); + for (ChannelImpl channel : loggingCollection.channels) { + if (channel.config.state == ChannelState.DELETED) { + toRemove.add(channel); + } else if (!channel.config.isDisabled()) { + logContainers.add(new LogRecordContainerImpl(channel.config.id, channel.latestRecord)); + } + } + + for (ChannelImpl channel : toRemove) { + loggingCollection.channels.remove(channel); + } + + if (loggingCollection.channels.size() > 0) { + addLoggingCollectionToActions(loggingCollection, currentAction.startTime + loggingCollection.interval); + } + } + for (DataLoggerService dataLogger : activeDataLoggers) { + dataLogger.log(logContainers, currentAction.startTime); + } + } + + if (currentAction.connectionRetryDevices != null && currentAction.connectionRetryDevices.size() > 0) { + for (Device device : currentAction.connectionRetryDevices) { + device.connectRetrySignal(); + } + } + + if (currentAction.samplingCollections != null && currentAction.samplingCollections.size() > 0) { + + for (ChannelCollection samplingCollection : currentAction.samplingCollections) { + List selectedChannels = new ArrayList( + samplingCollection.channels.size()); + for (ChannelImpl channel : samplingCollection.channels) { + selectedChannels.add(channel.createChannelRecordContainer()); + } + SamplingTask samplingTask = new SamplingTask(this, samplingCollection.device, selectedChannels, + samplingCollection.samplingGroup); + + int timeout = samplingCollection.device.deviceConfig.samplingTimeout; + + if (samplingCollection.device.addSamplingTask(samplingTask, samplingCollection.interval) && timeout > 0) { + addSamplingWorkerTimeoutToActions(samplingTask, + currentAction.startTime + samplingCollection.device.deviceConfig.samplingTimeout); + } + + addSamplingCollectionToActions(samplingCollection, currentAction.startTime + samplingCollection.interval); + } + + } + } + } + + private void addSamplingCollectionToActions(ChannelCollection channelCollection, long startTimestamp) { + + Action fittingAction = null; + + ListIterator actionIterator = actions.listIterator(); + while (actionIterator.hasNext()) { + Action currentAction = actionIterator.next(); + if (currentAction.startTime == startTimestamp) { + fittingAction = currentAction; + if (fittingAction.samplingCollections == null) { + fittingAction.samplingCollections = new LinkedList(); + } + break; + } else if (currentAction.startTime > startTimestamp) { + fittingAction = new Action(startTimestamp); + fittingAction.samplingCollections = new LinkedList(); + actionIterator.previous(); + actionIterator.add(fittingAction); + break; + } + } + + if (fittingAction == null) { + fittingAction = new Action(startTimestamp); + fittingAction.samplingCollections = new LinkedList(); + actions.add(fittingAction); + } + + fittingAction.samplingCollections.add(channelCollection); + channelCollection.action = fittingAction; + + } + + private void addLoggingCollectionToActions(ChannelCollection channelCollection, long startTimestamp) { + + Action fittingAction = null; + + ListIterator actionIterator = actions.listIterator(); + while (actionIterator.hasNext()) { + Action currentAction = actionIterator.next(); + if (currentAction.startTime == startTimestamp) { + fittingAction = currentAction; + if (fittingAction.loggingCollections == null) { + fittingAction.loggingCollections = new LinkedList(); + } + break; + } else if (currentAction.startTime > startTimestamp) { + fittingAction = new Action(startTimestamp); + fittingAction.loggingCollections = new LinkedList(); + actionIterator.previous(); + actionIterator.add(fittingAction); + break; + } + } + + if (fittingAction == null) { + fittingAction = new Action(startTimestamp); + fittingAction.loggingCollections = new LinkedList(); + actions.add(fittingAction); + } + + fittingAction.loggingCollections.add(channelCollection); + channelCollection.action = fittingAction; + } + + void addReconnectDeviceToActions(Device device, long startTimestamp) { + Action fittingAction = null; + + ListIterator actionIterator = actions.listIterator(); + while (actionIterator.hasNext()) { + Action currentAction = actionIterator.next(); + if (currentAction.startTime == startTimestamp) { + fittingAction = currentAction; + if (fittingAction.connectionRetryDevices == null) { + fittingAction.connectionRetryDevices = new LinkedList(); + } + break; + } else if (currentAction.startTime > startTimestamp) { + fittingAction = new Action(startTimestamp); + fittingAction.connectionRetryDevices = new LinkedList(); + actionIterator.previous(); + actionIterator.add(fittingAction); + break; + } + } + + if (fittingAction == null) { + fittingAction = new Action(startTimestamp); + fittingAction.connectionRetryDevices = new LinkedList(); + actions.add(fittingAction); + } + + fittingAction.connectionRetryDevices.add(device); + } + + private void addSamplingWorkerTimeoutToActions(SamplingTask readWorker, long timeout) { + + Action fittingAction = null; + + ListIterator actionIterator = actions.listIterator(); + while (actionIterator.hasNext()) { + Action currentAction = actionIterator.next(); + if (currentAction.startTime == timeout) { + fittingAction = currentAction; + if (fittingAction.timeouts == null) { + fittingAction.timeouts = new LinkedList(); + } + break; + } else if (currentAction.startTime > timeout) { + fittingAction = new Action(timeout); + fittingAction.timeouts = new LinkedList(); + actionIterator.previous(); + actionIterator.add(fittingAction); + break; + } + } + + if (fittingAction == null) { + fittingAction = new Action(timeout); + fittingAction.timeouts = new LinkedList(); + actions.add(fittingAction); + } + + fittingAction.timeouts.add(readWorker); + } + + private void handleInterruptEvent() { + + if (stopFlag) { + prepareStop(); + return; + } + + long currentTime = 0; + + if (newRootConfigWithoutDefaults != null) { + currentTime = System.currentTimeMillis(); + applyConfiguration(newRootConfigWithoutDefaults, currentTime); + newRootConfigWithoutDefaults = null; + newConfigSignal.countDown(); + } + + synchronized (receivedRecordContainers) { + if (receivedRecordContainers.size() != 0) { + for (List recordContainers : receivedRecordContainers) { + for (ChannelRecordContainer container : recordContainers) { + ChannelRecordContainerImpl containerImpl = (ChannelRecordContainerImpl) container; + if (containerImpl.channel.config.state == ChannelState.LISTENING) { + containerImpl.channel.setNewRecord(containerImpl.record); + } + } + } + } + receivedRecordContainers.clear(); + } + + synchronized (samplingTaskFinished) { + if (samplingTaskFinished.size() != 0) { + for (SamplingTask samplingTask : samplingTaskFinished) { + samplingTask.storeValues(); + samplingTask.device.taskFinished(); + } + samplingTaskFinished.clear(); + } + } + + synchronized (tasksFinished) { + if (tasksFinished.size() != 0) { + for (DeviceTask deviceTask : tasksFinished) { + deviceTask.device.taskFinished(); + } + tasksFinished.clear(); + } + } + + synchronized (newDrivers) { + if (newDrivers.size() != 0) { + // needed to synchronize with getRunningDrivers + synchronized (activeDrivers) { + activeDrivers.putAll(newDrivers); + } + for (Entry newDriverEntry : newDrivers.entrySet()) { + logger.info("Driver registered: " + newDriverEntry.getKey()); + DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(newDriverEntry.getKey()); + if (driverConfig != null) { + driverConfig.activeDriver = newDriverEntry.getValue(); + for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { + deviceConfig.device.driverRegisteredSignal(); + } + } + } + newDrivers.clear(); + } + } + + synchronized (newDataLoggers) { + if (newDataLoggers.size() != 0) { + activeDataLoggers.addAll(newDataLoggers); + for (DataLoggerService dataLogger : newDataLoggers) { + logger.info("Data logger registered: " + dataLogger.getId()); + dataLogger.setChannelsToLog(rootConfig.logChannels); + } + newDataLoggers.clear(); + } + } + + if (driverToBeRemovedId != null) { + + DriverService removedDriverService; + synchronized (activeDrivers) { + removedDriverService = activeDrivers.remove(driverToBeRemovedId); + } + + if (removedDriverService == null) { + // drivers was removed before it was added to activeDrivers + newDrivers.remove(driverToBeRemovedId); + driverRemovedSignal.countDown(); + } else { + DriverConfigImpl driverConfig = rootConfig.driverConfigsById.get(driverToBeRemovedId); + + if (driverConfig != null) { + activeDeviceCountDown = driverConfig.deviceConfigsById.size(); + if (activeDeviceCountDown > 0) { + + // all devices have to be given a chance to finish their current task and disconnect: + for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { + deviceConfig.device.driverDeregisteredSignal(); + } + synchronized (driverRemovedSignal) { + if (activeDeviceCountDown == 0) { + driverRemovedSignal.countDown(); + } + } + } else { + driverRemovedSignal.countDown(); + } + } else { + driverRemovedSignal.countDown(); + } + } + driverToBeRemovedId = null; + } + + if (dataLoggerToBeRemoved != null) { + if (activeDataLoggers.remove(dataLoggerToBeRemoved) == false) { + newDataLoggers.remove(dataLoggerToBeRemoved); + } + dataLoggerToBeRemoved = null; + dataLoggerRemovedSignal.countDown(); + } + + synchronized (connectionFailures) { + if (connectionFailures.size() != 0) { + if (currentTime == 0) { + currentTime = System.currentTimeMillis(); + } + for (Device connectionFailureDevice : connectionFailures) { + connectionFailureDevice.connectFailureSignal(currentTime); + } + connectionFailures.clear(); + } + } + + synchronized (connected) { + if (connected.size() != 0) { + if (currentTime == 0) { + currentTime = System.currentTimeMillis(); + } + for (Device connectedDevice : connected) { + connectedDevice.connectedSignal(currentTime); + } + connected.clear(); + } + } + + synchronized (newWriteTasks) { + if (newWriteTasks.size() != 0) { + for (WriteTask newWriteTask : newWriteTasks) { + newWriteTask.device.addWriteTask(newWriteTask); + } + newWriteTasks.clear(); + } + } + + synchronized (newReadTasks) { + if (newReadTasks.size() != 0) { + for (ReadTask newReadTask : newReadTasks) { + newReadTask.device.addReadTask(newReadTask); + } + newReadTasks.clear(); + } + } + + synchronized (disconnected) { + if (disconnected.size() != 0) { + for (Device connectedDevice : disconnected) { + connectedDevice.disconnectedSignal(); + } + disconnected.clear(); + } + } + + } + + private void applyConfiguration(RootConfigImpl configWithoutDefaults, long currentTime) { + + RootConfigImpl newRootConfig = configWithoutDefaults.cloneWithDefaults(); + + List logChannels = new LinkedList(); + + for (DriverConfigImpl oldDriverConfig : rootConfig.driverConfigsById.values()) { + DriverConfigImpl newDriverConfig = newRootConfig.driverConfigsById.get(oldDriverConfig.id); + if (newDriverConfig != null) { + newDriverConfig.activeDriver = oldDriverConfig.activeDriver; + } + for (DeviceConfigImpl oldDeviceConfig : oldDriverConfig.deviceConfigsById.values()) { + DeviceConfigImpl newDeviceConfig = null; + if (newDriverConfig != null) { + newDeviceConfig = newDriverConfig.deviceConfigsById.get(oldDeviceConfig.id); + } + if (newDeviceConfig == null) { + // Device was deleted in new config + oldDeviceConfig.device.deleteSignal(); + } else { + // Device exists in new and old config + oldDeviceConfig.device.configChangedSignal(newDeviceConfig, currentTime, logChannels); + } + } + } + + for (DriverConfigImpl newDriverConfig : newRootConfig.driverConfigsById.values()) { + DriverConfigImpl oldDriverConfig = rootConfig.driverConfigsById.get(newDriverConfig.id); + if (oldDriverConfig == null) { + newDriverConfig.activeDriver = activeDrivers.get(newDriverConfig.id); + } + for (DeviceConfigImpl newDeviceConfig : newDriverConfig.deviceConfigsById.values()) { + + DeviceConfigImpl oldDeviceConfig = null; + if (oldDriverConfig != null) { + oldDeviceConfig = oldDriverConfig.deviceConfigsById.get(newDeviceConfig.id); + } + + if (oldDeviceConfig == null) { + // Device is new + newDeviceConfig.device = new Device(this, newDeviceConfig, currentTime, logChannels); + if (newDeviceConfig.device.state == DeviceState.CONNECTING) { + newDeviceConfig.device.connectRetrySignal(); + } + } + } + } + + for (ChannelConfigImpl oldChannelConfig : rootConfig.channelConfigsById.values()) { + ChannelConfigImpl newChannelConfig = newRootConfig.channelConfigsById.get(oldChannelConfig.getId()); + if (newChannelConfig == null) { + // oldChannelConfig does not exist in the new configuration + if (oldChannelConfig.state == ChannelState.SAMPLING) { + removeFromSamplingCollections(oldChannelConfig.channel); + } + oldChannelConfig.state = ChannelState.DELETED; + oldChannelConfig.channel.setFlag(Flag.CHANNEL_DELETED); + // note: disabling SampleTasks and such has to be done at the + // Device level + } + + } + + for (DataLoggerService dataLogger : activeDataLoggers) { + dataLogger.setChannelsToLog(logChannels); + } + + newRootConfig.logChannels = logChannels; + + synchronized (configChangeListeners) { + + rootConfig = newRootConfig; + rootConfigWithoutDefaults = configWithoutDefaults; + + for (ConfigChangeListener configChangeListener : configChangeListeners) { + if (configChangeListener != null) { + // TODO this should be done in a separate thread + configChangeListener.configurationChanged(); + } + } + } + + notifyServers(); + } + + void addToSamplingCollections(ChannelImpl channel, Long time) { + + ChannelCollection fittingSamplingCollection = null; + for (Action action : actions) { + if (action.samplingCollections != null) { + for (ChannelCollection samplingCollection : action.samplingCollections) { + if (samplingCollection.interval == channel.config.samplingInterval && samplingCollection.timeOffset == channel.config + .samplingTimeOffset && samplingCollection.samplingGroup + .equals(channel.config.samplingGroup) && samplingCollection.device == channel.config.deviceParent.device) { + fittingSamplingCollection = samplingCollection; + break; + } + } + } + } + + if (fittingSamplingCollection == null) { + fittingSamplingCollection = new ChannelCollection(channel.config.samplingInterval, channel.config.samplingTimeOffset, + channel.config.samplingGroup, channel.config.deviceParent.device); + addSamplingCollectionToActions(fittingSamplingCollection, fittingSamplingCollection.calculateNextActionTime(time)); + } + + if (channel.samplingCollection != null) { + if (channel.samplingCollection != fittingSamplingCollection) { + removeFromSamplingCollections(channel); + } else { + return; + } + } + fittingSamplingCollection.channels.add(channel); + channel.samplingCollection = fittingSamplingCollection; + } + + void addToLoggingCollections(ChannelImpl channel, Long time) { + ChannelCollection fittingLoggingCollection = null; + for (Action action : actions) { + if (action.loggingCollections != null) { + for (ChannelCollection loggingCollection : action.loggingCollections) { + if (loggingCollection.interval == channel.config.loggingInterval && loggingCollection.timeOffset == channel.config + .loggingTimeOffset) { + fittingLoggingCollection = loggingCollection; + break; + } + } + } + } + if (fittingLoggingCollection == null) { + fittingLoggingCollection = new ChannelCollection(channel.config.loggingInterval, channel.config.loggingTimeOffset, null, null); + addLoggingCollectionToActions(fittingLoggingCollection, fittingLoggingCollection.calculateNextActionTime(time)); + } + + if (channel.loggingCollection != null) { + if (channel.loggingCollection != fittingLoggingCollection) { + removeFromLoggingCollections(channel); + } else { + return; + } + } + + fittingLoggingCollection.channels.add(channel); + channel.loggingCollection = fittingLoggingCollection; + } + + void removeFromLoggingCollections(ChannelImpl channel) { + channel.loggingCollection.channels.remove(channel); + if (channel.loggingCollection.channels.size() == 0) { + channel.loggingCollection.action.loggingCollections.remove(channel.loggingCollection); + } + channel.loggingCollection = null; + } + + void removeFromSamplingCollections(ChannelImpl channel) { + channel.samplingCollection.channels.remove(channel); + if (channel.samplingCollection.channels.size() == 0) { + channel.samplingCollection.action.samplingCollections.remove(channel.samplingCollection); + } + channel.samplingCollection = null; + } + + void removeFromConnectionRetry(Device device) { + for (Action action : actions) { + if (action.connectionRetryDevices != null && action.connectionRetryDevices.remove(device)) { + break; + } + } + } + + protected void setDriverService(DriverService driver) { + + String driverId = driver.getInfo().getId(); + + synchronized (newDrivers) { + if (activeDrivers.get(driverId) != null || newDrivers.get(driverId) != null) { + logger.error("Unable to register driver: a driver with the ID " + driverId + " is already registered."); + return; + } + newDrivers.put(driverId, driver); + interrupt(); + } + } + + /** + * Registeres a new ServerService. + * + * @param serverService + */ + protected void setServerService(ServerService serverService) { + String serverId = serverService.getId(); + serverServices.put(serverId, serverService); + + if (dataManagerActivated) { + notifyServer(serverService); + } + + logger.info("Registered Server: " + serverId); + } + + /** + * Removes a registered ServerService. + */ + protected void unsetServerService(ServerService serverService) { + serverServices.remove(serverService.getId()); + } + + /** + * Updates all ServerServices with mapped channels. + */ + protected void notifyServers() { + if (serverServices != null) { + for (ServerService serverService : serverServices.values()) { + notifyServer(serverService); + } + } + } + + /** + * Updates a specified ServerService with mapped channels. + * + * @param serverService + */ + protected void notifyServer(ServerService serverService) { + List relatedServerMappings = new ArrayList(); + + for (ChannelConfig config : rootConfig.channelConfigsById.values()) { + for (ServerMapping serverMapping : config.getServerMappings()) { + if (serverMapping.getId().equals(serverService.getId())) { + relatedServerMappings.add(new ServerMappingContainer(this.getChannel(config.getId()), serverMapping)); + } + } + } + serverService.serverMappings(relatedServerMappings); + } + + protected void unsetDriverService(DriverService driver) { + + String driverId = driver.getInfo().getId(); + logger.info("Deregistering driver: " + driverId); + + // note: no synchronization needed here because this function and the + // deactivate function are always called sequentially: + if (dataManagerActivated) { + driverToBeRemovedId = driverId; + driverRemovedSignal = new CountDownLatch(1); + interrupt(); + try { + driverRemovedSignal.await(); + } catch (InterruptedException e) { + } + } else { + if (activeDrivers.remove(driverId) == null) { + newDrivers.remove(driverId); + } + } + logger.info("Driver deregistered: " + driverId); + } + + protected void setDataLoggerService(DataLoggerService dataLogger) { + synchronized (newDataLoggers) { + newDataLoggers.add(dataLogger); + interrupt(); + } + } + + protected void unsetDataLoggerService(DataLoggerService dataLogger) { + + String dataLoggerId = dataLogger.getId(); + logger.info("Deregistering data logger: " + dataLoggerId); + + if (dataManagerActivated) { + dataLoggerRemovedSignal = new CountDownLatch(1); + dataLoggerToBeRemoved = dataLogger; + interrupt(); + try { + dataLoggerRemovedSignal.await(); + } catch (InterruptedException e) { + } + } else { + if (activeDataLoggers.remove(dataLogger) == false) { + newDataLoggers.remove(dataLogger); + } + } + + logger.info("Data logger deregistered: " + dataLoggerId); + + } + + private void prepareStop() { + // TODO tell all drivers to stop listening + // Do I have to wait for all threads (such as SamplingTasks) to finish? + executor.shutdown(); + } + + @Override + public Channel getChannel(String id) { + ChannelConfigImpl channelConfig = rootConfig.channelConfigsById.get(id); + if (channelConfig == null) { + return null; + } + return channelConfig.channel; + } + + @Override + public Channel getChannel(String id, ChannelChangeListener channelChangeListener) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getLogicalDevices(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getLogicalDevices(String type, LogicalDeviceChangeListener logicalDeviceChangeListener) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void newRecords(List recordContainers) { + List recordContainersCopy = new ArrayList(recordContainers.size()); + for (ChannelRecordContainer container : recordContainers) { + recordContainersCopy.add(container.copy()); + } + synchronized (receivedRecordContainers) { + receivedRecordContainers.add(recordContainersCopy); + } + + interrupt(); + + } + + @Override + public void connectionInterrupted(String driverId, Connection connection) { + // TODO synchronize here + DriverConfig driverConfig = rootConfig.getDriver(driverId); + if (driverConfig == null) { + return; + } + for (DeviceConfig deviceConfig : driverConfig.getDevices()) { + if (((DeviceConfigImpl) deviceConfig).device.connection == connection) { + Device device = ((DeviceConfigImpl) deviceConfig).device; + logger.info("Connection to device " + device.deviceConfig.id + " was interrupted."); + device.disconnectedSignal(); + return; + } + } + } + + @Override + public void lock() { + configLock.lock(); + } + + @Override + public boolean tryLock() { + return configLock.tryLock(); + } + + @Override + public void unlock() { + configLock.unlock(); + } + + @Override + public RootConfig getConfig() { + return rootConfigWithoutDefaults.clone(); + } + + @Override + public RootConfig getConfig(ConfigChangeListener listener) { + synchronized (configChangeListeners) { + for (ConfigChangeListener weakChangeListener : configChangeListeners) { + configChangeListeners.remove(weakChangeListener); + } + configChangeListeners.add(listener); + return getConfig(); + } + } + + @Override + public void stopListeningForConfigChange(ConfigChangeListener listener) { + synchronized (configChangeListeners) { + for (ConfigChangeListener weakChangeListener : configChangeListeners) { + if (weakChangeListener == listener) { + configChangeListeners.remove(weakChangeListener); + } + } + } + } + + @Override + public void setConfig(RootConfig config) { + configLock.lock(); + try { + RootConfigImpl newConfigCopy = ((RootConfigImpl) config).clone(); + setNewConfig(newConfigCopy); + } finally { + configLock.unlock(); + } + + } + + @Override + public void reloadConfigFromFile() throws FileNotFoundException, ParseException { + configLock.lock(); + try { + RootConfigImpl newConfigCopy = RootConfigImpl.createFromFile(configFile); + setNewConfig(newConfigCopy); + } finally { + configLock.unlock(); + } + + } + + private void setNewConfig(RootConfigImpl newConfigCopy) { + synchronized (this) { + newConfigSignal = new CountDownLatch(1); + newRootConfigWithoutDefaults = newConfigCopy; + interrupt(); + } + while (true) { + try { + newConfigSignal.await(); + break; + } catch (InterruptedException e) { + } + } + + } + + @Override + public RootConfig getEmptyConfig() { + return new RootConfigImpl(); + } + + @Override + public void writeConfigToFile() throws ConfigWriteException { + try { + rootConfigWithoutDefaults.writeToFile(configFile); + } catch (Exception e) { + throw new ConfigWriteException(e); + } + } + + class BlockingScanListener implements DriverDeviceScanListener { + List scanInfos = new ArrayList(); + + @Override + public void scanProgressUpdate(int progress) { + } + + @Override + public void deviceFound(DeviceScanInfo scanInfo) { + if (!scanInfos.contains(scanInfo)) { + scanInfos.add(scanInfo); + } + } + + } + + @Override + public List scanForDevices(String driverId, String settings) throws DriverNotAvailableException, UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { + + DriverService driver = activeDrivers.get(driverId); + if (driver == null) { + throw new DriverNotAvailableException(); + } + + BlockingScanListener blockingScanListener = new BlockingScanListener(); + + driver.scanForDevices(settings, blockingScanListener); + + return blockingScanListener.scanInfos; + + } + + @Override + public void scanForDevices(String driverId, String settings, DeviceScanListener scanListener) throws DriverNotAvailableException { + DriverService driver = activeDrivers.get(driverId); + if (driver == null) { + throw new DriverNotAvailableException(); + } + executor.execute(new ScanForDevicesTask(driver, settings, scanListener)); + } + + @Override + public void interruptDeviceScan(String driverId) throws DriverNotAvailableException, UnsupportedOperationException { + DriverService driver = activeDrivers.get(driverId); + if (driver == null) { + throw new DriverNotAvailableException(); + } + driver.interruptDeviceScan(); + } + + @Override + public List scanForChannels(String deviceId, String settings) throws DriverNotAvailableException, UnsupportedOperationException, ArgumentSyntaxException, ScanException { + // TODO this function is probably not thread safe + + DeviceConfigImpl config = (DeviceConfigImpl) rootConfig.getDevice(deviceId); + if (config == null) { + throw new ScanException("No device with ID \"" + deviceId + "\" found."); + } + DriverService activeDriver = activeDrivers.get(config.driverParent.id); + if (activeDriver == null) { + throw new DriverNotAvailableException(); + } + try { + return config.device.connection.scanForChannels(settings); + } catch (ConnectionException e) { + config.device.disconnectedSignal(); + throw new ScanException(e.getMessage(), e); + } + } + + @Override + public List getIdsOfRunningDrivers() { + List availableDrivers; + synchronized (activeDrivers) { + availableDrivers = new ArrayList(activeDrivers.size()); + for (String activeDriverName : activeDrivers.keySet()) { + availableDrivers.add(activeDriverName); + } + } + return availableDrivers; + } + + @Override + public void write(List values) { + HashMap> containersByDevice = new LinkedHashMap>(); + + for (WriteValueContainer value : values) { + if (value.getValue() == null) { + ((WriteValueContainerImpl) value).setFlag(Flag.CANNOT_WRITE_NULL_VALUE); + continue; + } + WriteValueContainerImpl valueContainerImpl = (WriteValueContainerImpl) value; + Device device = valueContainerImpl.channel.config.deviceParent.device; + List writeValueContainers = containersByDevice.get(device); + if (writeValueContainers == null) { + writeValueContainers = new LinkedList(); + containersByDevice.put(device, writeValueContainers); + } + writeValueContainers.add(valueContainerImpl); + } + CountDownLatch writeTasksFinishedSignal = new CountDownLatch(containersByDevice.size()); + + synchronized (newWriteTasks) { + for (Entry> writeValueContainers : containersByDevice.entrySet()) { + WriteTask writeTask = new WriteTask(this, writeValueContainers.getKey(), writeValueContainers.getValue(), + writeTasksFinishedSignal); + newWriteTasks.add(writeTask); + } + } + interrupt(); + + try { + writeTasksFinishedSignal.await(); + } catch (InterruptedException e) { + } + + } + + @Override + public void read(List readContainers) { + Map> containersByDevice = new HashMap>(); + + for (ReadRecordContainer container : readContainers) { + if (container instanceof ChannelRecordContainerImpl == false) { + throw new IllegalArgumentException("Only use ReadRecordContainer created by Channel.getReadContainer()"); + } + + ChannelImpl channel = (ChannelImpl) container.getChannel(); + List containersOfDevice = containersByDevice.get(channel.config.deviceParent.device); + if (containersOfDevice == null) { + containersOfDevice = new LinkedList(); + containersByDevice.put(channel.config.deviceParent.device, containersOfDevice); + } + containersOfDevice.add((ChannelRecordContainerImpl) container); + } + CountDownLatch readTasksFinishedSignal = new CountDownLatch(containersByDevice.size()); + + synchronized (newReadTasks) { + for (Entry> channelRecordContainers : containersByDevice.entrySet()) { + ReadTask readTask = new ReadTask(this, channelRecordContainers.getKey(), channelRecordContainers.getValue(), + readTasksFinishedSignal); + newReadTasks.add(readTask); + } + } + interrupt(); + + try { + readTasksFinishedSignal.await(); + } catch (InterruptedException e) { + } + } + + @Override + public List getAllIds() { + List ids = new ArrayList(rootConfig.channelConfigsById.size()); + for (String id : rootConfig.channelConfigsById.keySet()) { + ids.add(id); + } + return ids; + } + + DataLoggerService getDataLogger() throws DataLoggerNotAvailableException { + DataLoggerService dataLogger = activeDataLoggers.peekFirst(); + if (dataLogger == null) { + throw new DataLoggerNotAvailableException(); + } + logger.debug("Accessing logged values using " + dataLogger.getId()); + return dataLogger; + } + + @Override + public DriverInfo getDriverInfo(String driverId) throws DriverNotAvailableException { + DriverService driver = activeDrivers.get(driverId); + if (driver == null) { + throw new DriverNotAvailableException(); + } + + return driver.getInfo(); + } + + @Override + public DeviceState getDeviceState(String deviceId) { + DeviceConfigImpl deviceConfig = (DeviceConfigImpl) rootConfig.getDevice(deviceId); + if (deviceConfig == null) { + return null; + } + return deviceConfig.device.state; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Device.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Device.java index 61bef59b..56a5958a 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Device.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/Device.java @@ -21,12 +21,6 @@ package org.openmuc.framework.core.datamanager; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; - import org.openmuc.framework.config.ChannelConfig; import org.openmuc.framework.data.Flag; import org.openmuc.framework.dataaccess.ChannelState; @@ -36,623 +30,571 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; + public final class Device { - private final static Logger logger = LoggerFactory.getLogger(Device.class); - - DeviceConfigImpl deviceConfig; - DataManager dataManager; - DeviceState state = null; - Connection connection; - - private final List eventList = new ArrayList(); - private final List taskList = new ArrayList(); - - public Device(DataManager dataManager, DeviceConfigImpl deviceConfig, long currentTime, List logChannels) { - this.dataManager = dataManager; - this.deviceConfig = deviceConfig; - - if (deviceConfig.isDisabled()) { - state = DeviceState.DISABLED; - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - channelConfig.channel = new ChannelImpl(dataManager, channelConfig, ChannelState.DISABLED, - Flag.DISABLED, currentTime, logChannels); - } - } - else { - if (deviceConfig.driverParent.activeDriver == null) { - state = DeviceState.DRIVER_UNAVAILABLE; - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - channelConfig.channel = new ChannelImpl(dataManager, channelConfig, - ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); - } - } - else { - state = DeviceState.CONNECTING; - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - channelConfig.channel = new ChannelImpl(dataManager, channelConfig, ChannelState.CONNECTING, - Flag.CONNECTING, currentTime, logChannels); - } - } - } - } - - public void configChangedSignal(DeviceConfigImpl newDeviceConfig, long currentTime, List logChannels) { - DeviceConfigImpl oldDeviceConfig = deviceConfig; - deviceConfig = newDeviceConfig; - newDeviceConfig.device = this; - - if (state == DeviceState.DISABLED) { - if (newDeviceConfig.isDisabled()) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, - currentTime, logChannels); - } - else { - if (deviceConfig.driverParent.activeDriver == null) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DRIVER_UNAVAILABLE, - ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); - } - else { - setStatesForNewDevice(oldDeviceConfig, DeviceState.CONNECTING, ChannelState.CONNECTING, - Flag.CONNECTING, currentTime, logChannels); - connect(); - } - } - } - else if (state == DeviceState.DRIVER_UNAVAILABLE) { - if (newDeviceConfig.isDisabled()) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, - currentTime, logChannels); - } - else { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, - Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); - } - } - else if (state == DeviceState.CONNECTING) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING, - currentTime, logChannels); - if (newDeviceConfig.isDisabled()) { - addEvent(DeviceEvent.DISABLED); - } - else if (oldDeviceConfig.isDisabled()) { - eventList.remove(DeviceEvent.DISABLED); - } - } - else if (state == DeviceState.DISCONNECTING) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, - Flag.DISCONNECTING, currentTime, logChannels); - if (newDeviceConfig.isDisabled()) { - addEvent(DeviceEvent.DISABLED); - } - else if (oldDeviceConfig.isDisabled()) { - eventList.remove(DeviceEvent.DISABLED); - } - } - else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { - if (newDeviceConfig.isDisabled()) { - setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, - currentTime, logChannels); - } - else { - setStatesForNewDevice(oldDeviceConfig, DeviceState.WAITING_FOR_CONNECTION_RETRY, - ChannelState.WAITING_FOR_CONNECTION_RETRY, Flag.WAITING_FOR_CONNECTION_RETRY, currentTime, - logChannels); - } - } - else { - if (newDeviceConfig.isDisabled()) { - if (state == DeviceState.CONNECTED) { - eventList.add(DeviceEvent.DISABLED); - // TODO disable all readworkers - setStatesForNewConnectedDevice(oldDeviceConfig, DeviceState.DISCONNECTING, - ChannelState.DISCONNECTING, Flag.DISCONNECTING, currentTime, logChannels); - disconnect(); - } - else { - // Adding the disabled event will automatically disconnect the device as soon as the active task is - // finished - eventList.add(DeviceEvent.DISABLED); - // Update channels anyway to update the log channels - updateChannels(oldDeviceConfig, ChannelState.DISCONNECTING, Flag.DISCONNECTING, currentTime, - logChannels); - } - } - else { - updateChannels(oldDeviceConfig, ChannelState.CONNECTED, Flag.NO_VALUE_RECEIVED_YET, currentTime, - logChannels); - } - } - - } - - private void updateChannels(DeviceConfigImpl oldDeviceConfig, ChannelState channelState, Flag flag, - long currentTime, List logChannels) { - List listeningChannels = null; - for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { - ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); - ChannelConfigImpl newChannelConfig = newChannelConfigEntry.getValue(); - if (oldChannelConfig == null) { - if (newChannelConfig.state != ChannelState.DISABLED) { - if (newChannelConfig.listening == true) { - if (listeningChannels == null) { - listeningChannels = new LinkedList(); - } - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, - ChannelState.LISTENING, Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); - listeningChannels.add(newChannelConfig.channel.createChannelRecordContainer()); - } - else if (newChannelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, - ChannelState.SAMPLING, Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); - dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); - } - else { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, - currentTime, logChannels); - } - } - else { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, - currentTime, logChannels); - } - } - else { - newChannelConfig.channel = oldChannelConfig.channel; - newChannelConfig.channel.config = newChannelConfig; - newChannelConfig.channel.setNewDeviceState(oldChannelConfig.state, - newChannelConfig.channel.latestRecord.getFlag()); - if (!newChannelConfig.isDisabled() && (newChannelConfig.loggingInterval > 0)) { - dataManager.addToLoggingCollections(newChannelConfig.channel, currentTime); - logChannels.add(newChannelConfig); - } - else if (!oldChannelConfig.disabled && oldChannelConfig.loggingInterval > 0) { - dataManager.removeFromLoggingCollections(newChannelConfig.channel); - } - if (newChannelConfig.isSampling()) { - dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); - } - else if (oldChannelConfig.isSampling()) { - dataManager.removeFromSamplingCollections(newChannelConfig.channel); - } - if (!newChannelConfig.channelAddress.equals(oldChannelConfig.channelAddress)) { - newChannelConfig.channel.handle = null; - } - } - } - - if (listeningChannels != null) { - addStartListeningTask(new StartListeningTask(dataManager, this, listeningChannels)); - } - } - - private void addEvent(DeviceEvent event) { - Iterator i = eventList.iterator(); - while (i.hasNext()) { - if (i.next() == event) { - return; - } - } - eventList.add(event); - } - - private void setStatesForNewDevice(DeviceConfigImpl oldDeviceConfig, DeviceState DeviceState, - ChannelState channelState, Flag flag, long currentTime, List logChannels) { - state = DeviceState; - for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { - ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); - if (oldChannelConfig == null) { - newChannelConfigEntry.getValue().channel = new ChannelImpl(dataManager, - newChannelConfigEntry.getValue(), channelState, flag, currentTime, logChannels); - } - else { - newChannelConfigEntry.getValue().channel = oldChannelConfig.channel; - newChannelConfigEntry.getValue().channel.config = newChannelConfigEntry.getValue(); - newChannelConfigEntry.getValue().channel.setNewDeviceState(channelState, flag); - if (!newChannelConfigEntry.getValue().isDisabled() - && (newChannelConfigEntry.getValue().loggingInterval > 0)) { - dataManager.addToLoggingCollections(newChannelConfigEntry.getValue().channel, currentTime); - logChannels.add(newChannelConfigEntry.getValue()); - } - } - } - } - - private void setStatesForNewConnectedDevice(DeviceConfigImpl oldDeviceConfig, DeviceState DeviceState, - ChannelState channelState, Flag flag, long currentTime, List logChannels) { - state = DeviceState; - List listeningChannels = null; - for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { - ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); - ChannelConfigImpl newChannelConfig = newChannelConfigEntry.getValue(); - if (oldChannelConfig == null) { - if (newChannelConfig.state != ChannelState.DISABLED) { - if (newChannelConfig.listening == true) { - if (listeningChannels == null) { - listeningChannels = new LinkedList(); - } - listeningChannels.add(newChannelConfig.channel.createChannelRecordContainer()); - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, - ChannelState.LISTENING, Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); - } - else if (newChannelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, - ChannelState.SAMPLING, Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); - dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); - } - else { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, - currentTime, logChannels); - } - } - else { - newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, - currentTime, logChannels); - } - } - else { - newChannelConfig.channel = oldChannelConfig.channel; - newChannelConfig.channel.config = newChannelConfig; - newChannelConfig.channel.setNewDeviceState(channelState, flag); - if (!newChannelConfigEntry.getValue().isDisabled() - && (newChannelConfigEntry.getValue().loggingInterval > 0)) { - dataManager.addToLoggingCollections(newChannelConfig.channel, currentTime); - logChannels.add(newChannelConfigEntry.getValue()); - } - } - } - - } - - private void setStates(DeviceState DeviceState, ChannelState channelState, Flag flag) { - state = DeviceState; - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - if (channelConfig.state != ChannelState.DISABLED) { - channelConfig.state = channelState; - if (channelConfig.channel.latestRecord.getFlag() != Flag.SAMPLING_AND_LISTENING_DISABLED) { - channelConfig.channel.setFlag(flag); - } - } - } - } - - void driverRegisteredSignal() { - - if (state == DeviceState.DRIVER_UNAVAILABLE) { - setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); - connect(); - } - else if (state == DeviceState.DISCONNECTING) { - eventList.add(DeviceEvent.DRIVER_REGISTERED); - } - } - - void driverDeregisteredSignal() { - - if (state == DeviceState.DISABLED) { - dataManager.activeDeviceCountDown--; - if (dataManager.activeDeviceCountDown == 0) { - dataManager.driverRemovedSignal.countDown(); - } - } - else if (state == DeviceState.CONNECTED) { - - eventList.add(0, DeviceEvent.DRIVER_DEREGISTERED); - - disableSampling(); - removeAllTasksOfThisDevice(); - setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); - disconnect(); - } - else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { - disableConnectionRetry(); - setStates(DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE); - dataManager.activeDeviceCountDown--; - if (dataManager.activeDeviceCountDown == 0) { - dataManager.driverRemovedSignal.countDown(); - } - } - else { - // add driver deregistered event always to the front of the queue - eventList.add(0, DeviceEvent.DRIVER_DEREGISTERED); - } - } - - public void deleteSignal() { - if (state == DeviceState.DRIVER_UNAVAILABLE || state == DeviceState.DISABLED) { - setDeleted(); - } - else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { - disableConnectionRetry(); - setDeleted(); - } - else if (state == DeviceState.CONNECTED) { - eventList.add(DeviceEvent.DELETED); - setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); - disconnect(); - } - else { - eventList.add(DeviceEvent.DELETED); - } - } - - void connectedSignal(long currentTime) { - - taskList.remove(0); - - if (eventList.size() == 0) { - setConnected(currentTime); - executeNextTask(); - } - else { - handleEventQueueWhenConnected(); - } - } - - void connectFailureSignal(long currentTime) { - taskList.remove(0); - if (eventList.size() == 0) { - setStates(DeviceState.WAITING_FOR_CONNECTION_RETRY, ChannelState.WAITING_FOR_CONNECTION_RETRY, - Flag.WAITING_FOR_CONNECTION_RETRY); - dataManager.addReconnectDeviceToActions(this, currentTime + deviceConfig.getConnectRetryInterval()); - removeAllTasksOfThisDevice(); - } - else { - handleEventQueueWhenDisconnected(); - } - } - - // TODO is this function thread save? - public void disconnectedSignal() { - // TODO in rare cases where the RecordsReceivedListener causes the disconnectSignal while a SamplingTask is - // still sampling this could cause problems - synchronized (this) { - removeAllTasksOfThisDevice(); - if (eventList.size() == 0) { - setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); - connect(); - } - else { - handleEventQueueWhenDisconnected(); - } - } - } - - public void connectRetrySignal() { - setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); - connect(); - } - - private void disableConnectionRetry() { - dataManager.removeFromConnectionRetry(this); - } - - private void setDeleted() { - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - channelConfig.state = ChannelState.DELETED; - channelConfig.channel.setFlag(Flag.CHANNEL_DELETED); - channelConfig.channel.handle = null; - } - state = DeviceState.DELETED; - } - - private void disableSampling() { - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - if (channelConfig.state != ChannelState.DISABLED) { - if (channelConfig.state == ChannelState.SAMPLING) { - dataManager.removeFromSamplingCollections(channelConfig.channel); - } - } - } - } - - private void handleEventQueueWhenConnected() { - - removeAllTasksOfThisDevice(); - setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); - disconnect(); - - } - - private void removeAllTasksOfThisDevice() { - Iterator i = taskList.iterator(); - while (i.hasNext()) { - DeviceTask deviceTask = i.next(); - if (deviceTask.device == this) { - i.remove(); - } - } - - if (taskList.size() > 0) { - if (!taskList.get(0).isAlive()) { - taskList.get(0).device.executeNextTask(); - } - } - } - - private void handleEventQueueWhenDisconnected() { - - // DeviceEvent.DRIVER_DEREGISTERED will always be put at position 0 - if (eventList.get(0) == DeviceEvent.DRIVER_DEREGISTERED) { - - synchronized (dataManager.driverRemovedSignal) { - dataManager.activeDeviceCountDown--; - if (dataManager.activeDeviceCountDown == 0) { - dataManager.driverRemovedSignal.countDown(); - } - } - } - - DeviceEvent lastEvent = eventList.get(eventList.size() - 1); - - if (lastEvent == DeviceEvent.DRIVER_DEREGISTERED) { - setStates(DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE); - } - else if (lastEvent == DeviceEvent.DISABLED) { - setStates(DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED); - } - else if (lastEvent == DeviceEvent.DELETED) { - setDeleted(); - } - // TODO handle DeviceEvent.DRIVER_REGISTERED? - - eventList.clear(); - - } - - private void setConnected(long currentTime) { - - List listeningChannels = null; - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - if (channelConfig.state != ChannelState.DISABLED) { - if (channelConfig.listening == true) { - if (listeningChannels == null) { - listeningChannels = new LinkedList(); - } - listeningChannels.add(channelConfig.channel.createChannelRecordContainer()); - channelConfig.state = ChannelState.LISTENING; - channelConfig.channel.setFlag(Flag.NO_VALUE_RECEIVED_YET); - } - else if (channelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { - dataManager.addToSamplingCollections(channelConfig.channel, currentTime); - channelConfig.state = ChannelState.SAMPLING; - channelConfig.channel.setFlag(Flag.NO_VALUE_RECEIVED_YET); - } - else { - channelConfig.state = ChannelState.CONNECTED; - } - } - } - - if (listeningChannels != null) { - taskList.add(new StartListeningTask(dataManager, this, listeningChannels)); - state = DeviceState.STARTING_TO_LISTEN; - } - else { - state = DeviceState.CONNECTED; - } - - } - - private void connect() { - - ConnectTask connectTask = new ConnectTask(deviceConfig.driverParent.activeDriver, deviceConfig.device, - dataManager); - taskList.add(connectTask); - if (taskList.size() == 1) { - dataManager.executor.execute(connectTask); - } - } - - private void disconnect() { - DisconnectTask disconnectTask = new DisconnectTask(deviceConfig.driverParent.activeDriver, deviceConfig.device, - dataManager); - taskList.add(disconnectTask); - if (taskList.size() == 1) { - dataManager.executor.execute(disconnectTask); - } - } - - // only called by main thread - public boolean addSamplingTask(SamplingTask samplingTask, int samplingInterval) { - if (isConnected()) { - - // new - // if (deviceConfig.readTimeout == 0 || deviceConfig.readTimeout > samplingInterval) { - // if (taskList.size() > 0) { - // if (taskList.get(0).getType() == DeviceTaskType.READ) { - // ((GenReadTask) taskList.get(0)).startedLate = true; - // } - // } - // } - // new - - taskList.add(samplingTask); - if (taskList.size() == 1) { - samplingTask.running = true; - state = DeviceState.READING; - dataManager.executor.execute(samplingTask); - } - return true; - } - else { - samplingTask.deviceNotConnected(); - // TODO in the future change this to true - return true; - } - } - - public void addReadTask(ReadTask readTask) { - if (isConnected()) { - taskList.add(readTask); - if (taskList.size() == 1) { - readTask.running = true; - state = DeviceState.READING; - dataManager.executor.execute(readTask); - } - } - else { - readTask.deviceNotConnected(); - } - } - - public void taskFinished() { - taskList.remove(0); - if (eventList.size() == 0) { - executeNextTask(); - } - else { - handleEventQueueWhenConnected(); - } - - } - - private void executeNextTask() { - if (taskList.size() != 0) { - if (taskList.get(0).getType() == DeviceTaskType.SAMPLE) { - ((SamplingTask) taskList.get(0)).startedLate = true; - } - taskList.get(0).setDeviceState(); - if (taskList.get(0).device != this) { - state = DeviceState.CONNECTED; - } - dataManager.executor.execute(taskList.get(0)); - } - else { - state = DeviceState.CONNECTED; - } - } - - public void removeTask(SamplingTask samplingTask) { - taskList.remove(samplingTask); - } - - public void addWriteTask(WriteTask writeTask) { - if (isConnected()) { - taskList.add(writeTask); - if (taskList.size() == 1) { - state = DeviceState.WRITING; - dataManager.executor.execute(writeTask); - } - } - else { - writeTask.deviceNotConnected(); - } - } - - public void addStartListeningTask(StartListeningTask startListenTask) { - if (isConnected()) { - taskList.add(startListenTask); - if (taskList.size() == 1) { - state = DeviceState.WRITING; - dataManager.executor.execute(startListenTask); - } - } - } - - public boolean isConnected() { - return state == DeviceState.CONNECTED || state == DeviceState.READING - || state == DeviceState.SCANNING_FOR_CHANNELS || state == DeviceState.STARTING_TO_LISTEN - || state == DeviceState.WRITING; - } + private final static Logger logger = LoggerFactory.getLogger(Device.class); + + DeviceConfigImpl deviceConfig; + DataManager dataManager; + DeviceState state = null; + Connection connection; + + private final List eventList = new ArrayList(); + private final List taskList = new ArrayList(); + + public Device(DataManager dataManager, DeviceConfigImpl deviceConfig, long currentTime, List logChannels) { + this.dataManager = dataManager; + this.deviceConfig = deviceConfig; + + if (deviceConfig.isDisabled()) { + state = DeviceState.DISABLED; + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + channelConfig.channel = new ChannelImpl(dataManager, channelConfig, ChannelState.DISABLED, Flag.DISABLED, currentTime, + logChannels); + } + } else { + if (deviceConfig.driverParent.activeDriver == null) { + state = DeviceState.DRIVER_UNAVAILABLE; + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + channelConfig.channel = new ChannelImpl(dataManager, channelConfig, ChannelState.DRIVER_UNAVAILABLE, + Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); + } + } else { + state = DeviceState.CONNECTING; + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + channelConfig.channel = new ChannelImpl(dataManager, channelConfig, ChannelState.CONNECTING, Flag.CONNECTING, + currentTime, logChannels); + } + } + } + } + + public void configChangedSignal(DeviceConfigImpl newDeviceConfig, long currentTime, List logChannels) { + DeviceConfigImpl oldDeviceConfig = deviceConfig; + deviceConfig = newDeviceConfig; + newDeviceConfig.device = this; + + if (state == DeviceState.DISABLED) { + if (newDeviceConfig.isDisabled()) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, currentTime, + logChannels); + } else { + if (deviceConfig.driverParent.activeDriver == null) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, + Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); + } else { + setStatesForNewDevice(oldDeviceConfig, DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING, currentTime, + logChannels); + connect(); + } + } + } else if (state == DeviceState.DRIVER_UNAVAILABLE) { + if (newDeviceConfig.isDisabled()) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, currentTime, + logChannels); + } else { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, + Flag.DRIVER_UNAVAILABLE, currentTime, logChannels); + } + } else if (state == DeviceState.CONNECTING) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING, currentTime, + logChannels); + if (newDeviceConfig.isDisabled()) { + addEvent(DeviceEvent.DISABLED); + } else if (oldDeviceConfig.isDisabled()) { + eventList.remove(DeviceEvent.DISABLED); + } + } else if (state == DeviceState.DISCONNECTING) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING, currentTime, + logChannels); + if (newDeviceConfig.isDisabled()) { + addEvent(DeviceEvent.DISABLED); + } else if (oldDeviceConfig.isDisabled()) { + eventList.remove(DeviceEvent.DISABLED); + } + } else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { + if (newDeviceConfig.isDisabled()) { + setStatesForNewDevice(oldDeviceConfig, DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED, currentTime, + logChannels); + } else { + setStatesForNewDevice(oldDeviceConfig, DeviceState.WAITING_FOR_CONNECTION_RETRY, ChannelState.WAITING_FOR_CONNECTION_RETRY, + Flag.WAITING_FOR_CONNECTION_RETRY, currentTime, logChannels); + } + } else { + if (newDeviceConfig.isDisabled()) { + if (state == DeviceState.CONNECTED) { + eventList.add(DeviceEvent.DISABLED); + // TODO disable all readworkers + setStatesForNewConnectedDevice(oldDeviceConfig, DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, + Flag.DISCONNECTING, currentTime, logChannels); + disconnect(); + } else { + // Adding the disabled event will automatically disconnect the device as soon as the active task is + // finished + eventList.add(DeviceEvent.DISABLED); + // Update channels anyway to update the log channels + updateChannels(oldDeviceConfig, ChannelState.DISCONNECTING, Flag.DISCONNECTING, currentTime, logChannels); + } + } else { + updateChannels(oldDeviceConfig, ChannelState.CONNECTED, Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); + } + } + + } + + private void updateChannels(DeviceConfigImpl oldDeviceConfig, ChannelState channelState, Flag flag, long currentTime, + List logChannels) { + List listeningChannels = null; + for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { + ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); + ChannelConfigImpl newChannelConfig = newChannelConfigEntry.getValue(); + if (oldChannelConfig == null) { + if (newChannelConfig.state != ChannelState.DISABLED) { + if (newChannelConfig.listening == true) { + if (listeningChannels == null) { + listeningChannels = new LinkedList(); + } + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, ChannelState.LISTENING, + Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); + listeningChannels.add(newChannelConfig.channel.createChannelRecordContainer()); + } else if (newChannelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, ChannelState.SAMPLING, + Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); + dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); + } else { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, currentTime, + logChannels); + } + } else { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, currentTime, logChannels); + } + } else { + newChannelConfig.channel = oldChannelConfig.channel; + newChannelConfig.channel.config = newChannelConfig; + newChannelConfig.channel.setNewDeviceState(oldChannelConfig.state, newChannelConfig.channel.latestRecord.getFlag()); + if (!newChannelConfig.isDisabled() && (newChannelConfig.loggingInterval > 0)) { + dataManager.addToLoggingCollections(newChannelConfig.channel, currentTime); + logChannels.add(newChannelConfig); + } else if (!oldChannelConfig.disabled && oldChannelConfig.loggingInterval > 0) { + dataManager.removeFromLoggingCollections(newChannelConfig.channel); + } + if (newChannelConfig.isSampling()) { + dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); + } else if (oldChannelConfig.isSampling()) { + dataManager.removeFromSamplingCollections(newChannelConfig.channel); + } + if (!newChannelConfig.channelAddress.equals(oldChannelConfig.channelAddress)) { + newChannelConfig.channel.handle = null; + } + } + } + + if (listeningChannels != null) { + addStartListeningTask(new StartListeningTask(dataManager, this, listeningChannels)); + } + } + + private void addEvent(DeviceEvent event) { + Iterator i = eventList.iterator(); + while (i.hasNext()) { + if (i.next() == event) { + return; + } + } + eventList.add(event); + } + + private void setStatesForNewDevice(DeviceConfigImpl oldDeviceConfig, DeviceState DeviceState, ChannelState channelState, Flag flag, + long currentTime, List logChannels) { + state = DeviceState; + for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { + ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); + if (oldChannelConfig == null) { + newChannelConfigEntry.getValue().channel = new ChannelImpl(dataManager, newChannelConfigEntry.getValue(), channelState, + flag, currentTime, logChannels); + } else { + newChannelConfigEntry.getValue().channel = oldChannelConfig.channel; + newChannelConfigEntry.getValue().channel.config = newChannelConfigEntry.getValue(); + newChannelConfigEntry.getValue().channel.setNewDeviceState(channelState, flag); + if (!newChannelConfigEntry.getValue().isDisabled() && (newChannelConfigEntry.getValue().loggingInterval > 0)) { + dataManager.addToLoggingCollections(newChannelConfigEntry.getValue().channel, currentTime); + logChannels.add(newChannelConfigEntry.getValue()); + } + } + } + } + + private void setStatesForNewConnectedDevice(DeviceConfigImpl oldDeviceConfig, DeviceState DeviceState, ChannelState channelState, + Flag flag, long currentTime, List logChannels) { + state = DeviceState; + List listeningChannels = null; + for (Entry newChannelConfigEntry : deviceConfig.channelConfigsById.entrySet()) { + ChannelConfigImpl oldChannelConfig = oldDeviceConfig.channelConfigsById.get(newChannelConfigEntry.getKey()); + ChannelConfigImpl newChannelConfig = newChannelConfigEntry.getValue(); + if (oldChannelConfig == null) { + if (newChannelConfig.state != ChannelState.DISABLED) { + if (newChannelConfig.listening == true) { + if (listeningChannels == null) { + listeningChannels = new LinkedList(); + } + listeningChannels.add(newChannelConfig.channel.createChannelRecordContainer()); + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, ChannelState.LISTENING, + Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); + } else if (newChannelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, ChannelState.SAMPLING, + Flag.NO_VALUE_RECEIVED_YET, currentTime, logChannels); + dataManager.addToSamplingCollections(newChannelConfig.channel, currentTime); + } else { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, currentTime, + logChannels); + } + } else { + newChannelConfig.channel = new ChannelImpl(dataManager, newChannelConfig, channelState, flag, currentTime, logChannels); + } + } else { + newChannelConfig.channel = oldChannelConfig.channel; + newChannelConfig.channel.config = newChannelConfig; + newChannelConfig.channel.setNewDeviceState(channelState, flag); + if (!newChannelConfigEntry.getValue().isDisabled() && (newChannelConfigEntry.getValue().loggingInterval > 0)) { + dataManager.addToLoggingCollections(newChannelConfig.channel, currentTime); + logChannels.add(newChannelConfigEntry.getValue()); + } + } + } + + } + + private void setStates(DeviceState DeviceState, ChannelState channelState, Flag flag) { + state = DeviceState; + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + if (channelConfig.state != ChannelState.DISABLED) { + channelConfig.state = channelState; + if (channelConfig.channel.latestRecord.getFlag() != Flag.SAMPLING_AND_LISTENING_DISABLED) { + channelConfig.channel.setFlag(flag); + } + } + } + } + + void driverRegisteredSignal() { + + if (state == DeviceState.DRIVER_UNAVAILABLE) { + setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); + connect(); + } else if (state == DeviceState.DISCONNECTING) { + eventList.add(DeviceEvent.DRIVER_REGISTERED); + } + } + + void driverDeregisteredSignal() { + + if (state == DeviceState.DISABLED) { + dataManager.activeDeviceCountDown--; + if (dataManager.activeDeviceCountDown == 0) { + dataManager.driverRemovedSignal.countDown(); + } + } else if (state == DeviceState.CONNECTED) { + + eventList.add(0, DeviceEvent.DRIVER_DEREGISTERED); + + disableSampling(); + removeAllTasksOfThisDevice(); + setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); + disconnect(); + } else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { + disableConnectionRetry(); + setStates(DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE); + dataManager.activeDeviceCountDown--; + if (dataManager.activeDeviceCountDown == 0) { + dataManager.driverRemovedSignal.countDown(); + } + } else { + // add driver deregistered event always to the front of the queue + eventList.add(0, DeviceEvent.DRIVER_DEREGISTERED); + } + } + + public void deleteSignal() { + if (state == DeviceState.DRIVER_UNAVAILABLE || state == DeviceState.DISABLED) { + setDeleted(); + } else if (state == DeviceState.WAITING_FOR_CONNECTION_RETRY) { + disableConnectionRetry(); + setDeleted(); + } else if (state == DeviceState.CONNECTED) { + eventList.add(DeviceEvent.DELETED); + setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); + disconnect(); + } else { + eventList.add(DeviceEvent.DELETED); + } + } + + void connectedSignal(long currentTime) { + + taskList.remove(0); + + if (eventList.size() == 0) { + setConnected(currentTime); + executeNextTask(); + } else { + handleEventQueueWhenConnected(); + } + } + + void connectFailureSignal(long currentTime) { + taskList.remove(0); + if (eventList.size() == 0) { + setStates(DeviceState.WAITING_FOR_CONNECTION_RETRY, ChannelState.WAITING_FOR_CONNECTION_RETRY, + Flag.WAITING_FOR_CONNECTION_RETRY); + dataManager.addReconnectDeviceToActions(this, currentTime + deviceConfig.getConnectRetryInterval()); + removeAllTasksOfThisDevice(); + } else { + handleEventQueueWhenDisconnected(); + } + } + + // TODO is this function thread save? + public void disconnectedSignal() { + // TODO in rare cases where the RecordsReceivedListener causes the disconnectSignal while a SamplingTask is + // still sampling this could cause problems + synchronized (this) { + removeAllTasksOfThisDevice(); + if (eventList.size() == 0) { + setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); + connect(); + } else { + handleEventQueueWhenDisconnected(); + } + } + } + + public void connectRetrySignal() { + setStates(DeviceState.CONNECTING, ChannelState.CONNECTING, Flag.CONNECTING); + connect(); + } + + private void disableConnectionRetry() { + dataManager.removeFromConnectionRetry(this); + } + + private void setDeleted() { + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + channelConfig.state = ChannelState.DELETED; + channelConfig.channel.setFlag(Flag.CHANNEL_DELETED); + channelConfig.channel.handle = null; + } + state = DeviceState.DELETED; + } + + private void disableSampling() { + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + if (channelConfig.state != ChannelState.DISABLED) { + if (channelConfig.state == ChannelState.SAMPLING) { + dataManager.removeFromSamplingCollections(channelConfig.channel); + } + } + } + } + + private void handleEventQueueWhenConnected() { + + removeAllTasksOfThisDevice(); + setStates(DeviceState.DISCONNECTING, ChannelState.DISCONNECTING, Flag.DISCONNECTING); + disconnect(); + + } + + private void removeAllTasksOfThisDevice() { + Iterator i = taskList.iterator(); + while (i.hasNext()) { + DeviceTask deviceTask = i.next(); + if (deviceTask.device == this) { + i.remove(); + } + } + + if (taskList.size() > 0) { + if (!taskList.get(0).isAlive()) { + taskList.get(0).device.executeNextTask(); + } + } + } + + private void handleEventQueueWhenDisconnected() { + + // DeviceEvent.DRIVER_DEREGISTERED will always be put at position 0 + if (eventList.get(0) == DeviceEvent.DRIVER_DEREGISTERED) { + + synchronized (dataManager.driverRemovedSignal) { + dataManager.activeDeviceCountDown--; + if (dataManager.activeDeviceCountDown == 0) { + dataManager.driverRemovedSignal.countDown(); + } + } + } + + DeviceEvent lastEvent = eventList.get(eventList.size() - 1); + + if (lastEvent == DeviceEvent.DRIVER_DEREGISTERED) { + setStates(DeviceState.DRIVER_UNAVAILABLE, ChannelState.DRIVER_UNAVAILABLE, Flag.DRIVER_UNAVAILABLE); + } else if (lastEvent == DeviceEvent.DISABLED) { + setStates(DeviceState.DISABLED, ChannelState.DISABLED, Flag.DISABLED); + } else if (lastEvent == DeviceEvent.DELETED) { + setDeleted(); + } + // TODO handle DeviceEvent.DRIVER_REGISTERED? + + eventList.clear(); + + } + + private void setConnected(long currentTime) { + + List listeningChannels = null; + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + if (channelConfig.state != ChannelState.DISABLED) { + if (channelConfig.listening == true) { + if (listeningChannels == null) { + listeningChannels = new LinkedList(); + } + listeningChannels.add(channelConfig.channel.createChannelRecordContainer()); + channelConfig.state = ChannelState.LISTENING; + channelConfig.channel.setFlag(Flag.NO_VALUE_RECEIVED_YET); + } else if (channelConfig.samplingInterval != ChannelConfig.SAMPLING_INTERVAL_DEFAULT) { + dataManager.addToSamplingCollections(channelConfig.channel, currentTime); + channelConfig.state = ChannelState.SAMPLING; + channelConfig.channel.setFlag(Flag.NO_VALUE_RECEIVED_YET); + } else { + channelConfig.state = ChannelState.CONNECTED; + } + } + } + + if (listeningChannels != null) { + taskList.add(new StartListeningTask(dataManager, this, listeningChannels)); + state = DeviceState.STARTING_TO_LISTEN; + } else { + state = DeviceState.CONNECTED; + } + + } + + private void connect() { + + ConnectTask connectTask = new ConnectTask(deviceConfig.driverParent.activeDriver, deviceConfig.device, dataManager); + taskList.add(connectTask); + if (taskList.size() == 1) { + dataManager.executor.execute(connectTask); + } + } + + private void disconnect() { + DisconnectTask disconnectTask = new DisconnectTask(deviceConfig.driverParent.activeDriver, deviceConfig.device, dataManager); + taskList.add(disconnectTask); + if (taskList.size() == 1) { + dataManager.executor.execute(disconnectTask); + } + } + + // only called by main thread + public boolean addSamplingTask(SamplingTask samplingTask, int samplingInterval) { + if (isConnected()) { + + // new + // if (deviceConfig.readTimeout == 0 || deviceConfig.readTimeout > samplingInterval) { + // if (taskList.size() > 0) { + // if (taskList.get(0).getType() == DeviceTaskType.READ) { + // ((GenReadTask) taskList.get(0)).startedLate = true; + // } + // } + // } + // new + + taskList.add(samplingTask); + if (taskList.size() == 1) { + samplingTask.running = true; + state = DeviceState.READING; + dataManager.executor.execute(samplingTask); + } + return true; + } else { + samplingTask.deviceNotConnected(); + // TODO in the future change this to true + return true; + } + } + + public void addReadTask(ReadTask readTask) { + if (isConnected()) { + taskList.add(readTask); + if (taskList.size() == 1) { + readTask.running = true; + state = DeviceState.READING; + dataManager.executor.execute(readTask); + } + } else { + readTask.deviceNotConnected(); + } + } + + public void taskFinished() { + taskList.remove(0); + if (eventList.size() == 0) { + executeNextTask(); + } else { + handleEventQueueWhenConnected(); + } + + } + + private void executeNextTask() { + if (taskList.size() != 0) { + if (taskList.get(0).getType() == DeviceTaskType.SAMPLE) { + ((SamplingTask) taskList.get(0)).startedLate = true; + } + taskList.get(0).setDeviceState(); + if (taskList.get(0).device != this) { + state = DeviceState.CONNECTED; + } + dataManager.executor.execute(taskList.get(0)); + } else { + state = DeviceState.CONNECTED; + } + } + + public void removeTask(SamplingTask samplingTask) { + taskList.remove(samplingTask); + } + + public void addWriteTask(WriteTask writeTask) { + if (isConnected()) { + taskList.add(writeTask); + if (taskList.size() == 1) { + state = DeviceState.WRITING; + dataManager.executor.execute(writeTask); + } + } else { + writeTask.deviceNotConnected(); + } + } + + public void addStartListeningTask(StartListeningTask startListenTask) { + if (isConnected()) { + taskList.add(startListenTask); + if (taskList.size() == 1) { + state = DeviceState.WRITING; + dataManager.executor.execute(startListenTask); + } + } + } + + public boolean isConnected() { + return state == DeviceState.CONNECTED || state == DeviceState.READING || state == DeviceState.SCANNING_FOR_CHANNELS || state == DeviceState.STARTING_TO_LISTEN || state == DeviceState.WRITING; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceConfigImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceConfigImpl.java index 73f5596e..6900c839 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceConfigImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceConfigImpl.java @@ -21,368 +21,345 @@ package org.openmuc.framework.core.datamanager; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.ParseException; +import org.openmuc.framework.config.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; + public final class DeviceConfigImpl implements DeviceConfig { - String id; - String description = null; - String deviceAddress = null; - String settings = null; - - Integer samplingTimeout = null; - Integer connectRetryInterval = null; - Boolean disabled = null; - - Device device = null; - - final HashMap channelConfigsById = new LinkedHashMap(); - - DriverConfigImpl driverParent; - - DeviceConfigImpl(String id, DriverConfigImpl driverParent) { - this.id = id; - this.driverParent = driverParent; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) throws IdCollisionException { - if (id == null) { - throw new IllegalArgumentException("The device ID may not be null"); - } - ChannelConfigImpl.checkIdSyntax(id); - - if (driverParent.rootConfigParent.deviceConfigsById.containsKey(id)) { - throw new IdCollisionException("Collision with device ID:" + id); - } - - driverParent.deviceConfigsById.put(id, driverParent.deviceConfigsById.remove(this.id)); - driverParent.rootConfigParent.deviceConfigsById.put(id, - driverParent.rootConfigParent.deviceConfigsById.remove(this.id)); - - this.id = id; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getDeviceAddress() { - return deviceAddress; - } - - @Override - public void setDeviceAddress(String address) { - deviceAddress = address; - } - - @Override - public String getSettings() { - return settings; - } - - @Override - public void setSettings(String settings) { - this.settings = settings; - } - - @Override - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - @Override - public void setSamplingTimeout(Integer timeout) { - if (timeout != null && timeout < 0) { - throw new IllegalArgumentException("A negative sampling timeout is not allowed"); - } - samplingTimeout = timeout; - } - - @Override - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - @Override - public void setConnectRetryInterval(Integer interval) { - if (interval != null && interval < 0) { - throw new IllegalArgumentException("A negative connect retry interval is not allowed"); - } - connectRetryInterval = interval; - } - - @Override - public Boolean isDisabled() { - return disabled; - } - - @Override - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } - - @Override - public ChannelConfig addChannel(String channelId) throws IdCollisionException { - - if (channelId == null) { - throw new IllegalArgumentException("The channel ID may not be null"); - } - - ChannelConfigImpl.checkIdSyntax(channelId); - - if (driverParent.rootConfigParent.channelConfigsById.containsKey(channelId)) { - throw new IdCollisionException("Collision with channel ID: " + channelId); - } - - ChannelConfigImpl newChannel = new ChannelConfigImpl(channelId, this); - - driverParent.rootConfigParent.channelConfigsById.put(channelId, newChannel); - channelConfigsById.put(channelId, newChannel); - return newChannel; - } - - @Override - public ChannelConfig getChannel(String channelId) { - return channelConfigsById.get(channelId); - } - - @SuppressWarnings("unchecked") - @Override - public Collection getChannels() { - return (Collection) (Collection) Collections.unmodifiableCollection(channelConfigsById - .values()); - } - - @Override - public void delete() { - driverParent.deviceConfigsById.remove(id); - clear(); - } - - void clear() { - for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { - channelConfig.clear(); - } - channelConfigsById.clear(); - driverParent.rootConfigParent.deviceConfigsById.remove(id); - driverParent = null; - } - - @Override - public DriverConfig getDriver() { - return driverParent; - } - - static void addDeviceFromDomNode(Node deviceConfigNode, DriverConfig parentConfig) throws ParseException { - - String id = ChannelConfigImpl.getAttributeValue(deviceConfigNode, "id"); - if (id == null) { - throw new ParseException("device has no id attribute"); - } - - DeviceConfigImpl config; - try { - config = (DeviceConfigImpl) parentConfig.addDevice(id); - } catch (Exception e) { - throw new ParseException(e); - } - - NodeList deviceChildren = deviceConfigNode.getChildNodes(); - - try { - for (int i = 0; i < deviceChildren.getLength(); i++) { - Node childNode = deviceChildren.item(i); - String childName = childNode.getNodeName(); - - if (childName.equals("#text")) { - continue; - } - else if (childName.equals("channel")) { - ChannelConfigImpl.addChannelFromDomNode(childNode, config); - } - else if (childName.equals("description")) { - config.setDescription(childNode.getTextContent()); - } - else if (childName.equals("deviceAddress")) { - config.setDeviceAddress(childNode.getTextContent()); - } - else if (childName.equals("settings")) { - config.setSettings(childNode.getTextContent()); - } - else if (childName.equals("samplingTimeout")) { - config.setSamplingTimeout(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("connectRetryInterval")) { - config.setConnectRetryInterval(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("disabled")) { - String disabledString = childNode.getTextContent().toLowerCase(); - if (disabledString.equals("true")) { - config.disabled = true; - } - else if (disabledString.equals("false")) { - config.disabled = false; - } - else { - throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); - } - } - else { - throw new ParseException("found unknown tag:" + childName); - } - } - } catch (IllegalArgumentException e) { - throw new ParseException(e); - } - - } - - Element getDomElement(Document document) { - Element parentElement = document.createElement("device"); - parentElement.setAttribute("id", id); - - Element childElement; - - if (description != null) { - childElement = document.createElement("description"); - childElement.setTextContent(description); - parentElement.appendChild(childElement); - } - - if (deviceAddress != null) { - childElement = document.createElement("deviceAddress"); - childElement.setTextContent(deviceAddress); - parentElement.appendChild(childElement); - } - - if (settings != null) { - childElement = document.createElement("settings"); - childElement.setTextContent(settings); - parentElement.appendChild(childElement); - } - - if (samplingTimeout != null) { - childElement = document.createElement("samplingTimeout"); - childElement.setTextContent(ChannelConfigImpl.millisToTimeString(samplingTimeout)); - parentElement.appendChild(childElement); - } - - if (connectRetryInterval != null) { - childElement = document.createElement("connectRetryInterval"); - childElement.setTextContent(ChannelConfigImpl.millisToTimeString(connectRetryInterval)); - parentElement.appendChild(childElement); - } - - if (disabled != null) { - childElement = document.createElement("disabled"); - if (disabled) { - childElement.setTextContent("true"); - } - else { - childElement.setTextContent("false"); - } - parentElement.appendChild(childElement); - } - - for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { - parentElement.appendChild(channelConfig.getDomElement(document)); - } - - return parentElement; - } - - DeviceConfigImpl clone(DriverConfigImpl clonedParentConfig) { - DeviceConfigImpl configClone = new DeviceConfigImpl(id, clonedParentConfig); - - configClone.description = description; - configClone.deviceAddress = deviceAddress; - configClone.settings = settings; - configClone.samplingTimeout = samplingTimeout; - configClone.connectRetryInterval = connectRetryInterval; - configClone.disabled = disabled; - - for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { - configClone.channelConfigsById.put(channelConfig.id, channelConfig.clone(configClone)); - } - return configClone; - } - - DeviceConfigImpl cloneWithDefaults(DriverConfigImpl clonedParentConfig) { - - DeviceConfigImpl configClone = new DeviceConfigImpl(id, clonedParentConfig); - - if (description == null) { - configClone.description = DESCRIPTION_DEFAULT; - } - else { - configClone.description = description; - } - - if (deviceAddress == null) { - configClone.deviceAddress = DEVICE_ADDRESS_DEFAULT; - } - else { - configClone.deviceAddress = deviceAddress; - } - - if (settings == null) { - configClone.settings = SETTINGS_DEFAULT; - } - else { - configClone.settings = settings; - } - - if (samplingTimeout == null) { - configClone.samplingTimeout = clonedParentConfig.samplingTimeout; - } - else { - configClone.samplingTimeout = samplingTimeout; - } - - if (connectRetryInterval == null) { - configClone.connectRetryInterval = clonedParentConfig.connectRetryInterval; - } - else { - configClone.connectRetryInterval = connectRetryInterval; - } - - if (disabled == null || clonedParentConfig.disabled) { - configClone.disabled = clonedParentConfig.disabled; - } - else { - configClone.disabled = disabled; - } - - for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { - configClone.channelConfigsById.put(channelConfig.id, channelConfig.cloneWithDefaults(configClone)); - } - return configClone; - } + String id; + String description = null; + String deviceAddress = null; + String settings = null; + + Integer samplingTimeout = null; + Integer connectRetryInterval = null; + Boolean disabled = null; + + Device device = null; + + final HashMap channelConfigsById = new LinkedHashMap(); + + DriverConfigImpl driverParent; + + DeviceConfigImpl(String id, DriverConfigImpl driverParent) { + this.id = id; + this.driverParent = driverParent; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) throws IdCollisionException { + if (id == null) { + throw new IllegalArgumentException("The device ID may not be null"); + } + ChannelConfigImpl.checkIdSyntax(id); + + if (driverParent.rootConfigParent.deviceConfigsById.containsKey(id)) { + throw new IdCollisionException("Collision with device ID:" + id); + } + + driverParent.deviceConfigsById.put(id, driverParent.deviceConfigsById.remove(this.id)); + driverParent.rootConfigParent.deviceConfigsById.put(id, driverParent.rootConfigParent.deviceConfigsById.remove(this.id)); + + this.id = id; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getDeviceAddress() { + return deviceAddress; + } + + @Override + public void setDeviceAddress(String address) { + deviceAddress = address; + } + + @Override + public String getSettings() { + return settings; + } + + @Override + public void setSettings(String settings) { + this.settings = settings; + } + + @Override + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + @Override + public void setSamplingTimeout(Integer timeout) { + if (timeout != null && timeout < 0) { + throw new IllegalArgumentException("A negative sampling timeout is not allowed"); + } + samplingTimeout = timeout; + } + + @Override + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + @Override + public void setConnectRetryInterval(Integer interval) { + if (interval != null && interval < 0) { + throw new IllegalArgumentException("A negative connect retry interval is not allowed"); + } + connectRetryInterval = interval; + } + + @Override + public Boolean isDisabled() { + return disabled; + } + + @Override + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + @Override + public ChannelConfig addChannel(String channelId) throws IdCollisionException { + + if (channelId == null) { + throw new IllegalArgumentException("The channel ID may not be null"); + } + + ChannelConfigImpl.checkIdSyntax(channelId); + + if (driverParent.rootConfigParent.channelConfigsById.containsKey(channelId)) { + throw new IdCollisionException("Collision with channel ID: " + channelId); + } + + ChannelConfigImpl newChannel = new ChannelConfigImpl(channelId, this); + + driverParent.rootConfigParent.channelConfigsById.put(channelId, newChannel); + channelConfigsById.put(channelId, newChannel); + return newChannel; + } + + @Override + public ChannelConfig getChannel(String channelId) { + return channelConfigsById.get(channelId); + } + + @SuppressWarnings("unchecked") + @Override + public Collection getChannels() { + return (Collection) (Collection) Collections.unmodifiableCollection(channelConfigsById.values()); + } + + @Override + public void delete() { + driverParent.deviceConfigsById.remove(id); + clear(); + } + + void clear() { + for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { + channelConfig.clear(); + } + channelConfigsById.clear(); + driverParent.rootConfigParent.deviceConfigsById.remove(id); + driverParent = null; + } + + @Override + public DriverConfig getDriver() { + return driverParent; + } + + static void addDeviceFromDomNode(Node deviceConfigNode, DriverConfig parentConfig) throws ParseException { + + String id = ChannelConfigImpl.getAttributeValue(deviceConfigNode, "id"); + if (id == null) { + throw new ParseException("device has no id attribute"); + } + + DeviceConfigImpl config; + try { + config = (DeviceConfigImpl) parentConfig.addDevice(id); + } catch (Exception e) { + throw new ParseException(e); + } + + NodeList deviceChildren = deviceConfigNode.getChildNodes(); + + try { + for (int i = 0; i < deviceChildren.getLength(); i++) { + Node childNode = deviceChildren.item(i); + String childName = childNode.getNodeName(); + + if (childName.equals("#text")) { + continue; + } else if (childName.equals("channel")) { + ChannelConfigImpl.addChannelFromDomNode(childNode, config); + } else if (childName.equals("description")) { + config.setDescription(childNode.getTextContent()); + } else if (childName.equals("deviceAddress")) { + config.setDeviceAddress(childNode.getTextContent()); + } else if (childName.equals("settings")) { + config.setSettings(childNode.getTextContent()); + } else if (childName.equals("samplingTimeout")) { + config.setSamplingTimeout(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("connectRetryInterval")) { + config.setConnectRetryInterval(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("disabled")) { + String disabledString = childNode.getTextContent().toLowerCase(); + if (disabledString.equals("true")) { + config.disabled = true; + } else if (disabledString.equals("false")) { + config.disabled = false; + } else { + throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); + } + } else { + throw new ParseException("found unknown tag:" + childName); + } + } + } catch (IllegalArgumentException e) { + throw new ParseException(e); + } + + } + + Element getDomElement(Document document) { + Element parentElement = document.createElement("device"); + parentElement.setAttribute("id", id); + + Element childElement; + + if (description != null) { + childElement = document.createElement("description"); + childElement.setTextContent(description); + parentElement.appendChild(childElement); + } + + if (deviceAddress != null) { + childElement = document.createElement("deviceAddress"); + childElement.setTextContent(deviceAddress); + parentElement.appendChild(childElement); + } + + if (settings != null) { + childElement = document.createElement("settings"); + childElement.setTextContent(settings); + parentElement.appendChild(childElement); + } + + if (samplingTimeout != null) { + childElement = document.createElement("samplingTimeout"); + childElement.setTextContent(ChannelConfigImpl.millisToTimeString(samplingTimeout)); + parentElement.appendChild(childElement); + } + + if (connectRetryInterval != null) { + childElement = document.createElement("connectRetryInterval"); + childElement.setTextContent(ChannelConfigImpl.millisToTimeString(connectRetryInterval)); + parentElement.appendChild(childElement); + } + + if (disabled != null) { + childElement = document.createElement("disabled"); + if (disabled) { + childElement.setTextContent("true"); + } else { + childElement.setTextContent("false"); + } + parentElement.appendChild(childElement); + } + + for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { + parentElement.appendChild(channelConfig.getDomElement(document)); + } + + return parentElement; + } + + DeviceConfigImpl clone(DriverConfigImpl clonedParentConfig) { + DeviceConfigImpl configClone = new DeviceConfigImpl(id, clonedParentConfig); + + configClone.description = description; + configClone.deviceAddress = deviceAddress; + configClone.settings = settings; + configClone.samplingTimeout = samplingTimeout; + configClone.connectRetryInterval = connectRetryInterval; + configClone.disabled = disabled; + + for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { + configClone.channelConfigsById.put(channelConfig.id, channelConfig.clone(configClone)); + } + return configClone; + } + + DeviceConfigImpl cloneWithDefaults(DriverConfigImpl clonedParentConfig) { + + DeviceConfigImpl configClone = new DeviceConfigImpl(id, clonedParentConfig); + + if (description == null) { + configClone.description = DESCRIPTION_DEFAULT; + } else { + configClone.description = description; + } + + if (deviceAddress == null) { + configClone.deviceAddress = DEVICE_ADDRESS_DEFAULT; + } else { + configClone.deviceAddress = deviceAddress; + } + + if (settings == null) { + configClone.settings = SETTINGS_DEFAULT; + } else { + configClone.settings = settings; + } + + if (samplingTimeout == null) { + configClone.samplingTimeout = clonedParentConfig.samplingTimeout; + } else { + configClone.samplingTimeout = samplingTimeout; + } + + if (connectRetryInterval == null) { + configClone.connectRetryInterval = clonedParentConfig.connectRetryInterval; + } else { + configClone.connectRetryInterval = connectRetryInterval; + } + + if (disabled == null || clonedParentConfig.disabled) { + configClone.disabled = clonedParentConfig.disabled; + } else { + configClone.disabled = disabled; + } + + for (ChannelConfigImpl channelConfig : channelConfigsById.values()) { + configClone.channelConfigsById.put(channelConfig.id, channelConfig.cloneWithDefaults(configClone)); + } + return configClone; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceEvent.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceEvent.java index 27a320a0..94e17798 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceEvent.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceEvent.java @@ -22,5 +22,5 @@ package org.openmuc.framework.core.datamanager; public enum DeviceEvent { - DELETED, DISABLED, DRIVER_REGISTERED, DRIVER_DEREGISTERED; + DELETED, DISABLED, DRIVER_REGISTERED, DRIVER_DEREGISTERED; } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTask.java index 647f15c5..d1e62405 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTask.java @@ -25,11 +25,11 @@ public abstract class DeviceTask extends Thread { - protected Device device; - protected DriverService driver; - protected DataManager dataManager; + protected Device device; + protected DriverService driver; + protected DataManager dataManager; - public abstract DeviceTaskType getType(); + public abstract DeviceTaskType getType(); - public abstract void setDeviceState(); + public abstract void setDeviceState(); } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTaskType.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTaskType.java index adfba33b..6891b0c7 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTaskType.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DeviceTaskType.java @@ -22,5 +22,5 @@ package org.openmuc.framework.core.datamanager; public enum DeviceTaskType { - CONNECT, DISCONNECT, SAMPLE, READ, WRITE, START_LISTENING_FOR; + CONNECT, DISCONNECT, SAMPLE, READ, WRITE, START_LISTENING_FOR; } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DisconnectTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DisconnectTask.java index ef11320d..9cb6f84e 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DisconnectTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DisconnectTask.java @@ -26,31 +26,31 @@ public final class DisconnectTask extends DeviceTask { - public DisconnectTask(DriverService driver, Device device, DataManager dataManager) { - this.driver = driver; - this.device = device; - this.dataManager = dataManager; - } + public DisconnectTask(DriverService driver, Device device, DataManager dataManager) { + this.driver = driver; + this.device = device; + this.dataManager = dataManager; + } - @Override - public void run() { + @Override + public void run() { - device.connection.disconnect(); + device.connection.disconnect(); - synchronized (dataManager.disconnected) { - dataManager.disconnected.add(device); - } - dataManager.interrupt(); + synchronized (dataManager.disconnected) { + dataManager.disconnected.add(device); + } + dataManager.interrupt(); - } + } - @Override - public DeviceTaskType getType() { - return DeviceTaskType.DISCONNECT; - } + @Override + public DeviceTaskType getType() { + return DeviceTaskType.DISCONNECT; + } - @Override - public void setDeviceState() { - device.state = DeviceState.DISCONNECTING; - } + @Override + public void setDeviceState() { + device.state = DeviceState.DISCONNECTING; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DriverConfigImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DriverConfigImpl.java index 8899f6b9..d2031b3d 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DriverConfigImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/DriverConfigImpl.java @@ -21,271 +21,255 @@ package org.openmuc.framework.core.datamanager; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; - -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.ParseException; -import org.openmuc.framework.config.RootConfig; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.DriverService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; + public final class DriverConfigImpl implements DriverConfig { - String id; - Integer samplingTimeout = null; - Integer connectRetryInterval = null; - Boolean disabled = null; - - final HashMap deviceConfigsById = new LinkedHashMap(); - - RootConfigImpl rootConfigParent; - - DriverService activeDriver = null; - - DriverConfigImpl(String id, RootConfigImpl rootConfigParent) { - this.id = id; - this.rootConfigParent = rootConfigParent; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) throws IdCollisionException { - if (id == null) { - throw new IllegalArgumentException("The driver ID may not be null"); - } - ChannelConfigImpl.checkIdSyntax(id); - - if (rootConfigParent.driverConfigsById.containsKey(id)) { - throw new IdCollisionException("Collision with the driver ID:" + id); - } - rootConfigParent.driverConfigsById.put(id, rootConfigParent.driverConfigsById.remove(this.id)); - - this.id = id; - } - - @Override - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - @Override - public void setSamplingTimeout(Integer timeout) { - if (timeout != null && timeout < 0) { - throw new IllegalArgumentException("A negative sampling timeout is not allowed"); - } - samplingTimeout = timeout; - } - - @Override - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - @Override - public void setConnectRetryInterval(Integer interval) { - if (interval != null && interval < 0) { - throw new IllegalArgumentException("A negative connect retry interval is not allowed"); - } - connectRetryInterval = interval; - } - - @Override - public Boolean isDisabled() { - return disabled; - } - - @Override - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } - - @Override - public DeviceConfig addDevice(String deviceId) throws IdCollisionException { - - if (deviceId == null) { - throw new IllegalArgumentException("The device ID may not be null"); - } - - ChannelConfigImpl.checkIdSyntax(deviceId); - - if (rootConfigParent.deviceConfigsById.containsKey(deviceId)) { - throw new IdCollisionException("Collision with device ID: " + deviceId); - } - - DeviceConfigImpl newDevice = new DeviceConfigImpl(deviceId, this); - - rootConfigParent.deviceConfigsById.put(deviceId, newDevice); - deviceConfigsById.put(deviceId, newDevice); - - return newDevice; - } - - @Override - public DeviceConfig getDevice(String deviceId) { - return deviceConfigsById.get(deviceId); - } - - @SuppressWarnings("unchecked") - @Override - public Collection getDevices() { - return (Collection) (Collection) Collections - .unmodifiableCollection(deviceConfigsById.values()); - } - - @Override - public void delete() { - rootConfigParent.driverConfigsById.remove(id); - for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { - deviceConfig.clear(); - } - deviceConfigsById.clear(); - rootConfigParent = null; - } - - static void addDriverFromDomNode(Node driverConfigNode, RootConfig parentConfig) throws ParseException { - - String id = ChannelConfigImpl.getAttributeValue(driverConfigNode, "id"); - if (id == null) { - throw new ParseException("driver has no id attribute"); - } - - DriverConfigImpl config; - try { - config = (DriverConfigImpl) parentConfig.addDriver(id); - } catch (Exception e) { - throw new ParseException(e); - } - - NodeList driverChildren = driverConfigNode.getChildNodes(); - - try { - for (int j = 0; j < driverChildren.getLength(); j++) { - Node childNode = driverChildren.item(j); - String childName = childNode.getNodeName(); - - if (childName.equals("#text")) { - continue; - } - else if (childName.equals("device")) { - DeviceConfigImpl.addDeviceFromDomNode(childNode, config); - } - else if (childName.equals("samplingTimeout")) { - config.setSamplingTimeout(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("connectRetryInterval")) { - config.setConnectRetryInterval(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); - } - else if (childName.equals("disabled")) { - String disabledString = childNode.getTextContent().toLowerCase(); - if (disabledString.equals("true")) { - config.disabled = true; - } - else if (disabledString.equals("false")) { - config.disabled = false; - } - else { - throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); - } - } - else { - throw new ParseException("found unknown tag:" + childName); - } - - } - } catch (IllegalArgumentException e) { - throw new ParseException(e); - } - } - - Element getDomElement(Document document) { - Element parentElement = document.createElement("driver"); - parentElement.setAttribute("id", id); - - Element childElement; - - if (samplingTimeout != null) { - childElement = document.createElement("samplingTimeout"); - childElement.setTextContent(ChannelConfigImpl.millisToTimeString(samplingTimeout)); - parentElement.appendChild(childElement); - } - - if (connectRetryInterval != null) { - childElement = document.createElement("connectRetryInterval"); - childElement.setTextContent(ChannelConfigImpl.millisToTimeString(connectRetryInterval)); - parentElement.appendChild(childElement); - } - - if (disabled != null) { - childElement = document.createElement("disabled"); - if (disabled) { - childElement.setTextContent("true"); - } - else { - childElement.setTextContent("false"); - } - parentElement.appendChild(childElement); - } - - for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { - parentElement.appendChild(deviceConfig.getDomElement(document)); - } - - return parentElement; - } - - DriverConfigImpl clone(RootConfigImpl clonedParentConfig) { - DriverConfigImpl configClone = new DriverConfigImpl(id, clonedParentConfig); - - configClone.samplingTimeout = samplingTimeout; - configClone.connectRetryInterval = connectRetryInterval; - configClone.disabled = disabled; - - for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { - configClone.deviceConfigsById.put(deviceConfig.id, deviceConfig.clone(configClone)); - } - return configClone; - } - - DriverConfigImpl cloneWithDefaults(RootConfigImpl clonedParentConfig) { - DriverConfigImpl configClone = new DriverConfigImpl(id, clonedParentConfig); - - if (samplingTimeout == null) { - configClone.samplingTimeout = SAMPLING_TIMEOUT_DEFAULT; - } - else { - configClone.samplingTimeout = samplingTimeout; - } - - if (connectRetryInterval == null) { - configClone.connectRetryInterval = CONNECT_RETRY_INTERVAL_DEFAULT; - } - else { - configClone.connectRetryInterval = connectRetryInterval; - } - - if (disabled == null) { - configClone.disabled = DISABLED_DEFAULT; - } - else { - configClone.disabled = disabled; - } - - for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { - configClone.deviceConfigsById.put(deviceConfig.id, deviceConfig.cloneWithDefaults(configClone)); - } - return configClone; - } + String id; + Integer samplingTimeout = null; + Integer connectRetryInterval = null; + Boolean disabled = null; + + final HashMap deviceConfigsById = new LinkedHashMap(); + + RootConfigImpl rootConfigParent; + + DriverService activeDriver = null; + + DriverConfigImpl(String id, RootConfigImpl rootConfigParent) { + this.id = id; + this.rootConfigParent = rootConfigParent; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) throws IdCollisionException { + if (id == null) { + throw new IllegalArgumentException("The driver ID may not be null"); + } + ChannelConfigImpl.checkIdSyntax(id); + + if (rootConfigParent.driverConfigsById.containsKey(id)) { + throw new IdCollisionException("Collision with the driver ID:" + id); + } + rootConfigParent.driverConfigsById.put(id, rootConfigParent.driverConfigsById.remove(this.id)); + + this.id = id; + } + + @Override + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + @Override + public void setSamplingTimeout(Integer timeout) { + if (timeout != null && timeout < 0) { + throw new IllegalArgumentException("A negative sampling timeout is not allowed"); + } + samplingTimeout = timeout; + } + + @Override + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + @Override + public void setConnectRetryInterval(Integer interval) { + if (interval != null && interval < 0) { + throw new IllegalArgumentException("A negative connect retry interval is not allowed"); + } + connectRetryInterval = interval; + } + + @Override + public Boolean isDisabled() { + return disabled; + } + + @Override + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + @Override + public DeviceConfig addDevice(String deviceId) throws IdCollisionException { + + if (deviceId == null) { + throw new IllegalArgumentException("The device ID may not be null"); + } + + ChannelConfigImpl.checkIdSyntax(deviceId); + + if (rootConfigParent.deviceConfigsById.containsKey(deviceId)) { + throw new IdCollisionException("Collision with device ID: " + deviceId); + } + + DeviceConfigImpl newDevice = new DeviceConfigImpl(deviceId, this); + + rootConfigParent.deviceConfigsById.put(deviceId, newDevice); + deviceConfigsById.put(deviceId, newDevice); + + return newDevice; + } + + @Override + public DeviceConfig getDevice(String deviceId) { + return deviceConfigsById.get(deviceId); + } + + @SuppressWarnings("unchecked") + @Override + public Collection getDevices() { + return (Collection) (Collection) Collections.unmodifiableCollection(deviceConfigsById.values()); + } + + @Override + public void delete() { + rootConfigParent.driverConfigsById.remove(id); + for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { + deviceConfig.clear(); + } + deviceConfigsById.clear(); + rootConfigParent = null; + } + + static void addDriverFromDomNode(Node driverConfigNode, RootConfig parentConfig) throws ParseException { + + String id = ChannelConfigImpl.getAttributeValue(driverConfigNode, "id"); + if (id == null) { + throw new ParseException("driver has no id attribute"); + } + + DriverConfigImpl config; + try { + config = (DriverConfigImpl) parentConfig.addDriver(id); + } catch (Exception e) { + throw new ParseException(e); + } + + NodeList driverChildren = driverConfigNode.getChildNodes(); + + try { + for (int j = 0; j < driverChildren.getLength(); j++) { + Node childNode = driverChildren.item(j); + String childName = childNode.getNodeName(); + + if (childName.equals("#text")) { + continue; + } else if (childName.equals("device")) { + DeviceConfigImpl.addDeviceFromDomNode(childNode, config); + } else if (childName.equals("samplingTimeout")) { + config.setSamplingTimeout(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("connectRetryInterval")) { + config.setConnectRetryInterval(ChannelConfigImpl.timeStringToMillis(childNode.getTextContent())); + } else if (childName.equals("disabled")) { + String disabledString = childNode.getTextContent().toLowerCase(); + if (disabledString.equals("true")) { + config.disabled = true; + } else if (disabledString.equals("false")) { + config.disabled = false; + } else { + throw new ParseException("\"disabled\" tag contains neither \"true\" nor \"false\""); + } + } else { + throw new ParseException("found unknown tag:" + childName); + } + + } + } catch (IllegalArgumentException e) { + throw new ParseException(e); + } + } + + Element getDomElement(Document document) { + Element parentElement = document.createElement("driver"); + parentElement.setAttribute("id", id); + + Element childElement; + + if (samplingTimeout != null) { + childElement = document.createElement("samplingTimeout"); + childElement.setTextContent(ChannelConfigImpl.millisToTimeString(samplingTimeout)); + parentElement.appendChild(childElement); + } + + if (connectRetryInterval != null) { + childElement = document.createElement("connectRetryInterval"); + childElement.setTextContent(ChannelConfigImpl.millisToTimeString(connectRetryInterval)); + parentElement.appendChild(childElement); + } + + if (disabled != null) { + childElement = document.createElement("disabled"); + if (disabled) { + childElement.setTextContent("true"); + } else { + childElement.setTextContent("false"); + } + parentElement.appendChild(childElement); + } + + for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { + parentElement.appendChild(deviceConfig.getDomElement(document)); + } + + return parentElement; + } + + DriverConfigImpl clone(RootConfigImpl clonedParentConfig) { + DriverConfigImpl configClone = new DriverConfigImpl(id, clonedParentConfig); + + configClone.samplingTimeout = samplingTimeout; + configClone.connectRetryInterval = connectRetryInterval; + configClone.disabled = disabled; + + for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { + configClone.deviceConfigsById.put(deviceConfig.id, deviceConfig.clone(configClone)); + } + return configClone; + } + + DriverConfigImpl cloneWithDefaults(RootConfigImpl clonedParentConfig) { + DriverConfigImpl configClone = new DriverConfigImpl(id, clonedParentConfig); + + if (samplingTimeout == null) { + configClone.samplingTimeout = SAMPLING_TIMEOUT_DEFAULT; + } else { + configClone.samplingTimeout = samplingTimeout; + } + + if (connectRetryInterval == null) { + configClone.connectRetryInterval = CONNECT_RETRY_INTERVAL_DEFAULT; + } else { + configClone.connectRetryInterval = connectRetryInterval; + } + + if (disabled == null) { + configClone.disabled = DISABLED_DEFAULT; + } else { + configClone.disabled = disabled; + } + + for (DeviceConfigImpl deviceConfig : deviceConfigsById.values()) { + configClone.deviceConfigsById.put(deviceConfig.id, deviceConfig.cloneWithDefaults(configClone)); + } + return configClone; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenTask.java index f3c36b4e..37c041d4 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenTask.java @@ -21,18 +21,18 @@ package org.openmuc.framework.core.datamanager; +import org.openmuc.framework.driver.spi.ChannelRecordContainer; + import java.util.LinkedList; import java.util.List; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; - public final class ListenTask { - boolean startListening; - List selectedChannels; + boolean startListening; + List selectedChannels; - public ListenTask(boolean startListening) { - selectedChannels = new LinkedList(); - this.startListening = startListening; - } + public ListenTask(boolean startListening) { + selectedChannels = new LinkedList(); + this.startListening = startListening; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenerNotifier.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenerNotifier.java index 8b7116d8..26dfbcd0 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenerNotifier.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ListenerNotifier.java @@ -26,17 +26,17 @@ public final class ListenerNotifier extends Thread { - RecordListener listener; - Record record; + RecordListener listener; + Record record; - public ListenerNotifier(RecordListener listener, Record record) { - this.listener = listener; - this.record = record; - } + public ListenerNotifier(RecordListener listener, Record record) { + this.listener = listener; + this.record = record; + } - @Override - public void run() { - listener.newRecord(record); - } + @Override + public void run() { + listener.newRecord(record); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/LogRecordContainerImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/LogRecordContainerImpl.java index 682ed73d..e5460e29 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/LogRecordContainerImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/LogRecordContainerImpl.java @@ -26,22 +26,22 @@ public final class LogRecordContainerImpl implements LogRecordContainer { - private final String channelId; - private final Record record; - - public LogRecordContainerImpl(String channelId, Record record) { - this.channelId = channelId; - this.record = record; - } - - @Override - public String getChannelId() { - return channelId; - } - - @Override - public Record getRecord() { - return record; - } + private final String channelId; + private final Record record; + + public LogRecordContainerImpl(String channelId, Record record) { + this.channelId = channelId; + this.record = record; + } + + @Override + public String getChannelId() { + return channelId; + } + + @Override + public Record getRecord() { + return record; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RandomString.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RandomString.java index cc912bb7..54beeee1 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RandomString.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RandomString.java @@ -25,33 +25,33 @@ public final class RandomString { - private static final char[] symbols = new char[36]; - - static { - for (int idx = 0; idx < 10; ++idx) { - symbols[idx] = (char) ('0' + idx); - } - for (int idx = 10; idx < 36; ++idx) { - symbols[idx] = (char) ('a' + idx - 10); - } - } - - private final Random random = new Random(); - - private final char[] buf; - - public RandomString(int length) { - if (length < 1) { - throw new IllegalArgumentException("length < 1: " + length); - } - buf = new char[length]; - } - - public String nextString() { - for (int idx = 0; idx < buf.length; ++idx) { - buf[idx] = symbols[random.nextInt(symbols.length)]; - } - return new String(buf); - } + private static final char[] symbols = new char[36]; + + static { + for (int idx = 0; idx < 10; ++idx) { + symbols[idx] = (char) ('0' + idx); + } + for (int idx = 10; idx < 36; ++idx) { + symbols[idx] = (char) ('a' + idx - 10); + } + } + + private final Random random = new Random(); + + private final char[] buf; + + public RandomString(int length) { + if (length < 1) { + throw new IllegalArgumentException("length < 1: " + length); + } + buf = new char[length]; + } + + public String nextString() { + for (int idx = 0; idx < buf.length; ++idx) { + buf[idx] = symbols[random.nextInt(symbols.length)]; + } + return new String(buf); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ReadTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ReadTask.java index 26d3c898..21d52e47 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ReadTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ReadTask.java @@ -20,9 +20,6 @@ */ package org.openmuc.framework.core.datamanager; -import java.util.List; -import java.util.concurrent.CountDownLatch; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.dataaccess.DeviceState; @@ -31,101 +28,102 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.concurrent.CountDownLatch; + public class ReadTask extends DeviceTask { - private final static Logger logger = LoggerFactory.getLogger(ReadTask.class); - - private final CountDownLatch readTaskFinishedSignal; - List channelRecordContainers; - protected boolean methodNotExceptedExceptionThrown = false; - protected boolean unknownDriverExceptionThrown = false; - protected volatile boolean disabled = false; - - boolean running = false; - boolean startedLate = false; - - public ReadTask(DataManager dataManager, Device device, List selectedChannels, - CountDownLatch readTaskFinishedSignal) { - this.dataManager = dataManager; - this.device = device; - channelRecordContainers = selectedChannels; - this.readTaskFinishedSignal = readTaskFinishedSignal; - } - - @Override - public final void run() { - - try { - executeRead(); - } catch (UnsupportedOperationException e) { - methodNotExceptedExceptionThrown = true; - } catch (ConnectionException e) { - // Connection to device lost. Signal to device instance and end task without notifying DataManager - logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, - e.getMessage()); - - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.setRecord(new Record(Flag.ACCESS_METHOD_NOT_SUPPORTED)); - } - readTaskFinishedSignal.countDown(); - synchronized (dataManager.disconnected) { - dataManager.disconnected.add(device); - } - dataManager.interrupt(); - return; - } catch (Exception e) { - logger.warn("unexpected exception thrown by read funtion of driver ", e); - unknownDriverExceptionThrown = true; - } - - taskFinished(); - } - - @Override - public final DeviceTaskType getType() { - return DeviceTaskType.READ; - } - - @Override - public final void setDeviceState() { - device.state = DeviceState.READING; - } - - public final void deviceNotConnected() { - for (ChannelRecordContainer recordContainer : channelRecordContainers) { - recordContainer.setRecord(new Record(Flag.COMM_DEVICE_NOT_CONNECTED)); - } - taskAborted(); - } - - @SuppressWarnings("unchecked") - protected void executeRead() throws UnsupportedOperationException, ConnectionException { - device.connection.read((List) ((List) channelRecordContainers), true, ""); - } - - protected void taskFinished() { - disabled = true; - long now = System.currentTimeMillis(); - if (methodNotExceptedExceptionThrown) { - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.setRecord(new Record(null, now, Flag.ACCESS_METHOD_NOT_SUPPORTED)); - } - } - else if (unknownDriverExceptionThrown) { - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.setRecord(new Record(null, now, Flag.DRIVER_THREW_UNKNOWN_EXCEPTION)); - } - } - - readTaskFinishedSignal.countDown(); - - synchronized (dataManager.tasksFinished) { - dataManager.tasksFinished.add(this); - } - dataManager.interrupt(); - } - - protected void taskAborted() { - readTaskFinishedSignal.countDown(); - } + private final static Logger logger = LoggerFactory.getLogger(ReadTask.class); + + private final CountDownLatch readTaskFinishedSignal; + List channelRecordContainers; + protected boolean methodNotExceptedExceptionThrown = false; + protected boolean unknownDriverExceptionThrown = false; + protected volatile boolean disabled = false; + + boolean running = false; + boolean startedLate = false; + + public ReadTask(DataManager dataManager, Device device, List selectedChannels, CountDownLatch + readTaskFinishedSignal) { + this.dataManager = dataManager; + this.device = device; + channelRecordContainers = selectedChannels; + this.readTaskFinishedSignal = readTaskFinishedSignal; + } + + @Override + public final void run() { + + try { + executeRead(); + } catch (UnsupportedOperationException e) { + methodNotExceptedExceptionThrown = true; + } catch (ConnectionException e) { + // Connection to device lost. Signal to device instance and end task without notifying DataManager + logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, e.getMessage()); + + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.setRecord(new Record(Flag.ACCESS_METHOD_NOT_SUPPORTED)); + } + readTaskFinishedSignal.countDown(); + synchronized (dataManager.disconnected) { + dataManager.disconnected.add(device); + } + dataManager.interrupt(); + return; + } catch (Exception e) { + logger.warn("unexpected exception thrown by read funtion of driver ", e); + unknownDriverExceptionThrown = true; + } + + taskFinished(); + } + + @Override + public final DeviceTaskType getType() { + return DeviceTaskType.READ; + } + + @Override + public final void setDeviceState() { + device.state = DeviceState.READING; + } + + public final void deviceNotConnected() { + for (ChannelRecordContainer recordContainer : channelRecordContainers) { + recordContainer.setRecord(new Record(Flag.COMM_DEVICE_NOT_CONNECTED)); + } + taskAborted(); + } + + @SuppressWarnings("unchecked") + protected void executeRead() throws UnsupportedOperationException, ConnectionException { + device.connection.read((List) ((List) channelRecordContainers), true, ""); + } + + protected void taskFinished() { + disabled = true; + long now = System.currentTimeMillis(); + if (methodNotExceptedExceptionThrown) { + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.setRecord(new Record(null, now, Flag.ACCESS_METHOD_NOT_SUPPORTED)); + } + } else if (unknownDriverExceptionThrown) { + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.setRecord(new Record(null, now, Flag.DRIVER_THREW_UNKNOWN_EXCEPTION)); + } + } + + readTaskFinishedSignal.countDown(); + + synchronized (dataManager.tasksFinished) { + dataManager.tasksFinished.add(this); + } + dataManager.interrupt(); + } + + protected void taskAborted() { + readTaskFinishedSignal.countDown(); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RootConfigImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RootConfigImpl.java index 6dc69ada..fc09ade1 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RootConfigImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/RootConfigImpl.java @@ -21,226 +21,207 @@ package org.openmuc.framework.core.datamanager; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; +import org.openmuc.framework.config.*; +import org.openmuc.framework.datalogger.spi.LogChannel; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.ParseException; -import org.openmuc.framework.config.RootConfig; -import org.openmuc.framework.datalogger.spi.LogChannel; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; public final class RootConfigImpl implements RootConfig { - private String dataLogSource = null; + private String dataLogSource = null; - final HashMap driverConfigsById = new LinkedHashMap(); - final HashMap deviceConfigsById = new HashMap(); - final HashMap channelConfigsById = new HashMap(); + final HashMap driverConfigsById = new LinkedHashMap(); + final HashMap deviceConfigsById = new HashMap(); + final HashMap channelConfigsById = new HashMap(); - // TODO really needed?: - List logChannels; + // TODO really needed?: + List logChannels; - @Override - public String getDataLogSource() { - return dataLogSource; - } + @Override + public String getDataLogSource() { + return dataLogSource; + } - @Override - public void setDataLogSource(String source) { - dataLogSource = source; - } - - static RootConfigImpl createFromFile(File configFile) throws ParseException, FileNotFoundException { - if (configFile == null) { - throw new NullPointerException("configFileName is null or the empty string."); - } - - if (!configFile.exists()) { - throw new FileNotFoundException(); - } - - DocumentBuilderFactory docBFac = DocumentBuilderFactory.newInstance(); - docBFac.setIgnoringComments(true); - - Document doc; - try { - doc = docBFac.newDocumentBuilder().parse(configFile); - } catch (Exception e) { - throw new ParseException(e); - } - - Node rootNode = doc.getDocumentElement(); - - if (!rootNode.getNodeName().equals("configuration")) { - throw new ParseException("root node in configuration is not of type \"configuration\""); - } - - return getRootConfigFromDomNode(rootNode); - - } - - static RootConfigImpl getRootConfigFromDomNode(Node rootConfigNode) throws ParseException { - - RootConfigImpl rootConfig = new RootConfigImpl(); - - NodeList rootConfigChildren = rootConfigNode.getChildNodes(); - - for (int i = 0; i < rootConfigChildren.getLength(); i++) { - Node childNode = rootConfigChildren.item(i); - String childName = childNode.getNodeName(); - if (childName.equals("#text")) { - continue; - } - else if (childName.equals("driver")) { - DriverConfigImpl.addDriverFromDomNode(childNode, rootConfig); - } - else if (childName.equals("dataLogSource")) { - rootConfig.dataLogSource = childNode.getTextContent(); - } - else { - throw new ParseException("found unknown tag:" + childName); - } - } - - return rootConfig; - } - - void writeToFile(File configFile) throws TransformerFactoryConfigurationError, IOException, - ParserConfigurationException, TransformerException { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - - StreamResult result = new StreamResult(new FileWriter(configFile)); - - DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = docBuild.newDocument(); - - doc.appendChild(getDomElement(doc)); - DOMSource source = new DOMSource(doc); - transformer.transform(source, result); - - } - - Element getDomElement(Document document) { - Element rootConfigElement = document.createElement("configuration"); - - if (dataLogSource != null) { - Node loggerChild = document.createElement("dataLogSource"); - loggerChild.setTextContent(dataLogSource); - rootConfigElement.appendChild(loggerChild); - } - - for (DriverConfig driverConfig : driverConfigsById.values()) { - rootConfigElement.appendChild(((DriverConfigImpl) driverConfig).getDomElement(document)); - } - - return rootConfigElement; - } - - @Override - public DriverConfig getOrAddDriver(String id) { - try { - return addDriver(id); - } catch (IdCollisionException e) { - return driverConfigsById.get(id); - } - } - - @Override - public DriverConfig addDriver(String id) throws IdCollisionException { - if (id == null) { - throw new IllegalArgumentException("The driver ID may not be null"); - } - ChannelConfigImpl.checkIdSyntax(id); - - if (driverConfigsById.containsKey(id)) { - throw new IdCollisionException("Collision with the driver ID:" + id); - } - DriverConfigImpl driverConfig = new DriverConfigImpl(id, this); - driverConfigsById.put(id, driverConfig); - return driverConfig; - } - - @Override - public DriverConfig getDriver(String id) { - return driverConfigsById.get(id); - } - - @Override - public DeviceConfig getDevice(String id) { - return deviceConfigsById.get(id); - } - - @Override - public ChannelConfig getChannel(String id) { - return channelConfigsById.get(id); - } - - @SuppressWarnings("unchecked") - @Override - public Collection getDrivers() { - return (Collection) (Collection) Collections - .unmodifiableCollection(driverConfigsById.values()); - } - - @Override - protected RootConfigImpl clone() { - RootConfigImpl configClone = new RootConfigImpl(); - configClone.dataLogSource = dataLogSource; - for (DriverConfigImpl driverConfig : driverConfigsById.values()) { - configClone.addDriver(driverConfig.clone(configClone)); - } - return configClone; - } - - RootConfigImpl cloneWithDefaults() { - RootConfigImpl configClone = new RootConfigImpl(); - if (dataLogSource != null) { - configClone.dataLogSource = dataLogSource; - } - else { - configClone.dataLogSource = ""; - } - for (DriverConfigImpl driverConfig : driverConfigsById.values()) { - configClone.addDriver(driverConfig.cloneWithDefaults(configClone)); - } - return configClone; - } - - private void addDriver(DriverConfigImpl driverConfig) { - driverConfigsById.put(driverConfig.getId(), driverConfig); - for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { - deviceConfigsById.put(deviceConfig.getId(), deviceConfig); - for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { - channelConfigsById.put(channelConfig.getId(), channelConfig); - } - } - } + @Override + public void setDataLogSource(String source) { + dataLogSource = source; + } + + static RootConfigImpl createFromFile(File configFile) throws ParseException, FileNotFoundException { + if (configFile == null) { + throw new NullPointerException("configFileName is null or the empty string."); + } + + if (!configFile.exists()) { + throw new FileNotFoundException(); + } + + DocumentBuilderFactory docBFac = DocumentBuilderFactory.newInstance(); + docBFac.setIgnoringComments(true); + + Document doc; + try { + doc = docBFac.newDocumentBuilder().parse(configFile); + } catch (Exception e) { + throw new ParseException(e); + } + + Node rootNode = doc.getDocumentElement(); + + if (!rootNode.getNodeName().equals("configuration")) { + throw new ParseException("root node in configuration is not of type \"configuration\""); + } + + return getRootConfigFromDomNode(rootNode); + + } + + static RootConfigImpl getRootConfigFromDomNode(Node rootConfigNode) throws ParseException { + + RootConfigImpl rootConfig = new RootConfigImpl(); + + NodeList rootConfigChildren = rootConfigNode.getChildNodes(); + + for (int i = 0; i < rootConfigChildren.getLength(); i++) { + Node childNode = rootConfigChildren.item(i); + String childName = childNode.getNodeName(); + if (childName.equals("#text")) { + continue; + } else if (childName.equals("driver")) { + DriverConfigImpl.addDriverFromDomNode(childNode, rootConfig); + } else if (childName.equals("dataLogSource")) { + rootConfig.dataLogSource = childNode.getTextContent(); + } else { + throw new ParseException("found unknown tag:" + childName); + } + } + + return rootConfig; + } + + void writeToFile(File configFile) throws TransformerFactoryConfigurationError, IOException, ParserConfigurationException, + TransformerException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + + StreamResult result = new StreamResult(new FileWriter(configFile)); + + DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = docBuild.newDocument(); + + doc.appendChild(getDomElement(doc)); + DOMSource source = new DOMSource(doc); + transformer.transform(source, result); + + } + + Element getDomElement(Document document) { + Element rootConfigElement = document.createElement("configuration"); + + if (dataLogSource != null) { + Node loggerChild = document.createElement("dataLogSource"); + loggerChild.setTextContent(dataLogSource); + rootConfigElement.appendChild(loggerChild); + } + + for (DriverConfig driverConfig : driverConfigsById.values()) { + rootConfigElement.appendChild(((DriverConfigImpl) driverConfig).getDomElement(document)); + } + + return rootConfigElement; + } + + @Override + public DriverConfig getOrAddDriver(String id) { + try { + return addDriver(id); + } catch (IdCollisionException e) { + return driverConfigsById.get(id); + } + } + + @Override + public DriverConfig addDriver(String id) throws IdCollisionException { + if (id == null) { + throw new IllegalArgumentException("The driver ID may not be null"); + } + ChannelConfigImpl.checkIdSyntax(id); + + if (driverConfigsById.containsKey(id)) { + throw new IdCollisionException("Collision with the driver ID:" + id); + } + DriverConfigImpl driverConfig = new DriverConfigImpl(id, this); + driverConfigsById.put(id, driverConfig); + return driverConfig; + } + + @Override + public DriverConfig getDriver(String id) { + return driverConfigsById.get(id); + } + + @Override + public DeviceConfig getDevice(String id) { + return deviceConfigsById.get(id); + } + + @Override + public ChannelConfig getChannel(String id) { + return channelConfigsById.get(id); + } + + @SuppressWarnings("unchecked") + @Override + public Collection getDrivers() { + return (Collection) (Collection) Collections.unmodifiableCollection(driverConfigsById.values()); + } + + @Override + protected RootConfigImpl clone() { + RootConfigImpl configClone = new RootConfigImpl(); + configClone.dataLogSource = dataLogSource; + for (DriverConfigImpl driverConfig : driverConfigsById.values()) { + configClone.addDriver(driverConfig.clone(configClone)); + } + return configClone; + } + + RootConfigImpl cloneWithDefaults() { + RootConfigImpl configClone = new RootConfigImpl(); + if (dataLogSource != null) { + configClone.dataLogSource = dataLogSource; + } else { + configClone.dataLogSource = ""; + } + for (DriverConfigImpl driverConfig : driverConfigsById.values()) { + configClone.addDriver(driverConfig.cloneWithDefaults(configClone)); + } + return configClone; + } + + private void addDriver(DriverConfigImpl driverConfig) { + driverConfigsById.put(driverConfig.getId(), driverConfig); + for (DeviceConfigImpl deviceConfig : driverConfig.deviceConfigsById.values()) { + deviceConfigsById.put(deviceConfig.getId(), deviceConfig); + for (ChannelConfigImpl channelConfig : deviceConfig.channelConfigsById.values()) { + channelConfigsById.put(channelConfig.getId(), channelConfig); + } + } + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/SamplingTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/SamplingTask.java index 092ab808..909951f8 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/SamplingTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/SamplingTask.java @@ -21,8 +21,6 @@ package org.openmuc.framework.core.datamanager; -import java.util.List; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.dataaccess.DeviceState; @@ -31,132 +29,128 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public final class SamplingTask extends DeviceTask { - private final static Logger logger = LoggerFactory.getLogger(SamplingTask.class); - - List channelRecordContainers; - private boolean methodNotExceptedExceptionThrown = false; - private boolean unknownDriverExceptionThrown = false; - private volatile boolean disabled = false; - - boolean running = false; - boolean startedLate = false; - String samplingGroup; - - public SamplingTask(DataManager dataManager, Device device, List selectedChannels, - String samplingGroup) { - this.dataManager = dataManager; - this.device = device; - channelRecordContainers = selectedChannels; - this.samplingGroup = samplingGroup; - } - - // called by main thread - public void storeValues() { - if (disabled) { - return; - } - disabled = true; - if (methodNotExceptedExceptionThrown) { - for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { - channelRecordContainer.channel.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); - } - } - else if (unknownDriverExceptionThrown) { - for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { - channelRecordContainer.channel.setFlag(Flag.DRIVER_THREW_UNKNOWN_EXCEPTION); - } - } - else { - for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { - channelRecordContainer.channel.setNewRecord(channelRecordContainer.record); - } - } - } - - @SuppressWarnings("unchecked") - protected void executeRead() throws UnsupportedOperationException, ConnectionException { - // TODO must pass containerListHandle - device.connection.read((List) ((List) channelRecordContainers), null, samplingGroup); - } - - protected void taskAborted() { - } - - @Override - public final void run() { - - try { - executeRead(); - } catch (UnsupportedOperationException e) { - methodNotExceptedExceptionThrown = true; - } catch (ConnectionException e) { - // Connection to device lost. Signal to device instance and end task without notifying DataManager - logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, - e.getMessage()); - - synchronized (dataManager.disconnected) { - dataManager.disconnected.add(device); - } - dataManager.interrupt(); - return; - } catch (Exception e) { - logger.warn("unexpected exception thrown by read funtion of driver ", e); - unknownDriverExceptionThrown = true; - } - - for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { - channelRecordContainer.channel.handle = channelRecordContainer.getChannelHandle(); - } - - synchronized (dataManager.samplingTaskFinished) { - dataManager.samplingTaskFinished.add(this); - } - dataManager.interrupt(); - } - - // called by main thread - public final void timeout() { - if (disabled) { - return; - } - - disabled = true; - if (startedLate) { - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.channel.setFlag(Flag.STARTED_LATE_AND_TIMED_OUT); - } - } - else if (running) { - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.channel.setFlag(Flag.TIMEOUT); - } - } - else { - for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { - driverChannel.channel.setFlag(Flag.DEVICE_OR_INTERFACE_BUSY); - } - device.removeTask(this); - } - - } - - @Override - public final DeviceTaskType getType() { - return DeviceTaskType.SAMPLE; - } - - @Override - public final void setDeviceState() { - device.state = DeviceState.READING; - } - - public final void deviceNotConnected() { - for (ChannelRecordContainer recordContainer : channelRecordContainers) { - recordContainer.setRecord(new Record(Flag.COMM_DEVICE_NOT_CONNECTED)); - } - taskAborted(); - } + private final static Logger logger = LoggerFactory.getLogger(SamplingTask.class); + + List channelRecordContainers; + private boolean methodNotExceptedExceptionThrown = false; + private boolean unknownDriverExceptionThrown = false; + private volatile boolean disabled = false; + + boolean running = false; + boolean startedLate = false; + String samplingGroup; + + public SamplingTask(DataManager dataManager, Device device, List selectedChannels, String samplingGroup) { + this.dataManager = dataManager; + this.device = device; + channelRecordContainers = selectedChannels; + this.samplingGroup = samplingGroup; + } + + // called by main thread + public void storeValues() { + if (disabled) { + return; + } + disabled = true; + if (methodNotExceptedExceptionThrown) { + for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { + channelRecordContainer.channel.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); + } + } else if (unknownDriverExceptionThrown) { + for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { + channelRecordContainer.channel.setFlag(Flag.DRIVER_THREW_UNKNOWN_EXCEPTION); + } + } else { + for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { + channelRecordContainer.channel.setNewRecord(channelRecordContainer.record); + } + } + } + + @SuppressWarnings("unchecked") + protected void executeRead() throws UnsupportedOperationException, ConnectionException { + // TODO must pass containerListHandle + device.connection.read((List) ((List) channelRecordContainers), null, samplingGroup); + } + + protected void taskAborted() { + } + + @Override + public final void run() { + + try { + executeRead(); + } catch (UnsupportedOperationException e) { + methodNotExceptedExceptionThrown = true; + } catch (ConnectionException e) { + // Connection to device lost. Signal to device instance and end task without notifying DataManager + logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, e.getMessage()); + + synchronized (dataManager.disconnected) { + dataManager.disconnected.add(device); + } + dataManager.interrupt(); + return; + } catch (Exception e) { + logger.warn("unexpected exception thrown by read funtion of driver ", e); + unknownDriverExceptionThrown = true; + } + + for (ChannelRecordContainerImpl channelRecordContainer : channelRecordContainers) { + channelRecordContainer.channel.handle = channelRecordContainer.getChannelHandle(); + } + + synchronized (dataManager.samplingTaskFinished) { + dataManager.samplingTaskFinished.add(this); + } + dataManager.interrupt(); + } + + // called by main thread + public final void timeout() { + if (disabled) { + return; + } + + disabled = true; + if (startedLate) { + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.channel.setFlag(Flag.STARTED_LATE_AND_TIMED_OUT); + } + } else if (running) { + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.channel.setFlag(Flag.TIMEOUT); + } + } else { + for (ChannelRecordContainerImpl driverChannel : channelRecordContainers) { + driverChannel.channel.setFlag(Flag.DEVICE_OR_INTERFACE_BUSY); + } + device.removeTask(this); + } + + } + + @Override + public final DeviceTaskType getType() { + return DeviceTaskType.SAMPLE; + } + + @Override + public final void setDeviceState() { + device.state = DeviceState.READING; + } + + public final void deviceNotConnected() { + for (ChannelRecordContainer recordContainer : channelRecordContainers) { + recordContainer.setRecord(new Record(Flag.COMM_DEVICE_NOT_CONNECTED)); + } + taskAborted(); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ScanForDevicesTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ScanForDevicesTask.java index a8928e54..dab88399 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ScanForDevicesTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/ScanForDevicesTask.java @@ -20,68 +20,64 @@ */ package org.openmuc.framework.core.datamanager; -import java.util.ArrayList; -import java.util.List; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DeviceScanListener; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; import org.openmuc.framework.driver.spi.DriverService; +import java.util.ArrayList; +import java.util.List; + public class ScanForDevicesTask implements Runnable { - private final DriverService driver; - private final String settings; - private final DeviceScanListener listener; + private final DriverService driver; + private final String settings; + private final DeviceScanListener listener; - public ScanForDevicesTask(DriverService driver, String settings, DeviceScanListener listener) { - this.driver = driver; - this.settings = settings; - this.listener = listener; - } + public ScanForDevicesTask(DriverService driver, String settings, DeviceScanListener listener) { + this.driver = driver; + this.settings = settings; + this.listener = listener; + } - @Override - public void run() { - try { - driver.scanForDevices(settings, new NonBlockingScanListener(listener)); - } catch (UnsupportedOperationException e) { - listener.scanError("Device scan not supported by driver"); - return; - } catch (ArgumentSyntaxException e) { - listener.scanError("Scan settings syntax invalid: " + e.getMessage()); - return; - } catch (ScanException e) { - listener.scanError("IOException while scanning: " + e.getMessage()); - return; - } catch (ScanInterruptedException e) { - listener.scanInterrupted(); - return; - } - listener.scanFinished(); - } + @Override + public void run() { + try { + driver.scanForDevices(settings, new NonBlockingScanListener(listener)); + } catch (UnsupportedOperationException e) { + listener.scanError("Device scan not supported by driver"); + return; + } catch (ArgumentSyntaxException e) { + listener.scanError("Scan settings syntax invalid: " + e.getMessage()); + return; + } catch (ScanException e) { + listener.scanError("IOException while scanning: " + e.getMessage()); + return; + } catch (ScanInterruptedException e) { + listener.scanInterrupted(); + return; + } + listener.scanFinished(); + } - class NonBlockingScanListener implements DriverDeviceScanListener { - List scanInfos = new ArrayList(); - DeviceScanListener listener; + class NonBlockingScanListener implements DriverDeviceScanListener { + List scanInfos = new ArrayList(); + DeviceScanListener listener; - public NonBlockingScanListener(DeviceScanListener listener) { - this.listener = listener; - } + public NonBlockingScanListener(DeviceScanListener listener) { + this.listener = listener; + } - @Override - public void scanProgressUpdate(int progress) { - listener.scanProgress(progress); - } + @Override + public void scanProgressUpdate(int progress) { + listener.scanProgress(progress); + } - @Override - public void deviceFound(DeviceScanInfo scanInfo) { - if (!scanInfos.contains(scanInfo)) { - scanInfos.add(scanInfo); - listener.deviceFound(scanInfo); - } - } - } + @Override + public void deviceFound(DeviceScanInfo scanInfo) { + if (!scanInfos.contains(scanInfo)) { + scanInfos.add(scanInfo); + listener.deviceFound(scanInfo); + } + } + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/StartListeningTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/StartListeningTask.java index 641d1674..6cf6e82f 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/StartListeningTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/StartListeningTask.java @@ -21,8 +21,6 @@ package org.openmuc.framework.core.datamanager; -import java.util.List; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.dataaccess.DeviceState; import org.openmuc.framework.driver.spi.ChannelRecordContainer; @@ -30,55 +28,55 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public final class StartListeningTask extends DeviceTask { - private final static Logger logger = LoggerFactory.getLogger(StartListeningTask.class); + private final static Logger logger = LoggerFactory.getLogger(StartListeningTask.class); - List selectedChannels; + List selectedChannels; - public StartListeningTask(DataManager dataManager, Device device, List selectedChannels) { - this.dataManager = dataManager; - this.device = device; - this.selectedChannels = selectedChannels; - } + public StartListeningTask(DataManager dataManager, Device device, List selectedChannels) { + this.dataManager = dataManager; + this.device = device; + this.selectedChannels = selectedChannels; + } - @Override - @SuppressWarnings("unchecked") - public void run() { + @Override + @SuppressWarnings("unchecked") + public void run() { - try { - device.connection.startListening((List) ((List) selectedChannels), dataManager); - } catch (UnsupportedOperationException e) { - for (ChannelRecordContainer channelRecordContainer : selectedChannels) { - ((ChannelRecordContainerImpl) channelRecordContainer).channel.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); - } - } catch (ConnectionException e) { - // Connection to device lost. Signal to device instance and end task - // without notifying DataManager - logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, - e.getMessage()); - device.disconnectedSignal(); - return; - } catch (Exception e) { - logger.error("unexpected exception by startListeningFor funtion of driver: " - + device.deviceConfig.driverParent.id, e); - // TODO set flag? - } + try { + device.connection.startListening((List) ((List) selectedChannels), dataManager); + } catch (UnsupportedOperationException e) { + for (ChannelRecordContainer channelRecordContainer : selectedChannels) { + ((ChannelRecordContainerImpl) channelRecordContainer).channel.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); + } + } catch (ConnectionException e) { + // Connection to device lost. Signal to device instance and end task + // without notifying DataManager + logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, e.getMessage()); + device.disconnectedSignal(); + return; + } catch (Exception e) { + logger.error("unexpected exception by startListeningFor funtion of driver: " + device.deviceConfig.driverParent.id, e); + // TODO set flag? + } - synchronized (dataManager.tasksFinished) { - dataManager.tasksFinished.add(this); - } - dataManager.interrupt(); - } + synchronized (dataManager.tasksFinished) { + dataManager.tasksFinished.add(this); + } + dataManager.interrupt(); + } - @Override - public DeviceTaskType getType() { - return DeviceTaskType.START_LISTENING_FOR; - } + @Override + public DeviceTaskType getType() { + return DeviceTaskType.START_LISTENING_FOR; + } - @Override - public void setDeviceState() { - device.state = DeviceState.STARTING_TO_LISTEN; - } + @Override + public void setDeviceState() { + device.state = DeviceState.STARTING_TO_LISTEN; + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteTask.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteTask.java index 2ab5c6fe..1542b1ef 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteTask.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteTask.java @@ -21,9 +21,6 @@ package org.openmuc.framework.core.datamanager; -import java.util.List; -import java.util.concurrent.CountDownLatch; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.dataaccess.DeviceState; import org.openmuc.framework.driver.spi.ChannelValueContainer; @@ -31,74 +28,76 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.concurrent.CountDownLatch; + public final class WriteTask extends DeviceTask { - private final static Logger logger = LoggerFactory.getLogger(WriteTask.class); + private final static Logger logger = LoggerFactory.getLogger(WriteTask.class); - private final CountDownLatch writeTaskFinishedSignal; - List writeValueContainers; + private final CountDownLatch writeTaskFinishedSignal; + List writeValueContainers; - public WriteTask(DataManager dataManager, Device device, List writeValueContainers, - CountDownLatch writeTaskFinishedSignal) { - this.dataManager = dataManager; - this.device = device; - this.writeTaskFinishedSignal = writeTaskFinishedSignal; - this.writeValueContainers = writeValueContainers; - } + public WriteTask(DataManager dataManager, Device device, List writeValueContainers, CountDownLatch + writeTaskFinishedSignal) { + this.dataManager = dataManager; + this.device = device; + this.writeTaskFinishedSignal = writeTaskFinishedSignal; + this.writeValueContainers = writeValueContainers; + } - @Override - @SuppressWarnings("unchecked") - public void run() { + @Override + @SuppressWarnings("unchecked") + public void run() { - try { - device.connection.write((List) ((List) writeValueContainers), null); - } catch (UnsupportedOperationException e) { - for (WriteValueContainerImpl valueContainer : writeValueContainers) { - valueContainer.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); - } - } catch (ConnectionException e) { - // Connection to device lost. Signal to device instance and end task without notifying DataManager - logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, - e.getMessage()); - for (WriteValueContainerImpl valueContainer : writeValueContainers) { - valueContainer.setFlag(Flag.CONNECTION_EXCEPTION); - } - writeTaskFinishedSignal.countDown(); - synchronized (dataManager.disconnected) { - dataManager.disconnected.add(device); - } - dataManager.interrupt(); - return; - } catch (Exception e) { - logger.warn("unexpected exception thrown by write funtion of driver ", e); - for (WriteValueContainerImpl valueContainer : writeValueContainers) { - valueContainer.setFlag(Flag.DRIVER_THREW_UNKNOWN_EXCEPTION); - } - } + try { + device.connection.write((List) ((List) writeValueContainers), null); + } catch (UnsupportedOperationException e) { + for (WriteValueContainerImpl valueContainer : writeValueContainers) { + valueContainer.setFlag(Flag.ACCESS_METHOD_NOT_SUPPORTED); + } + } catch (ConnectionException e) { + // Connection to device lost. Signal to device instance and end task without notifying DataManager + logger.warn("Connection to device {} lost because {}. Trying to reconnect...", device.deviceConfig.id, e.getMessage()); + for (WriteValueContainerImpl valueContainer : writeValueContainers) { + valueContainer.setFlag(Flag.CONNECTION_EXCEPTION); + } + writeTaskFinishedSignal.countDown(); + synchronized (dataManager.disconnected) { + dataManager.disconnected.add(device); + } + dataManager.interrupt(); + return; + } catch (Exception e) { + logger.warn("unexpected exception thrown by write funtion of driver ", e); + for (WriteValueContainerImpl valueContainer : writeValueContainers) { + valueContainer.setFlag(Flag.DRIVER_THREW_UNKNOWN_EXCEPTION); + } + } - writeTaskFinishedSignal.countDown(); - synchronized (dataManager.tasksFinished) { - dataManager.tasksFinished.add(this); - } - dataManager.interrupt(); + writeTaskFinishedSignal.countDown(); + synchronized (dataManager.tasksFinished) { + dataManager.tasksFinished.add(this); + } + dataManager.interrupt(); - } + } - @Override - public DeviceTaskType getType() { - return DeviceTaskType.WRITE; - } + @Override + public DeviceTaskType getType() { + return DeviceTaskType.WRITE; + } - @Override - public void setDeviceState() { - device.state = DeviceState.WRITING; - } + @Override + public void setDeviceState() { + device.state = DeviceState.WRITING; + } - public void deviceNotConnected() { - for (WriteValueContainerImpl valueContainer : writeValueContainers) { - valueContainer.setFlag(Flag.COMM_DEVICE_NOT_CONNECTED); - } - writeTaskFinishedSignal.countDown(); - } + public void deviceNotConnected() { + for (WriteValueContainerImpl valueContainer : writeValueContainers) { + valueContainer.setFlag(Flag.COMM_DEVICE_NOT_CONNECTED); + } + writeTaskFinishedSignal.countDown(); + } } diff --git a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteValueContainerImpl.java b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteValueContainerImpl.java index 03e6c8ca..5fac3cd0 100644 --- a/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteValueContainerImpl.java +++ b/projects/core/datamanager/src/main/java/org/openmuc/framework/core/datamanager/WriteValueContainerImpl.java @@ -29,56 +29,56 @@ public final class WriteValueContainerImpl implements WriteValueContainer, ChannelValueContainer { - ChannelImpl channel; - private Value value = null; - private Flag flag = Flag.DRIVER_ERROR_UNSPECIFIED; - Object channelHandle; - String channelAddress; + ChannelImpl channel; + private Value value = null; + private Flag flag = Flag.DRIVER_ERROR_UNSPECIFIED; + Object channelHandle; + String channelAddress; - public WriteValueContainerImpl(ChannelImpl channel) { - this.channel = channel; - channelAddress = channel.config.channelAddress; - channelHandle = channel.handle; - } + public WriteValueContainerImpl(ChannelImpl channel) { + this.channel = channel; + channelAddress = channel.config.channelAddress; + channelHandle = channel.handle; + } - @Override - public void setValue(Value value) { - this.value = value; - } + @Override + public void setValue(Value value) { + this.value = value; + } - @Override - public Value getValue() { - return value; - } + @Override + public Value getValue() { + return value; + } - @Override - public Flag getFlag() { - return flag; - } + @Override + public Flag getFlag() { + return flag; + } - @Override - public Channel getChannel() { - return channel; - } + @Override + public Channel getChannel() { + return channel; + } - @Override - public String getChannelAddress() { - return channelAddress; - } + @Override + public String getChannelAddress() { + return channelAddress; + } - @Override - public Object getChannelHandle() { - return channelHandle; - } + @Override + public Object getChannelHandle() { + return channelHandle; + } - @Override - public void setChannelHandle(Object handle) { - channelHandle = handle; - } + @Override + public void setChannelHandle(Object handle) { + channelHandle = handle; + } - @Override - public void setFlag(Flag flag) { - this.flag = flag; - } + @Override + public void setFlag(Flag flag) { + this.flag = flag; + } } diff --git a/projects/core/datamanager/src/main/resources/OSGI-INF/authentication.xml b/projects/core/datamanager/src/main/resources/OSGI-INF/authentication.xml index 3b09b33d..34787938 100644 --- a/projects/core/datamanager/src/main/resources/OSGI-INF/authentication.xml +++ b/projects/core/datamanager/src/main/resources/OSGI-INF/authentication.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/core/datamanager/src/main/resources/OSGI-INF/components.xml b/projects/core/datamanager/src/main/resources/OSGI-INF/components.xml index f3b688e6..0c469f92 100644 --- a/projects/core/datamanager/src/main/resources/OSGI-INF/components.xml +++ b/projects/core/datamanager/src/main/resources/OSGI-INF/components.xml @@ -1,26 +1,26 @@ - - - - - - - - + + + + + + + + diff --git a/projects/core/spi/build.gradle b/projects/core/spi/build.gradle index de5a5a73..a1ae7a50 100644 --- a/projects/core/spi/build.gradle +++ b/projects/core/spi/build.gradle @@ -1,11 +1,10 @@ - dependencies { - compile project(':openmuc-core-api') + compile project(':openmuc-core-api') } jar { - manifest { - name = "OpenMUC Core - SPI" - instruction 'Export-Package', '*' - } + manifest { + name = "OpenMUC Core - SPI" + instruction 'Export-Package', '*' + } } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/DataLoggerService.java b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/DataLoggerService.java index 4fb58f4d..1e6eaf21 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/DataLoggerService.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/DataLoggerService.java @@ -21,34 +21,30 @@ package org.openmuc.framework.datalogger.spi; +import org.openmuc.framework.data.Record; + import java.io.IOException; import java.util.List; -import org.openmuc.framework.data.Record; - public interface DataLoggerService { - public String getId(); - - public void setChannelsToLog(List channels); - - public void log(List containers, long timestamp); - - /** - * Returns a list of all logged data records with timestamps from startTime to endTime for - * the channel with the given channelId. - * - * @param channelId - * the channel ID. - * @param startTime - * the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive - * @param endTime - * the ending time in milliseconds since midnight, January 1, 1970 UTC. inclusive - * @return a list of all logged data records with timestamps from startTime to endTime for - * the channel with the given channelId. - * @throws IOException - * if any kind of error occurs accessing the logged data. - */ - public List getRecords(String channelId, long startTime, long endTime) throws IOException; + public String getId(); + + public void setChannelsToLog(List channels); + + public void log(List containers, long timestamp); + + /** + * Returns a list of all logged data records with timestamps from startTime to endTime for + * the channel with the given channelId. + * + * @param channelId the channel ID. + * @param startTime the starting time in milliseconds since midnight, January 1, 1970 UTC. inclusive + * @param endTime the ending time in milliseconds since midnight, January 1, 1970 UTC. inclusive + * @return a list of all logged data records with timestamps from startTime to endTime for + * the channel with the given channelId. + * @throws IOException if any kind of error occurs accessing the logged data. + */ + public List getRecords(String channelId, long startTime, long endTime) throws IOException; } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogChannel.java b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogChannel.java index a1f236da..680d9605 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogChannel.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogChannel.java @@ -25,18 +25,18 @@ public interface LogChannel { - public String getId(); + public String getId(); - public String getDescription(); + public String getDescription(); - public String getUnit(); + public String getUnit(); - public ValueType getValueType(); + public ValueType getValueType(); - public Integer getValueTypeLength(); + public Integer getValueTypeLength(); - public Integer getLoggingInterval(); + public Integer getLoggingInterval(); - public Integer getLoggingTimeOffset(); + public Integer getLoggingTimeOffset(); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogRecordContainer.java b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogRecordContainer.java index f89e53c2..74ac6455 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogRecordContainer.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/datalogger/spi/LogRecordContainer.java @@ -25,8 +25,8 @@ public interface LogRecordContainer { - public String getChannelId(); + public String getChannelId(); - public Record getRecord(); + public Record getRecord(); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelRecordContainer.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelRecordContainer.java index b6fbd7b4..93b23cbb 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelRecordContainer.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelRecordContainer.java @@ -26,14 +26,14 @@ public interface ChannelRecordContainer extends ReadRecordContainer { - public String getChannelAddress(); + public String getChannelAddress(); - public Object getChannelHandle(); + public Object getChannelHandle(); - public void setChannelHandle(Object handle); + public void setChannelHandle(Object handle); - public void setRecord(Record record); + public void setRecord(Record record); - public ChannelRecordContainer copy(); + public ChannelRecordContainer copy(); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelValueContainer.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelValueContainer.java index 17acf8fc..8058d9c0 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelValueContainer.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ChannelValueContainer.java @@ -26,15 +26,15 @@ public interface ChannelValueContainer { - String getChannelAddress(); + String getChannelAddress(); - Object getChannelHandle(); + Object getChannelHandle(); - void setChannelHandle(Object handle); + void setChannelHandle(Object handle); - Value getValue(); + Value getValue(); - void setFlag(Flag flag); + void setFlag(Flag flag); - Flag getFlag(); + Flag getFlag(); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/Connection.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/Connection.java index 118c4b31..030a6fd1 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/Connection.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/Connection.java @@ -20,17 +20,16 @@ */ package org.openmuc.framework.driver.spi; -import java.util.List; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.config.ScanException; +import java.util.List; + /** - * * A connection represents an association to particular device. A driver returns an implementation of this interface * when {@link DriverService#connect(String, String)} is called. - * + *

    * The OpenMUC framework can give certain guarantees about the order of the functions it calls: *

      *
    • Communication related functions (e.g. connect,read,write..) are never called concurrently for the same device.
    • @@ -39,106 +38,85 @@ *
    • Before a driver service is unregistered or the data manager is stopped the framework calls disconnect for all * connected devices. The disconnect function should do any necessary resource clean up.
    • *
    - * - * @author Stefan Feuerhahn * + * @author Stefan Feuerhahn */ public interface Connection { - /** - * Scan a given communication device for available data channels. - * - * @param settings - * scanning settings. The syntax is driver specific. - * @return A list of channels that were found. - * @throws ArgumentSyntaxException - * if the syntax of the deviceAddress or settings string is incorrect. - * @throws UnsupportedOperationException - * if the method is not implemented by the driver. - * @throws ScanException - * if an error occurs while scanning but the connection is still alive. - * @throws ConnectionException - * if an error occurs while scanning and the connection was closed - */ - public List scanForChannels(String settings) throws UnsupportedOperationException, - ArgumentSyntaxException, ScanException, ConnectionException; + /** + * Scan a given communication device for available data channels. + * + * @param settings scanning settings. The syntax is driver specific. + * @return A list of channels that were found. + * @throws ArgumentSyntaxException if the syntax of the deviceAddress or settings string is incorrect. + * @throws UnsupportedOperationException if the method is not implemented by the driver. + * @throws ScanException if an error occurs while scanning but the connection is still alive. + * @throws ConnectionException if an error occurs while scanning and the connection was closed + */ + public List scanForChannels(String settings) throws UnsupportedOperationException, ArgumentSyntaxException, + ScanException, ConnectionException; - /** - * Reads the data channels that correspond to the given record containers. The read result is returned by setting - * the record in the containers. If for some reason no value can be read the record should be set anyways. In this - * case the record constructor that takes only a flag should be used. The flag shall best describe the reason of - * failure. If no record is set the default Flag is Flag.DRIVER_ERROR_UNSPECIFIED. If the connection to - * the device is interrupted, then any necessary resources that correspond to this connection should be cleaned up - * and a ConnectionException shall be thrown. - * - * @param containers - * the containers hold the information of what channels are to be read. They will be filled by this - * function with the records read. - * @param containerListHandle - * the containerListHandle returned by the last read call for this exact list of containers. Will be - * equal to null if this is the first read call for this container list after a connection - * has been established. Driver implementations can optionally use this object to improve the read - * performance. - * @param samplingGroup - * the samplingGroup that was configured for this list of channels that are to be read. Sometimes it may - * be desirable to give the driver a hint on how to group several channels when reading them. This can - * done through the samplingGroup. - * @return the containerListHandle Object that will passed the next time the same list of channels is to be read. - * Use this Object as a handle to improve performance or simply return null. - * @throws UnsupportedOperationException - * if the method is not implemented by the driver. - * @throws ConnectionException - * if the connection to the device was interrupted. - */ - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException; + /** + * Reads the data channels that correspond to the given record containers. The read result is returned by setting + * the record in the containers. If for some reason no value can be read the record should be set anyways. In this + * case the record constructor that takes only a flag should be used. The flag shall best describe the reason of + * failure. If no record is set the default Flag is Flag.DRIVER_ERROR_UNSPECIFIED. If the connection to + * the device is interrupted, then any necessary resources that correspond to this connection should be cleaned up + * and a ConnectionException shall be thrown. + * + * @param containers the containers hold the information of what channels are to be read. They will be filled by this + * function with the records read. + * @param containerListHandle the containerListHandle returned by the last read call for this exact list of containers. Will be + * equal to null if this is the first read call for this container list after a connection + * has been established. Driver implementations can optionally use this object to improve the read + * performance. + * @param samplingGroup the samplingGroup that was configured for this list of channels that are to be read. Sometimes it may + * be desirable to give the driver a hint on how to group several channels when reading them. This can + * done through the samplingGroup. + * @return the containerListHandle Object that will passed the next time the same list of channels is to be read. + * Use this Object as a handle to improve performance or simply return null. + * @throws UnsupportedOperationException if the method is not implemented by the driver. + * @throws ConnectionException if the connection to the device was interrupted. + */ + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException; - /** - * Starts listening on the given connection for data from the channels that correspond to the given record - * containers. The list of containers will overwrite the list passed by the previous startListening call. Will - * notify the given listener of new records that arrive on the data channels. - * - * @param containers - * the containers identify the channels to listen on. They will be filled by this function with the - * records received and passed to the listener. - * @param listener - * the listener to inform that new data has arrived. - * @throws UnsupportedOperationException - * if the method is not implemented by the driver. - * @throws ConnectionException - * if the connection to the device was interrupted. - */ - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException; + /** + * Starts listening on the given connection for data from the channels that correspond to the given record + * containers. The list of containers will overwrite the list passed by the previous startListening call. Will + * notify the given listener of new records that arrive on the data channels. + * + * @param containers the containers identify the channels to listen on. They will be filled by this function with the + * records received and passed to the listener. + * @param listener the listener to inform that new data has arrived. + * @throws UnsupportedOperationException if the method is not implemented by the driver. + * @throws ConnectionException if the connection to the device was interrupted. + */ + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException, ConnectionException; - /** - * Writes the data channels that correspond to the given value containers. The write result is returned by setting - * the flag in the containers. If the connection to the device is interrupted, then any necessary resources that - * correspond to this connection should be cleaned up and a ConnectionException shall be thrown. - * - * @param containers - * the containers hold the information of what channels are to be written and the values that are to - * written. They will be filled by this function with a flag stating whether the write process was - * successful or not. - * @param containerListHandle - * the containerListHandle returned by the last write call for this exact list of containers. Will be - * equal to null if this is the first read call for this container list after a connection - * has been established. Driver implementations can optionally use this object to improve the write - * performance. - * @return the containerListHandle Object that will passed the next time the same list of channels is to be written. - * Use this Object as a handle to improve performance or simply return null. - * @throws UnsupportedOperationException - * if the method is not implemented by the driver. - * @throws ConnectionException - * if the connection to the device was interrupted. - */ - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException; + /** + * Writes the data channels that correspond to the given value containers. The write result is returned by setting + * the flag in the containers. If the connection to the device is interrupted, then any necessary resources that + * correspond to this connection should be cleaned up and a ConnectionException shall be thrown. + * + * @param containers the containers hold the information of what channels are to be written and the values that are to + * written. They will be filled by this function with a flag stating whether the write process was + * successful or not. + * @param containerListHandle the containerListHandle returned by the last write call for this exact list of containers. Will be + * equal to null if this is the first read call for this container list after a connection + * has been established. Driver implementations can optionally use this object to improve the write + * performance. + * @return the containerListHandle Object that will passed the next time the same list of channels is to be written. + * Use this Object as a handle to improve performance or simply return null. + * @throws UnsupportedOperationException if the method is not implemented by the driver. + * @throws ConnectionException if the connection to the device was interrupted. + */ + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException; - /** - * Disconnects or closes the connection. Cleans up any resources associated with the connection. - * - */ - public void disconnect(); + /** + * Disconnects or closes the connection. Cleans up any resources associated with the connection. + */ + public void disconnect(); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ConnectionException.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ConnectionException.java index 565be7d3..e8aa3ff8 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ConnectionException.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/ConnectionException.java @@ -23,22 +23,22 @@ public class ConnectionException extends Exception { - private static final long serialVersionUID = 4361169138720682346L; + private static final long serialVersionUID = 4361169138720682346L; - public ConnectionException() { - super(); - } + public ConnectionException() { + super(); + } - public ConnectionException(String s) { - super(s); - } + public ConnectionException(String s) { + super(s); + } - public ConnectionException(Throwable cause) { - super(cause); - } + public ConnectionException(Throwable cause) { + super(cause); + } - public ConnectionException(String s, Throwable cause) { - super(s, cause); - } + public ConnectionException(String s, Throwable cause) { + super(s, cause); + } } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverDeviceScanListener.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverDeviceScanListener.java index 7cae2a7d..e0b8a8ee 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverDeviceScanListener.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverDeviceScanListener.java @@ -24,21 +24,19 @@ public interface DriverDeviceScanListener { - /** - * Can optionally be used by driver to let the Data Manager know about the device scan progress in percent. - * Applications can access this value through the ConfigService. - * - * @param progress - * the progress in percent. - */ - void scanProgressUpdate(int progress); + /** + * Can optionally be used by driver to let the Data Manager know about the device scan progress in percent. + * Applications can access this value through the ConfigService. + * + * @param progress the progress in percent. + */ + void scanProgressUpdate(int progress); - /** - * Is used by the driver to notify the Data Manager of new devices found during a scan. - * - * @param scanInfo - * the information obtained from the device. - */ - void deviceFound(DeviceScanInfo scanInfo); + /** + * Is used by the driver to notify the Data Manager of new devices found during a scan. + * + * @param scanInfo the information obtained from the device. + */ + void deviceFound(DeviceScanInfo scanInfo); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverService.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverService.java index 13596573..c70eceab 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverService.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/DriverService.java @@ -27,14 +27,13 @@ import org.openmuc.framework.config.ScanInterruptedException; /** - * * The DriverService is the interface that all OpenMUC communication drivers have to implement and register * as a service in the OSGi environment. The OpenMUC Core Data Manager tracks this service and will therefore be * automatically notified of any new drivers in the framework. If sampling, listening or logging has been configured for * this driver, then the data manager will start right away with the appropriate actions. - * + *

    * A driver often implements a communication protocol but could also get its data from any other source (e.g. a file). - * + *

    * Some guidelines should be followed when implementing a driver for OpenMUC: *

      *
    • Logging may only be done with level debug or trace. Even these debug messages should be @@ -46,75 +45,63 @@ * log file and slow down performance if the function is called many times. Instead the appropriate Flag should be * returned for the affected channels.
    • *
    - * */ public interface DriverService { - /** - * Returns the driver information. Contains the driver's ID, a description of the driver and the syntax of various - * configuration options. - * - * @return the driver information - */ - public DriverInfo getInfo(); + /** + * Returns the driver information. Contains the driver's ID, a description of the driver and the syntax of various + * configuration options. + * + * @return the driver information + */ + public DriverInfo getInfo(); - /** - * Scans for available devices. Once a device is found it is reported as soon as possible to the DeviceScanListener - * through the deviceFound() function. Optionally this method may occasionally call the - * updateScanProgress function of DeviceScanListener. The updateScanProgress function should pass the progress in - * percent. The progress should never be explicitly set to 100%. The caller of this function will know that the - * progress is at 100% once the function has returned. - * - * @param settings - * scanning settings (e.g. location where to scan, baud rate etc.). The syntax is driver specific. - * @param listener - * the listener that is notified of devices found and progress updates. - * @throws UnsupportedOperationException - * if the method is not implemented by the driver - * @throws ArgumentSyntaxException - * if an the settings string cannot be understood by the driver - * @throws ScanException - * if an error occurs while scanning - * @throws ScanInterruptedException - * if the scan was interrupted through a call of interruptDeviceScan() before it was done. - */ - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException; + /** + * Scans for available devices. Once a device is found it is reported as soon as possible to the DeviceScanListener + * through the deviceFound() function. Optionally this method may occasionally call the + * updateScanProgress function of DeviceScanListener. The updateScanProgress function should pass the progress in + * percent. The progress should never be explicitly set to 100%. The caller of this function will know that the + * progress is at 100% once the function has returned. + * + * @param settings scanning settings (e.g. location where to scan, baud rate etc.). The syntax is driver specific. + * @param listener the listener that is notified of devices found and progress updates. + * @throws UnsupportedOperationException if the method is not implemented by the driver + * @throws ArgumentSyntaxException if an the settings string cannot be understood by the driver + * @throws ScanException if an error occurs while scanning + * @throws ScanInterruptedException if the scan was interrupted through a call of interruptDeviceScan() before it + * was done. + */ + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException; - /** - * A call of this function signals the driver to stop the device scan as soon as possible. The function should - * return immediately instead of waiting until the device scan has effectively been interrupted. The function - * scanForDevices() is to throw a ScanInterruptedException once the scan was really stopped. Note that there is no - * guarantee that scanForDevices will throw the ScanInterruptedException as a result of this function call because - * it could stop earlier for some other reason (e.g. successful finish, Exception etc.) instead. - * - * @throws UnsupportedOperationException - * if the method is not implemented by the driver - */ - public void interruptDeviceScan() throws UnsupportedOperationException; + /** + * A call of this function signals the driver to stop the device scan as soon as possible. The function should + * return immediately instead of waiting until the device scan has effectively been interrupted. The function + * scanForDevices() is to throw a ScanInterruptedException once the scan was really stopped. Note that there is no + * guarantee that scanForDevices will throw the ScanInterruptedException as a result of this function call because + * it could stop earlier for some other reason (e.g. successful finish, Exception etc.) instead. + * + * @throws UnsupportedOperationException if the method is not implemented by the driver + */ + public void interruptDeviceScan() throws UnsupportedOperationException; - /** - * Attempts to connect to the given communication device using the given settings. The resulting connection shall be - * returned as an object that implements the {@link Connection} interface. The framework will then call read/write - * etc functions on the returned connection object. If the syntax of the given deviceAddresse, or settings String is - * incorrect it will throw an ArgumentSyntaxException. If the connection attempt fails it throws a - * ConnectionException. - * - * Some communication protocols are not connection oriented. That means no connection has to be build up in order to - * read or write data. In this case the connect function may optionally test if the device is reachable. - * - * @param deviceAddress - * the configured device address. - * @param settings - * the settings that should be used for the communication with this device. - * @return the connection object that will be used for subsequent read/listen/write/scanForChannels/disconnect - * function calls. - * @throws ArgumentSyntaxException - * if the syntax of the deviceAddress or settings string is incorrect. - * @throws ConnectionException - * if the connection attempt fails. - */ - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException; + /** + * Attempts to connect to the given communication device using the given settings. The resulting connection shall be + * returned as an object that implements the {@link Connection} interface. The framework will then call read/write + * etc functions on the returned connection object. If the syntax of the given deviceAddresse, or settings String is + * incorrect it will throw an ArgumentSyntaxException. If the connection attempt fails it throws a + * ConnectionException. + *

    + * Some communication protocols are not connection oriented. That means no connection has to be build up in order to + * read or write data. In this case the connect function may optionally test if the device is reachable. + * + * @param deviceAddress the configured device address. + * @param settings the settings that should be used for the communication with this device. + * @return the connection object that will be used for subsequent read/listen/write/scanForChannels/disconnect + * function calls. + * @throws ArgumentSyntaxException if the syntax of the deviceAddress or settings string is incorrect. + * @throws ConnectionException if the connection attempt fails. + */ + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException; } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/RecordsReceivedListener.java b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/RecordsReceivedListener.java index d533fdf8..aff022d4 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/RecordsReceivedListener.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/driver/spi/RecordsReceivedListener.java @@ -25,8 +25,8 @@ public interface RecordsReceivedListener { - public void newRecords(List recordContainers); + public void newRecords(List recordContainers); - public void connectionInterrupted(String driverId, Connection connection); + public void connectionInterrupted(String driverId, Connection connection); } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerMappingContainer.java b/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerMappingContainer.java index 3d3df001..465dc173 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerMappingContainer.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerMappingContainer.java @@ -25,34 +25,33 @@ /** * Class that contains the mapping between a server-address/configuration and channel. - * - * @author sfey * + * @author sfey */ public class ServerMappingContainer { - private final Channel channel; - private final ServerMapping serverMapping; + private final Channel channel; + private final ServerMapping serverMapping; - public ServerMappingContainer(Channel channel, ServerMapping serverMapping) { - this.channel = channel; - this.serverMapping = serverMapping; - } + public ServerMappingContainer(Channel channel, ServerMapping serverMapping) { + this.channel = channel; + this.serverMapping = serverMapping; + } - /** - * The serverMapping that the channel should be mapped to. - * - * @return the serverAddress - */ - public ServerMapping getServerMapping() { - return this.serverMapping; - } + /** + * The serverMapping that the channel should be mapped to. + * + * @return the serverAddress + */ + public ServerMapping getServerMapping() { + return this.serverMapping; + } - /** - * The mapped Channel - * - * @return the channel - */ - public Channel getChannel() { - return this.channel; - } + /** + * The mapped Channel + * + * @return the channel + */ + public Channel getChannel() { + return this.channel; + } } diff --git a/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerService.java b/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerService.java index 51374620..e2428a9b 100644 --- a/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerService.java +++ b/projects/core/spi/src/main/java/org/openmuc/framework/server/spi/ServerService.java @@ -24,33 +24,30 @@ /** * This interface is to be implemented by bundles that provide server functionality. - * - * @author sfey * + * @author sfey */ public interface ServerService { - /** - * returns the unique Identifier of a server - * - * @return the unique Identifier - */ - public String getId(); + /** + * returns the unique Identifier of a server + * + * @return the unique Identifier + */ + public String getId(); - /** - * This method is called when configuration is updated. - * - * @param mappings - * the channels configured be mapped to the server - */ - public void updatedConfiguration(List mappings); + /** + * This method is called when configuration is updated. + * + * @param mappings the channels configured be mapped to the server + */ + public void updatedConfiguration(List mappings); - /** - * This method is called after registering as a server. It provides access to the channels that are configured to be - * mapped to a server - * - * @param mappings - * the channels configured be mapped to the server - */ - public void serverMappings(List mappings); + /** + * This method is called after registering as a server. It provides access to the channels that are configured to be + * mapped to a server + * + * @param mappings the channels configured be mapped to the server + */ + public void serverMappings(List mappings); } diff --git a/projects/datalogger/ascii/build.gradle b/projects/datalogger/ascii/build.gradle index f9af6e81..e13e471b 100644 --- a/projects/datalogger/ascii/build.gradle +++ b/projects/datalogger/ascii/build.gradle @@ -1,13 +1,12 @@ - dependencies { - compile project(':openmuc-core-spi') - compile project(':openmuc-core-datamanager') + compile project(':openmuc-core-spi') + compile project(':openmuc-core-datamanager') } jar { - manifest { - name = "OpenMUC Data Logger - ASCII" - instruction 'Service-Component', 'OSGI-INF/components.xml' - instruction 'Export-Package', '' - } + manifest { + name = "OpenMUC Data Logger - ASCII" + instruction 'Service-Component', 'OSGI-INF/components.xml' + instruction 'Export-Package', '' + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/AsciiLogger.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/AsciiLogger.java index 6a37abf2..1b6988ef 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/AsciiLogger.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/AsciiLogger.java @@ -20,21 +20,6 @@ */ package org.openmuc.framework.datalogger.ascii; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - import org.openmuc.framework.data.Record; import org.openmuc.framework.datalogger.ascii.utils.Const; import org.openmuc.framework.datalogger.ascii.utils.LoggerUtils; @@ -45,215 +30,214 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; + public class AsciiLogger implements DataLoggerService { - private final static Logger logger = LoggerFactory.getLogger(AsciiLogger.class); + private final static Logger logger = LoggerFactory.getLogger(AsciiLogger.class); + + private final String loggerDirectory; + private final HashMap logChannelList = new HashMap(); + private boolean isFillUpFiles = false; + + protected void activate(ComponentContext context) { - private final String loggerDirectory; - private final HashMap logChannelList = new HashMap(); - private boolean isFillUpFiles = false; + logger.info("Activating Ascii Logger"); + setSystemProperties(); + } - protected void activate(ComponentContext context) { + protected void deactivate(ComponentContext context) { - logger.info("Activating Ascii Logger"); - setSystemProperties(); - } - - protected void deactivate(ComponentContext context) { - - logger.info("Deactivating Ascii Logger"); - } - - /** - * - */ - public AsciiLogger() { - - loggerDirectory = Const.DEFAULT_DIR; - createDirectory(); - } - - public AsciiLogger(String loggerDirectory) { - - this.loggerDirectory = loggerDirectory; - createDirectory(); - } - - private void createDirectory() { - - logger.trace("using directory: " + loggerDirectory); - File asciidata = new File(loggerDirectory); - if (!asciidata.exists()) { - if (!asciidata.mkdir()) { - logger.error("Could not create logger directory: " + asciidata.getAbsolutePath()); - // TODO: weitere Behandlung, - } - } - } - - @Override - public String getId() { - return "asciilogger"; - } - - public boolean text(String test) { - return true; - } - - /** - * Will called if OpenMUC starts the logger - */ - @Override - public void setChannelsToLog(List channels) { - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - logChannelList.clear(); - - logger.trace("channels to log:"); - for (LogChannel channel : channels) { - - if (logger.isTraceEnabled()) { - logger.trace("channel.getId() " + channel.getId()); - logger.trace("channel.getLoggingInterval() " + channel.getLoggingInterval()); - } - logChannelList.put(channel.getId(), channel); - } - - if (isFillUpFiles) { - Map areHeaderIdentical = isHeaderIdentical(channels, calendar); - - for (Entry entry : areHeaderIdentical.entrySet()) { - String key = entry.getKey(); - - if (!entry.getValue()) { - // rename files in old files, because of configuration is changed - LoggerUtils.renameToOldFile(loggerDirectory, key, calendar); - } - else { - // Fill file up with error flag 32 (DATA_LOGGING_NOT_ACTIVE) - LoggerUtils.fillUpFileWithErrorCode(loggerDirectory, key, calendar); - } - } - } - else { - LoggerUtils.renameOldFiles(loggerDirectory, calendar); - } - - } - - @Override - public synchronized void log(List containers, long timestamp) { - - HashMap, LogIntervalContainerGroup> logIntervalGroups = new HashMap, LogIntervalContainerGroup>(); - - // add each container to a group with the same logging interval - for (LogRecordContainer container : containers) { - - int logInterval = -1; - int logTimeOffset = 0; - List logTimeArray = Arrays.asList(logInterval, logTimeOffset); - - if (logChannelList.containsKey(container.getChannelId())) { - logInterval = logChannelList.get(container.getChannelId()).getLoggingInterval(); - logTimeOffset = logChannelList.get(container.getChannelId()).getLoggingTimeOffset(); - logTimeArray = Arrays.asList(logInterval, logTimeOffset); - } - else { - // TODO there might be a change in the channel config file - } - - if (logIntervalGroups.containsKey(logTimeArray)) { - // add the container to an existing group - LogIntervalContainerGroup group = logIntervalGroups.get(logTimeArray); - group.add(container); - } - else { - // create a new group and add the container - LogIntervalContainerGroup group = new LogIntervalContainerGroup(); - group.add(container); - logIntervalGroups.put(logTimeArray, group); - } - - } - - // alle gruppen loggen - Iterator, LogIntervalContainerGroup>> it = logIntervalGroups.entrySet().iterator(); - List logTimeArray; - - while (it.hasNext()) { - - logTimeArray = it.next().getKey(); - LogIntervalContainerGroup group = logIntervalGroups.get(logTimeArray); - LogFileWriter fileOutHandler = new LogFileWriter(); - fileOutHandler.log(group, logTimeArray.get(0), logTimeArray.get(1), new Date(timestamp), logChannelList); - } - } - - @Override - public List getRecords(String channelId, long startTime, long endTime) throws IOException { - - LogChannel logChannel = logChannelList.get(channelId); - LogFileReader reader = null; - - if (logChannel != null) { - reader = new LogFileReader(loggerDirectory, logChannel); - return reader.getValues(startTime, endTime); - }// TODO: hier einfügen das nach Loggdateien gesucht werden sollen die vorhanden sind aber nicht geloggt werden, - // z.B für server only ohne Logging. Das suchen sollte nur beim ersten mal passieren (start). - else { - throw new IOException("ChannelID (" + channelId + ") not available. It's not a logging Channel."); - } - } - - private void setSystemProperties() { - - String fillUpProperty = System.getProperty("org.openmuc.framework.datalogger.ascii.fillUpFiles"); - - if (fillUpProperty != null) { - isFillUpFiles = Boolean.parseBoolean(fillUpProperty); - } - } - - private Map isHeaderIdentical(List channels, Calendar calendar) { - - Map areHeaderIdentical = new TreeMap(); - Map> logChannelMap = new TreeMap>(); - LogFileHeader logFileHeader = new LogFileHeader(); - String key = ""; - - for (LogChannel logChannel : channels) { - - if (logChannel.getLoggingTimeOffset() != 0) { - key = logChannel.getLoggingInterval() + "_" + logChannel.getLoggingTimeOffset(); - } - else { - key = logChannel.getLoggingInterval().toString(); - } - - if (!logChannelMap.containsKey(key)) { - List logChannelList = new ArrayList(); - logChannelList.add(logChannel); - logChannelMap.put(key, logChannelList); - } - else { - logChannelMap.get(key).add(logChannel); - } - } - - List logChannels; - - for (Entry> entry : logChannelMap.entrySet()) { - - key = entry.getKey(); - logChannels = entry.getValue(); - String fileName = LoggerUtils.buildFilename(key, calendar); - - String headerGenerated = logFileHeader.getIESDataFormatHeaderString(fileName, logChannels); - String oldHeader = LoggerUtils.getHeaderFromFile(loggerDirectory + fileName, key); - boolean isToFillUp = headerGenerated.equals(oldHeader); - areHeaderIdentical.put(key, isToFillUp); - } - return areHeaderIdentical; - } + logger.info("Deactivating Ascii Logger"); + } + + /** + * + */ + public AsciiLogger() { + + loggerDirectory = Const.DEFAULT_DIR; + createDirectory(); + } + + public AsciiLogger(String loggerDirectory) { + + this.loggerDirectory = loggerDirectory; + createDirectory(); + } + + private void createDirectory() { + + logger.trace("using directory: " + loggerDirectory); + File asciidata = new File(loggerDirectory); + if (!asciidata.exists()) { + if (!asciidata.mkdir()) { + logger.error("Could not create logger directory: " + asciidata.getAbsolutePath()); + // TODO: weitere Behandlung, + } + } + } + + @Override + public String getId() { + return "asciilogger"; + } + + public boolean text(String test) { + return true; + } + + /** + * Will called if OpenMUC starts the logger + */ + @Override + public void setChannelsToLog(List channels) { + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + logChannelList.clear(); + + logger.trace("channels to log:"); + for (LogChannel channel : channels) { + + if (logger.isTraceEnabled()) { + logger.trace("channel.getId() " + channel.getId()); + logger.trace("channel.getLoggingInterval() " + channel.getLoggingInterval()); + } + logChannelList.put(channel.getId(), channel); + } + + if (isFillUpFiles) { + Map areHeaderIdentical = isHeaderIdentical(channels, calendar); + + for (Entry entry : areHeaderIdentical.entrySet()) { + String key = entry.getKey(); + + if (!entry.getValue()) { + // rename files in old files, because of configuration is changed + LoggerUtils.renameToOldFile(loggerDirectory, key, calendar); + } else { + // Fill file up with error flag 32 (DATA_LOGGING_NOT_ACTIVE) + LoggerUtils.fillUpFileWithErrorCode(loggerDirectory, key, calendar); + } + } + } else { + LoggerUtils.renameOldFiles(loggerDirectory, calendar); + } + + } + + @Override + public synchronized void log(List containers, long timestamp) { + + HashMap, LogIntervalContainerGroup> logIntervalGroups = new HashMap, LogIntervalContainerGroup>(); + + // add each container to a group with the same logging interval + for (LogRecordContainer container : containers) { + + int logInterval = -1; + int logTimeOffset = 0; + List logTimeArray = Arrays.asList(logInterval, logTimeOffset); + + if (logChannelList.containsKey(container.getChannelId())) { + logInterval = logChannelList.get(container.getChannelId()).getLoggingInterval(); + logTimeOffset = logChannelList.get(container.getChannelId()).getLoggingTimeOffset(); + logTimeArray = Arrays.asList(logInterval, logTimeOffset); + } else { + // TODO there might be a change in the channel config file + } + + if (logIntervalGroups.containsKey(logTimeArray)) { + // add the container to an existing group + LogIntervalContainerGroup group = logIntervalGroups.get(logTimeArray); + group.add(container); + } else { + // create a new group and add the container + LogIntervalContainerGroup group = new LogIntervalContainerGroup(); + group.add(container); + logIntervalGroups.put(logTimeArray, group); + } + + } + + // alle gruppen loggen + Iterator, LogIntervalContainerGroup>> it = logIntervalGroups.entrySet().iterator(); + List logTimeArray; + + while (it.hasNext()) { + + logTimeArray = it.next().getKey(); + LogIntervalContainerGroup group = logIntervalGroups.get(logTimeArray); + LogFileWriter fileOutHandler = new LogFileWriter(); + fileOutHandler.log(group, logTimeArray.get(0), logTimeArray.get(1), new Date(timestamp), logChannelList); + } + } + + @Override + public List getRecords(String channelId, long startTime, long endTime) throws IOException { + + LogChannel logChannel = logChannelList.get(channelId); + LogFileReader reader = null; + + if (logChannel != null) { + reader = new LogFileReader(loggerDirectory, logChannel); + return reader.getValues(startTime, endTime); + }// TODO: hier einfügen das nach Loggdateien gesucht werden sollen die vorhanden sind aber nicht geloggt werden, + // z.B für server only ohne Logging. Das suchen sollte nur beim ersten mal passieren (start). + else { + throw new IOException("ChannelID (" + channelId + ") not available. It's not a logging Channel."); + } + } + + private void setSystemProperties() { + + String fillUpProperty = System.getProperty("org.openmuc.framework.datalogger.ascii.fillUpFiles"); + + if (fillUpProperty != null) { + isFillUpFiles = Boolean.parseBoolean(fillUpProperty); + } + } + + private Map isHeaderIdentical(List channels, Calendar calendar) { + + Map areHeaderIdentical = new TreeMap(); + Map> logChannelMap = new TreeMap>(); + LogFileHeader logFileHeader = new LogFileHeader(); + String key = ""; + + for (LogChannel logChannel : channels) { + + if (logChannel.getLoggingTimeOffset() != 0) { + key = logChannel.getLoggingInterval() + "_" + logChannel.getLoggingTimeOffset(); + } else { + key = logChannel.getLoggingInterval().toString(); + } + + if (!logChannelMap.containsKey(key)) { + List logChannelList = new ArrayList(); + logChannelList.add(logChannel); + logChannelMap.put(key, logChannelList); + } else { + logChannelMap.get(key).add(logChannel); + } + } + + List logChannels; + + for (Entry> entry : logChannelMap.entrySet()) { + + key = entry.getKey(); + logChannels = entry.getValue(); + String fileName = LoggerUtils.buildFilename(key, calendar); + + String headerGenerated = logFileHeader.getIESDataFormatHeaderString(fileName, logChannels); + String oldHeader = LoggerUtils.getHeaderFromFile(loggerDirectory + fileName, key); + boolean isToFillUp = headerGenerated.equals(oldHeader); + areHeaderIdentical.put(key, isToFillUp); + } + return areHeaderIdentical; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileHeader.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileHeader.java index 63f36b3b..1926dc2c 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileHeader.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileHeader.java @@ -20,245 +20,226 @@ */ package org.openmuc.framework.datalogger.ascii; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - import org.openmuc.framework.data.ValueType; import org.openmuc.framework.datalogger.ascii.utils.Const; import org.openmuc.framework.datalogger.spi.LogChannel; import org.openmuc.framework.datalogger.spi.LogRecordContainer; +import java.util.*; + public class LogFileHeader { - public LogFileHeader() { - - } - - /** - * Generate the standard IES Data Format Header and write it into the output stream 'out'. - * - * @param group - * @param filename - * @param loggingInterval - * @param logChannelList - * @return - */ - public String getIESDataFormatHeaderString(LogIntervalContainerGroup group, String filename, int loggingInterval, - HashMap logChannelList) { - - StringBuilder sb = new StringBuilder(); - setHeaderTop(sb, loggingInterval, filename); - - // write channel specific header informations - int colNumber = 4; - for (LogRecordContainer container : group.getList()) { - - LogChannel logChannel = logChannelList.get(container.getChannelId()); - appendChannelSpecificComment(sb, logChannel, colNumber); - ++colNumber; - } - List containers = group.getList(); - appendColumnHeaderTimestamp(sb); - - Iterator iterator = containers.iterator(); - - while (iterator.hasNext()) { - sb.append(iterator.next().getChannelId()); - if (iterator.hasNext()) { - sb.append(Const.SEPARATOR); - } - } - - sb.append(Const.LINESEPARATOR); - return sb.toString(); - } - - /** - * Generate the standard IES Data Format Header and write it into the output stream 'out'. - * - * @param filename - * @param logChannelList - * @return - */ - public String getIESDataFormatHeaderString(String filename, List logChannelList) { - - StringBuilder sb0 = new StringBuilder(); - StringBuilder sb1 = new StringBuilder(); - setHeaderTop(sb0, logChannelList.get(0).getLoggingInterval(), filename); - - // write channel specific header informations - int colNumber = 4; - Iterator iterator = logChannelList.listIterator(); - while (iterator.hasNext()) { - - LogChannel logChannel = iterator.next(); - appendChannelSpecificComment(sb0, logChannel, colNumber); - - sb1.append(logChannel.getId()); - if (iterator.hasNext()) { - sb1.append(Const.SEPARATOR); - } - ++colNumber; - } - appendColumnHeaderTimestamp(sb0); - sb0.append(sb1); - sb0.append(Const.LINESEPARATOR); - return sb0.toString(); - } - - /** - * Appends channel specific comments to a StringBuilder - * - * @param sb - * @param logChannel - * @param colNumber - */ - private void appendChannelSpecificComment(StringBuilder sb, LogChannel logChannel, int colNumber) { - - String unit = logChannel.getUnit(); - if (unit.equals("")) { - unit = "0"; - } - ValueType vType = logChannel.getValueType(); - String valueType = vType.toString(); - int valueTypeLength = 0; - if (vType.equals(ValueType.BYTE_ARRAY) || vType.equals(ValueType.STRING)) { - valueTypeLength = logChannel.getValueTypeLength(); - } - - String description = logChannel.getDescription(); - if (description.equals("")) { - description = "-"; - } - - createRow(sb, String.format("%03d", colNumber), logChannel.getId(), "FALSE", "TRUE", unit, "other", valueType, - valueTypeLength, description); - } - - /** - * Append column headers, the timestamps, in a StringBuilder - * - * @param sb - * @param group - */ - private void appendColumnHeaderTimestamp(StringBuilder sb) { - - // write column headers - sb.append("YYYYMMDD"); - sb.append(Const.SEPARATOR); - sb.append("hhmmss"); - sb.append(Const.SEPARATOR); - sb.append("unixtimestamp"); - sb.append(Const.SEPARATOR); - } - - /** - * Sets the top of the header. - * - * @param sb - * @param loggingInterval - * @param filename - */ - private void setHeaderTop(StringBuilder sb, int loggingInterval, String filename) { - - String timestep_sec = String.valueOf(loggingInterval / (double) 1000); - String seperator = Const.SEPARATOR; - - // write general header informations - appendStrings(sb, "#ies_format_version: ", String.valueOf(Const.ISEFORMATVERSION), Const.LINESEPARATOR_STRING); - appendStrings(sb, "#file: ", filename, Const.LINESEPARATOR_STRING); - appendStrings(sb, "#file_info: ", Const.FILEINFO, Const.LINESEPARATOR_STRING); - appendStrings(sb, "#timezone: ", getDiffLocalUTC(), Const.LINESEPARATOR_STRING); - appendStrings(sb, "#timestep_sec: ", timestep_sec, Const.LINESEPARATOR_STRING); - appendStrings(sb, "#", "col_no", seperator, "col_name", seperator, "confidential", seperator, "measured", - seperator, "unit", seperator, "category", seperator, Const.COMMENT_NAME, Const.LINESEPARATOR_STRING); - createRow(sb, "001", "YYYYMMDD", "FALSE", "FALSE", "0", "time", "INTEGER", 8, "Date [human readable]"); - createRow(sb, "002", "hhmmss", "FALSE", "FALSE", "0", "time", "SHORT", 6, "Time [human readable]"); - createRow(sb, "003", "unixtimestamp", "FALSE", "FALSE", "s", "time", "DOUBLE", 14, - "lapsed seconds from 01-01-1970"); - } - - /** - * Construct a header row with predefined separators and comment signs. - * - * @param col_no - * column number example: #001 - * @param col_name - * column name example: YYYYMMDD - * @param confidential - * false or true - * @param measured - * false or true - * @param unit - * example: kWh - * @param category - * example: time - * @param valueType - * example: DOUBLE - * @param valueTypeLength - * example: 8 - * @param comment - * a comment - */ - private void createRow(StringBuilder sb, String col_no, String col_name, String confidential, String measured, - String unit, String category, String valueType, int valueTypeLength, String comment) { - - String seperator = Const.SEPARATOR; - String com_sign = Const.COMMENT_SIGN; - String vtEndSign = Const.VALUETYPE_ENDSIGN; - String vtSizeSep = Const.VALUETYPE_SIZE_SEPARATOR; - String valueTypeLengthString = ""; - if (valueTypeLength != 0) { - valueTypeLengthString += valueTypeLength; - } - appendStrings(sb, com_sign, col_no, seperator, col_name, seperator, confidential, seperator, measured, - seperator, unit, seperator, category, seperator, valueType, vtSizeSep, valueTypeLengthString, - vtEndSign, comment, Const.LINESEPARATOR_STRING); - } - - /** - * appendStrings appends a any String to a StringBuilder - * - * @param sb - * StringBuilder to append a String - * @param s - * the String to append - */ - private void appendStrings(StringBuilder sb, String... s) { - - for (String element : s) { - sb.append(element); - } - } - - /** - * Calculates the difference between the configured local time and the Coordinated Universal Time (UTC) without - * daylight saving time and returns it as a string. - * - * @return the difference between local time and UTC as string. - */ - private String getDiffLocalUTC() { - - String ret; - long time = 0; - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - - time = calendar.getTimeZone().getRawOffset(); - time /= 1000 * 60 * 60; - - if (time >= 0) { - ret = ("+ " + time); - } - else { - ret = ("- " + time); - } - - return ret; - } + public LogFileHeader() { + + } + + /** + * Generate the standard IES Data Format Header and write it into the output stream 'out'. + * + * @param group + * @param filename + * @param loggingInterval + * @param logChannelList + * @return + */ + public String getIESDataFormatHeaderString(LogIntervalContainerGroup group, String filename, int loggingInterval, HashMap logChannelList) { + + StringBuilder sb = new StringBuilder(); + setHeaderTop(sb, loggingInterval, filename); + + // write channel specific header informations + int colNumber = 4; + for (LogRecordContainer container : group.getList()) { + + LogChannel logChannel = logChannelList.get(container.getChannelId()); + appendChannelSpecificComment(sb, logChannel, colNumber); + ++colNumber; + } + List containers = group.getList(); + appendColumnHeaderTimestamp(sb); + + Iterator iterator = containers.iterator(); + + while (iterator.hasNext()) { + sb.append(iterator.next().getChannelId()); + if (iterator.hasNext()) { + sb.append(Const.SEPARATOR); + } + } + + sb.append(Const.LINESEPARATOR); + return sb.toString(); + } + + /** + * Generate the standard IES Data Format Header and write it into the output stream 'out'. + * + * @param filename + * @param logChannelList + * @return + */ + public String getIESDataFormatHeaderString(String filename, List logChannelList) { + + StringBuilder sb0 = new StringBuilder(); + StringBuilder sb1 = new StringBuilder(); + setHeaderTop(sb0, logChannelList.get(0).getLoggingInterval(), filename); + + // write channel specific header informations + int colNumber = 4; + Iterator iterator = logChannelList.listIterator(); + while (iterator.hasNext()) { + + LogChannel logChannel = iterator.next(); + appendChannelSpecificComment(sb0, logChannel, colNumber); + + sb1.append(logChannel.getId()); + if (iterator.hasNext()) { + sb1.append(Const.SEPARATOR); + } + ++colNumber; + } + appendColumnHeaderTimestamp(sb0); + sb0.append(sb1); + sb0.append(Const.LINESEPARATOR); + return sb0.toString(); + } + + /** + * Appends channel specific comments to a StringBuilder + * + * @param sb + * @param logChannel + * @param colNumber + */ + private void appendChannelSpecificComment(StringBuilder sb, LogChannel logChannel, int colNumber) { + + String unit = logChannel.getUnit(); + if (unit.equals("")) { + unit = "0"; + } + ValueType vType = logChannel.getValueType(); + String valueType = vType.toString(); + int valueTypeLength = 0; + if (vType.equals(ValueType.BYTE_ARRAY) || vType.equals(ValueType.STRING)) { + valueTypeLength = logChannel.getValueTypeLength(); + } + + String description = logChannel.getDescription(); + if (description.equals("")) { + description = "-"; + } + + createRow(sb, String.format("%03d", colNumber), logChannel.getId(), "FALSE", "TRUE", unit, "other", valueType, valueTypeLength, + description); + } + + /** + * Append column headers, the timestamps, in a StringBuilder + * + * @param sb + * @param group + */ + private void appendColumnHeaderTimestamp(StringBuilder sb) { + + // write column headers + sb.append("YYYYMMDD"); + sb.append(Const.SEPARATOR); + sb.append("hhmmss"); + sb.append(Const.SEPARATOR); + sb.append("unixtimestamp"); + sb.append(Const.SEPARATOR); + } + + /** + * Sets the top of the header. + * + * @param sb + * @param loggingInterval + * @param filename + */ + private void setHeaderTop(StringBuilder sb, int loggingInterval, String filename) { + + String timestep_sec = String.valueOf(loggingInterval / (double) 1000); + String seperator = Const.SEPARATOR; + + // write general header informations + appendStrings(sb, "#ies_format_version: ", String.valueOf(Const.ISEFORMATVERSION), Const.LINESEPARATOR_STRING); + appendStrings(sb, "#file: ", filename, Const.LINESEPARATOR_STRING); + appendStrings(sb, "#file_info: ", Const.FILEINFO, Const.LINESEPARATOR_STRING); + appendStrings(sb, "#timezone: ", getDiffLocalUTC(), Const.LINESEPARATOR_STRING); + appendStrings(sb, "#timestep_sec: ", timestep_sec, Const.LINESEPARATOR_STRING); + appendStrings(sb, "#", "col_no", seperator, "col_name", seperator, "confidential", seperator, "measured", seperator, "unit", + seperator, "category", seperator, Const.COMMENT_NAME, Const.LINESEPARATOR_STRING); + createRow(sb, "001", "YYYYMMDD", "FALSE", "FALSE", "0", "time", "INTEGER", 8, "Date [human readable]"); + createRow(sb, "002", "hhmmss", "FALSE", "FALSE", "0", "time", "SHORT", 6, "Time [human readable]"); + createRow(sb, "003", "unixtimestamp", "FALSE", "FALSE", "s", "time", "DOUBLE", 14, "lapsed seconds from 01-01-1970"); + } + + /** + * Construct a header row with predefined separators and comment signs. + * + * @param col_no column number example: #001 + * @param col_name column name example: YYYYMMDD + * @param confidential false or true + * @param measured false or true + * @param unit example: kWh + * @param category example: time + * @param valueType example: DOUBLE + * @param valueTypeLength example: 8 + * @param comment a comment + */ + private void createRow(StringBuilder sb, String col_no, String col_name, String confidential, String measured, String unit, String + category, String valueType, int valueTypeLength, String comment) { + + String seperator = Const.SEPARATOR; + String com_sign = Const.COMMENT_SIGN; + String vtEndSign = Const.VALUETYPE_ENDSIGN; + String vtSizeSep = Const.VALUETYPE_SIZE_SEPARATOR; + String valueTypeLengthString = ""; + if (valueTypeLength != 0) { + valueTypeLengthString += valueTypeLength; + } + appendStrings(sb, com_sign, col_no, seperator, col_name, seperator, confidential, seperator, measured, seperator, unit, seperator, + category, seperator, valueType, vtSizeSep, valueTypeLengthString, vtEndSign, comment, Const.LINESEPARATOR_STRING); + } + + /** + * appendStrings appends a any String to a StringBuilder + * + * @param sb StringBuilder to append a String + * @param s the String to append + */ + private void appendStrings(StringBuilder sb, String... s) { + + for (String element : s) { + sb.append(element); + } + } + + /** + * Calculates the difference between the configured local time and the Coordinated Universal Time (UTC) without + * daylight saving time and returns it as a string. + * + * @return the difference between local time and UTC as string. + */ + private String getDiffLocalUTC() { + + String ret; + long time = 0; + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + + time = calendar.getTimeZone().getRawOffset(); + time /= 1000 * 60 * 60; + + if (time >= 0) { + ret = ("+ " + time); + } else { + ret = ("- " + time); + } + + return ret; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileReader.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileReader.java index 881354b4..7e572eed 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileReader.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileReader.java @@ -20,6 +20,13 @@ */ package org.openmuc.framework.datalogger.ascii; +import org.openmuc.framework.data.*; +import org.openmuc.framework.datalogger.ascii.utils.Const; +import org.openmuc.framework.datalogger.ascii.utils.LoggerUtils; +import org.openmuc.framework.datalogger.spi.LogChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; @@ -27,372 +34,345 @@ import java.util.ArrayList; import java.util.List; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.datalogger.ascii.utils.Const; -import org.openmuc.framework.datalogger.ascii.utils.LoggerUtils; -import org.openmuc.framework.datalogger.spi.LogChannel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class LogFileReader { - private static final Logger logger = LoggerFactory.getLogger(LogFileReader.class); - - private final String channelId; - private final String path; - private final int loggingInterval; - private final int logTimeOffset; - private int unixTimestampColumn; - private long startTimestamp; - private long endTimestamp; - private long firstTimestampFromFile; - - /** - * Constructor - * - * @param path - * @param id - * @param loggingInterval - */ - public LogFileReader(String path, LogChannel logChannel) { - - this.path = path; - channelId = logChannel.getId(); - this.loggingInterval = logChannel.getLoggingInterval(); - this.logTimeOffset = logChannel.getLoggingTimeOffset(); - firstTimestampFromFile = -1; - } - - /** - * @return All records of the given time span - */ - public List getValues(long startTimestamp, long endTimestamp) { - - this.startTimestamp = startTimestamp; - this.endTimestamp = endTimestamp; - - List allRecords = new ArrayList(); - - List filenames = LoggerUtils.getFilenames(loggingInterval, logTimeOffset, this.startTimestamp, - this.endTimestamp); - - for (int i = 0; i < filenames.size(); i++) { - Boolean nextFile = false; - if (logger.isTraceEnabled()) { - logger.trace("using " + filenames.get(i)); - } - - String filepath; - if (path.endsWith(File.separator)) { - filepath = path + filenames.get(i); - } - else { - filepath = path + File.separatorChar + filenames.get(i); - } - - if (i > 0) { - nextFile = true; - } - List fileRecords = processFile(filepath, nextFile); - if (fileRecords != null) { - allRecords.addAll(fileRecords); - if (logger.isTraceEnabled()) { - logger.trace("read records: " + fileRecords.size()); - } - } - else { - // some error occurred while processing the file so no records will be added - } - - } - return allRecords; - } - - /** - * @param timestamp - * @return Record on success, otherwise null - */ - public Record getValue(long timestamp) { - - // Returns a record which lays within the interval [timestamp, timestamp + loggingInterval] - // The interval is necessary for a requested time stamp which lays between the time stamps of two logged values - // e.g.: t_request = 7, t1_logged = 5, t2_logged = 10, loggingInterval = 5 - // method will return the record of t2_logged because this lays within the interval [7,12] - // If the t_request matches exactly a logged time stamp, then the according record is returned. - - Record record = null; - List records = getValues(timestamp, timestamp);// + loggingInterval); - if (records.size() == 0) { - // no record found for requested timestamp - - // TODO statt null flag 3 setzen! - record = null; - } - else if (records.size() == 1) { - // t_request lays between two logged values - record = records.get(0); - } - else if (records.size() == 2) { - // t_request matches exactly a logged value - // so getVaules returns a record for t_request and one for t_request+loggingInterval - record = records.get(0); - } - - // nur wert zurückgeben wenn zeitstempel identisch ist - // sonst - - return record; - } - - /** - * Reads the file line by line - * - * @param br - * @return records on success, otherwise null - */ - private List processFile(String filepath, Boolean nextFile) { - - List records = new ArrayList(); - String line = null; - long currentPosition = 0; - long rowSize; - long firstTimestamp = 0; - String firstValueLine = null; - long currentTimestamp = 0; - - RandomAccessFile raf = LoggerUtils.getRandomAccessFile(new File(filepath), "r"); - if (raf == null) { - return null; - } - try { - int channelColumn = -1; - while (channelColumn <= 0) { - line = raf.readLine(); - channelColumn = LoggerUtils.getColumnNumberByName(line, channelId); - unixTimestampColumn = LoggerUtils.getColumnNumberByName(line, Const.TIMESTAMP_STRING); - } - - firstValueLine = raf.readLine(); - - rowSize = firstValueLine.length() + 1; // +1 because of "\n" - - // rewind the position to the start of the firstValue line - currentPosition = raf.getFilePointer() - rowSize; - - firstTimestamp = (long) (Double.valueOf((firstValueLine.split(Const.SEPARATOR))[unixTimestampColumn]) * 1000); - - if (nextFile || startTimestamp < firstTimestamp) { - startTimestamp = firstTimestamp; - } - - if (startTimestamp >= firstTimestamp) { - long filepos = getFilePosition(loggingInterval, startTimestamp, firstTimestamp, currentPosition, - rowSize); - raf.seek(filepos); - - currentTimestamp = startTimestamp; - - while ((line = raf.readLine()) != null && currentTimestamp <= endTimestamp) { - - processLine(line, channelColumn, records); - currentTimestamp += loggingInterval; - } - raf.close(); - } - else { - records = null; // because the column of the channel was not identified - } - } catch (IOException e) { - e.printStackTrace(); - records = null; - } - return records; - } - - /** - * Process the line: ignore comments, read records - * - * @param line - */ - private void processLine(String line, int channelColumn, List records) { - - if (!line.startsWith(Const.COMMENT_SIGN)) { - readRecordFromLine(line, channelColumn, records); - } - } - - /** - * - * @param line - * to read - * @param column - * of the channelId - * @return Record read from line - */ - private void readRecordFromLine(String line, int channelColumn, List records) { - - String columnValue[] = line.split(Const.SEPARATOR); - - try { - Double timestampS = Double.parseDouble(columnValue[unixTimestampColumn]); - - long timestampMS = ((Double) (timestampS * (1000))).longValue(); - - if (isTimestampPartOfRequestedInterval(timestampMS)) { - Record record = convertLogfileEntryToRecord(columnValue[channelColumn], timestampMS); - records.add(record); - } - else { - // for debugging - // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); - // logger.trace("timestampMS: " + sdf.format(timestampMS) + " " + timestampMS); - } - } catch (NumberFormatException e) { - logger.debug("It's not a timestamp."); - e.printStackTrace(); - } catch (ArrayIndexOutOfBoundsException e) { - e.printStackTrace(); - } - } - - /** - * Checks if the timestamp read from file is part of the requested logging interval - * - * @param lineTimestamp - * @return true if it is a part of the requested interval, if not false. - */ - private boolean isTimestampPartOfRequestedInterval(long lineTimestamp) { - boolean result = false; - - // TODO tidy up, move to better place, is asked each line! - if (firstTimestampFromFile == -1) { - firstTimestampFromFile = lineTimestamp; - } - - if (lineTimestamp >= startTimestamp && lineTimestamp <= endTimestamp) { - result = true; - } - return result; - } - - /** - * Get the position of the startTimestamp, without Header. - * - * @param loggingInterval - * @param startTimestamp - * @return the position of the start timestamp as long. - */ - private long getFilePosition(int loggingInterval, long startTimestamp, long firstTimestampOfFile, - long firstValuePos, long rowSize) { - - long timeOffsetMs = startTimestamp - firstTimestampOfFile; - long numberOfLinesToSkip = timeOffsetMs / loggingInterval; - - // if offset isn't a multiple of loggingInterval add an additional line - if (timeOffsetMs % loggingInterval != 0) { - ++numberOfLinesToSkip; - } - - long pos = numberOfLinesToSkip * rowSize + firstValuePos; - - // for debugging - // logger.trace("pos " + pos); - // logger.trace("startTimestamp " + startTimestamp); - // logger.trace("firstTimestamp " + firstTimestampOfFile); - // logger.trace("loggingInterval " + loggingInterval); - // logger.trace("rowSize " + rowSize); - // logger.trace("firstValuePos " + firstValuePos); - - return pos; - } - - // TODO support ints, booleans, ... - /** - * Converts an entry from the logfile into a record - * - * @param strValue - * @param timestamp - * @return the converted logfile entry. - */ - private Record convertLogfileEntryToRecord(String strValue, long timestamp) { - - Record record = null; - if (isNumber(strValue)) { - record = new Record(new DoubleValue(Double.parseDouble(strValue)), timestamp, Flag.VALID); - } - else { - // fehlerfall, wenn errors "errxx" geloggt wurden - // record = new Record(null, timestamp, Flag); - record = getRecordFromNonNumberValue(strValue, timestamp); - - } - return record; - } - - /** - * Returns the record from a non number value read from the logfile. This is the case if the value is an error like - * "e0" or a normal ByteArrayValue - * - * @param strValue - * @param timestamp - * @return the value in a record. - */ - private Record getRecordFromNonNumberValue(String strValue, long timestamp) { - - Record record = null; - - if (strValue.trim().startsWith(Const.ERROR)) { - int errorSize = Const.ERROR.length(); - String errorFlag = strValue.substring(errorSize, errorSize + 2); - if (isNumber(errorFlag)) { - record = new Record(null, timestamp, Flag.newFlag(Integer.parseInt(errorFlag.trim()))); - } - else { - record = new Record(null, timestamp, Flag.NO_VALUE_RECEIVED_YET); - } - } - else if (strValue.trim().startsWith(Const.HEXADECIMAL)) { - try { - record = new Record(new ByteArrayValue(strValue.trim().getBytes("US-ASCII")), timestamp, Flag.VALID); - } catch (UnsupportedEncodingException e) { - record = new Record(Flag.UNKNOWN_ERROR); - logger.error("Hexadecimal value is non US-ASCII decoded, value is: " + strValue.trim()); - } - } - else { - record = new Record(new StringValue(strValue.trim()), timestamp, Flag.VALID); - } - return record; - } - - /** - * Checks if the string value is a number - * - * @param strValue - * @return True on success, otherwise false - */ - private boolean isNumber(String strValue) { - - boolean isDecimalSeparatorFound = false; - - if (!Character.isDigit(strValue.charAt(0)) && strValue.charAt(0) != Const.MINUS_SIGN - && strValue.charAt(0) != Const.PLUS_SIGN) { - return false; - } - - for (char charactor : strValue.substring(1).toCharArray()) { - if (!Character.isDigit(charactor)) { - if (charactor == Const.DECIMAL_SEPARATOR && !isDecimalSeparatorFound) { - isDecimalSeparatorFound = true; - continue; - } - return false; - } - } - return true; - } + private static final Logger logger = LoggerFactory.getLogger(LogFileReader.class); + + private final String channelId; + private final String path; + private final int loggingInterval; + private final int logTimeOffset; + private int unixTimestampColumn; + private long startTimestamp; + private long endTimestamp; + private long firstTimestampFromFile; + + /** + * Constructor + * + * @param path + * @param id + * @param loggingInterval + */ + public LogFileReader(String path, LogChannel logChannel) { + + this.path = path; + channelId = logChannel.getId(); + this.loggingInterval = logChannel.getLoggingInterval(); + this.logTimeOffset = logChannel.getLoggingTimeOffset(); + firstTimestampFromFile = -1; + } + + /** + * @return All records of the given time span + */ + public List getValues(long startTimestamp, long endTimestamp) { + + this.startTimestamp = startTimestamp; + this.endTimestamp = endTimestamp; + + List allRecords = new ArrayList(); + + List filenames = LoggerUtils.getFilenames(loggingInterval, logTimeOffset, this.startTimestamp, this.endTimestamp); + + for (int i = 0; i < filenames.size(); i++) { + Boolean nextFile = false; + if (logger.isTraceEnabled()) { + logger.trace("using " + filenames.get(i)); + } + + String filepath; + if (path.endsWith(File.separator)) { + filepath = path + filenames.get(i); + } else { + filepath = path + File.separatorChar + filenames.get(i); + } + + if (i > 0) { + nextFile = true; + } + List fileRecords = processFile(filepath, nextFile); + if (fileRecords != null) { + allRecords.addAll(fileRecords); + if (logger.isTraceEnabled()) { + logger.trace("read records: " + fileRecords.size()); + } + } else { + // some error occurred while processing the file so no records will be added + } + + } + return allRecords; + } + + /** + * @param timestamp + * @return Record on success, otherwise null + */ + public Record getValue(long timestamp) { + + // Returns a record which lays within the interval [timestamp, timestamp + loggingInterval] + // The interval is necessary for a requested time stamp which lays between the time stamps of two logged values + // e.g.: t_request = 7, t1_logged = 5, t2_logged = 10, loggingInterval = 5 + // method will return the record of t2_logged because this lays within the interval [7,12] + // If the t_request matches exactly a logged time stamp, then the according record is returned. + + Record record = null; + List records = getValues(timestamp, timestamp);// + loggingInterval); + if (records.size() == 0) { + // no record found for requested timestamp + + // TODO statt null flag 3 setzen! + record = null; + } else if (records.size() == 1) { + // t_request lays between two logged values + record = records.get(0); + } else if (records.size() == 2) { + // t_request matches exactly a logged value + // so getVaules returns a record for t_request and one for t_request+loggingInterval + record = records.get(0); + } + + // nur wert zurückgeben wenn zeitstempel identisch ist + // sonst + + return record; + } + + /** + * Reads the file line by line + * + * @param br + * @return records on success, otherwise null + */ + private List processFile(String filepath, Boolean nextFile) { + + List records = new ArrayList(); + String line = null; + long currentPosition = 0; + long rowSize; + long firstTimestamp = 0; + String firstValueLine = null; + long currentTimestamp = 0; + + RandomAccessFile raf = LoggerUtils.getRandomAccessFile(new File(filepath), "r"); + if (raf == null) { + return null; + } + try { + int channelColumn = -1; + while (channelColumn <= 0) { + line = raf.readLine(); + channelColumn = LoggerUtils.getColumnNumberByName(line, channelId); + unixTimestampColumn = LoggerUtils.getColumnNumberByName(line, Const.TIMESTAMP_STRING); + } + + firstValueLine = raf.readLine(); + + rowSize = firstValueLine.length() + 1; // +1 because of "\n" + + // rewind the position to the start of the firstValue line + currentPosition = raf.getFilePointer() - rowSize; + + firstTimestamp = (long) (Double.valueOf((firstValueLine.split(Const.SEPARATOR))[unixTimestampColumn]) * 1000); + + if (nextFile || startTimestamp < firstTimestamp) { + startTimestamp = firstTimestamp; + } + + if (startTimestamp >= firstTimestamp) { + long filepos = getFilePosition(loggingInterval, startTimestamp, firstTimestamp, currentPosition, rowSize); + raf.seek(filepos); + + currentTimestamp = startTimestamp; + + while ((line = raf.readLine()) != null && currentTimestamp <= endTimestamp) { + + processLine(line, channelColumn, records); + currentTimestamp += loggingInterval; + } + raf.close(); + } else { + records = null; // because the column of the channel was not identified + } + } catch (IOException e) { + e.printStackTrace(); + records = null; + } + return records; + } + + /** + * Process the line: ignore comments, read records + * + * @param line + */ + private void processLine(String line, int channelColumn, List records) { + + if (!line.startsWith(Const.COMMENT_SIGN)) { + readRecordFromLine(line, channelColumn, records); + } + } + + /** + * @param line to read + * @param column of the channelId + * @return Record read from line + */ + private void readRecordFromLine(String line, int channelColumn, List records) { + + String columnValue[] = line.split(Const.SEPARATOR); + + try { + Double timestampS = Double.parseDouble(columnValue[unixTimestampColumn]); + + long timestampMS = ((Double) (timestampS * (1000))).longValue(); + + if (isTimestampPartOfRequestedInterval(timestampMS)) { + Record record = convertLogfileEntryToRecord(columnValue[channelColumn], timestampMS); + records.add(record); + } else { + // for debugging + // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); + // logger.trace("timestampMS: " + sdf.format(timestampMS) + " " + timestampMS); + } + } catch (NumberFormatException e) { + logger.debug("It's not a timestamp."); + e.printStackTrace(); + } catch (ArrayIndexOutOfBoundsException e) { + e.printStackTrace(); + } + } + + /** + * Checks if the timestamp read from file is part of the requested logging interval + * + * @param lineTimestamp + * @return true if it is a part of the requested interval, if not false. + */ + private boolean isTimestampPartOfRequestedInterval(long lineTimestamp) { + boolean result = false; + + // TODO tidy up, move to better place, is asked each line! + if (firstTimestampFromFile == -1) { + firstTimestampFromFile = lineTimestamp; + } + + if (lineTimestamp >= startTimestamp && lineTimestamp <= endTimestamp) { + result = true; + } + return result; + } + + /** + * Get the position of the startTimestamp, without Header. + * + * @param loggingInterval + * @param startTimestamp + * @return the position of the start timestamp as long. + */ + private long getFilePosition(int loggingInterval, long startTimestamp, long firstTimestampOfFile, long firstValuePos, long rowSize) { + + long timeOffsetMs = startTimestamp - firstTimestampOfFile; + long numberOfLinesToSkip = timeOffsetMs / loggingInterval; + + // if offset isn't a multiple of loggingInterval add an additional line + if (timeOffsetMs % loggingInterval != 0) { + ++numberOfLinesToSkip; + } + + long pos = numberOfLinesToSkip * rowSize + firstValuePos; + + // for debugging + // logger.trace("pos " + pos); + // logger.trace("startTimestamp " + startTimestamp); + // logger.trace("firstTimestamp " + firstTimestampOfFile); + // logger.trace("loggingInterval " + loggingInterval); + // logger.trace("rowSize " + rowSize); + // logger.trace("firstValuePos " + firstValuePos); + + return pos; + } + + // TODO support ints, booleans, ... + + /** + * Converts an entry from the logfile into a record + * + * @param strValue + * @param timestamp + * @return the converted logfile entry. + */ + private Record convertLogfileEntryToRecord(String strValue, long timestamp) { + + Record record = null; + if (isNumber(strValue)) { + record = new Record(new DoubleValue(Double.parseDouble(strValue)), timestamp, Flag.VALID); + } else { + // fehlerfall, wenn errors "errxx" geloggt wurden + // record = new Record(null, timestamp, Flag); + record = getRecordFromNonNumberValue(strValue, timestamp); + + } + return record; + } + + /** + * Returns the record from a non number value read from the logfile. This is the case if the value is an error like + * "e0" or a normal ByteArrayValue + * + * @param strValue + * @param timestamp + * @return the value in a record. + */ + private Record getRecordFromNonNumberValue(String strValue, long timestamp) { + + Record record = null; + + if (strValue.trim().startsWith(Const.ERROR)) { + int errorSize = Const.ERROR.length(); + String errorFlag = strValue.substring(errorSize, errorSize + 2); + if (isNumber(errorFlag)) { + record = new Record(null, timestamp, Flag.newFlag(Integer.parseInt(errorFlag.trim()))); + } else { + record = new Record(null, timestamp, Flag.NO_VALUE_RECEIVED_YET); + } + } else if (strValue.trim().startsWith(Const.HEXADECIMAL)) { + try { + record = new Record(new ByteArrayValue(strValue.trim().getBytes("US-ASCII")), timestamp, Flag.VALID); + } catch (UnsupportedEncodingException e) { + record = new Record(Flag.UNKNOWN_ERROR); + logger.error("Hexadecimal value is non US-ASCII decoded, value is: " + strValue.trim()); + } + } else { + record = new Record(new StringValue(strValue.trim()), timestamp, Flag.VALID); + } + return record; + } + + /** + * Checks if the string value is a number + * + * @param strValue + * @return True on success, otherwise false + */ + private boolean isNumber(String strValue) { + + boolean isDecimalSeparatorFound = false; + + if (!Character.isDigit(strValue.charAt(0)) && strValue.charAt(0) != Const.MINUS_SIGN && strValue.charAt(0) != Const.PLUS_SIGN) { + return false; + } + + for (char charactor : strValue.substring(1).toCharArray()) { + if (!Character.isDigit(charactor)) { + if (charactor == Const.DECIMAL_SEPARATOR && !isDecimalSeparatorFound) { + isDecimalSeparatorFound = true; + continue; + } + return false; + } + } + return true; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileWriter.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileWriter.java index d2d01251..8c3d1736 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileWriter.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogFileWriter.java @@ -20,18 +20,6 @@ */ package org.openmuc.framework.datalogger.ascii; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.datalogger.ascii.exceptions.WrongCharacterException; @@ -44,274 +32,262 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.util.*; + public class LogFileWriter { - private final String directoryPath; - private static final Logger logger = LoggerFactory.getLogger(LogFileWriter.class); - private final LogFileHeader header = new LogFileHeader(); - private File actualFile; - - public LogFileWriter() { - directoryPath = Const.DEFAULT_DIR; - } - - public LogFileWriter(String directoryPath) { - - this.directoryPath = directoryPath; - } - - /** - * Main logger writing controller. - * - * @param group - * @param loggingInterval - * @param date - * @param logChannelList - */ - public void log(LogIntervalContainerGroup group, int loggingInterval, int logTimeOffset, Date date, - HashMap logChannelList) { - - PrintStream out = getStream(group, loggingInterval, logTimeOffset, date, logChannelList); - - if (out == null) { - return; - } - - List logRecordContainer = group.getList(); - - // TODO match column with container id, so that they don't get mixed up - String logLine = setLoggingStringBuilder(logRecordContainer, logChannelList, date); - - out.print(logLine); // print because of println makes different newline char on different systems - out.flush(); - out.close(); - } - - private String setLoggingStringBuilder(List logRecordContainer, - HashMap logChannelList, Date date) { - - StringBuilder sb = new StringBuilder(); - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - calendar.setTime(date); - LoggerUtils.setLoggerTimestamps(sb, calendar); - - for (int i = 0; i < logRecordContainer.size(); i++) { - String value = ""; - int size = Const.VALUE_SIZE_MINIMAL; - boolean left = true; - - if (logRecordContainer.get(i).getRecord() != null) { - if (logRecordContainer.get(i).getRecord().getFlag() == Flag.VALID) { - if (logRecordContainer.get(i).getRecord().getValue() == null) { - // write error flag - value = LoggerUtils.buildError(Flag.CANNOT_WRITE_NULL_VALUE); - size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); - } - else { - ValueType valueType = logChannelList.get(logRecordContainer.get(i).getChannelId()) - .getValueType(); - // logger.debug("channel: " + containers.get(i).getChannelId()); - switch (valueType) { - case BOOLEAN: - value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asShort()); - break; - case LONG: - value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asLong()); - size = Const.VALUE_SIZE_LONG; - break; - case INTEGER: - value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asInt()); - size = Const.VALUE_SIZE_INTEGER; - break; - case SHORT: - value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asShort()); - size = Const.VALUE_SIZE_SHORT; - break; - case DOUBLE: - case FLOAT: - size = Const.VALUE_SIZE_DOUBLE; - try { - value = IESDataFormatUtils.convertDoubleToStringWithMaxLength(logRecordContainer.get(i) - .getRecord().getValue().asDouble(), size); - } catch (WrongScalingException e) { - value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); - logger.error(e.getMessage() + " ChannelId: " + logRecordContainer.get(i).getChannelId()); - } - break; - case BYTE_ARRAY: - left = false; - size = checkMinimalValueSize(logChannelList.get(logRecordContainer.get(i).getChannelId()) - .getValueTypeLength()); - byte[] byteArray = logRecordContainer.get(i).getRecord().getValue().asByteArray(); - if (byteArray.length > size) { - value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); - logger.error("The byte array is too big, length is " + byteArray.length - + " but max. length allowed is " + size + ", ChannelId: " - + logRecordContainer.get(i).getChannelId()); - } - else { - value = Const.HEXADECIMAL + LoggerUtils.byteArrayToHexString(byteArray); - } - break; - case STRING: - left = false; - size = checkMinimalValueSize(logChannelList.get(logRecordContainer.get(i).getChannelId()) - .getValueTypeLength()); - value = logRecordContainer.get(i).getRecord().getValue().toString(); - try { - checkStringValue(value); - } catch (WrongCharacterException e) { - value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); - logger.error(e.getMessage()); - } - if (value.length() > size) { - value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); - logger.error("The string is too big, length is " + value.length() - + " but max. length allowed is " + size + ", ChannelId: " - + logRecordContainer.get(i).getChannelId()); - } - break; - case BYTE: - value = String.format("0x%02x", logRecordContainer.get(i).getRecord().getValue().asByte()); - break; - default: - throw new RuntimeException("unsupported valueType"); - } - } - } - else { - // write errorflag - value = LoggerUtils.buildError(logRecordContainer.get(i).getRecord().getFlag()); - size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); - } - } - else { - // got no data - value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); - size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); - } - - if (left) { - value = LoggerUtils.addSpacesLeft(value, size); - } - else { - value = LoggerUtils.addSpacesRight(value, size); - } - sb.append(value); - - if (LoggerUtils.hasNext(logRecordContainer, i)) { - sb.append(Const.SEPARATOR); - } - } - sb.append(Const.LINESEPARATOR); // All systems with the same newline charter - return sb.toString(); - } - - /** - * Checkes a string if it is IESData conform, f.e. wrong characters. If not it will drop a error. - * - * @param value - * the string value which should be checked - */ - private void checkStringValue(String value) throws WrongCharacterException { - - if (value.contains(Const.SEPARATOR)) { - throw new WrongCharacterException("Wrong character: String contains Seperator character: " - + Const.SEPARATOR); - } - else if (value.startsWith(Const.ERROR)) { - throw new WrongCharacterException("Wrong character: String begins with: " + Const.ERROR); - } - else if (value.startsWith(Const.HEXADECIMAL)) { - throw new WrongCharacterException("Wrong character: String begins with: " + Const.HEXADECIMAL); - } - else if (!value.matches("^[\\x00-\\x7F]*")) { - throw new WrongCharacterException("Wrong character: Non ASCII character in String."); - } - } - - private int checkMinimalValueSize(int size) { - - if (size < Const.VALUE_SIZE_MINIMAL) { - size = Const.VALUE_SIZE_MINIMAL; - } - return size; - } - - /** - * Returns the PrintStream for logging. - * - * @param group - * @param loggingInterval - * @param date - * @param logChannelList - * @return the PrintStream for logging. - */ - private PrintStream getStream(LogIntervalContainerGroup group, int loggingInterval, int logTimeOffset, Date date, - HashMap logChannelList) { - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - calendar.setTime(date); - String filename = LoggerUtils.buildFilename(loggingInterval, logTimeOffset, calendar); - - File file = new File(directoryPath + filename); - actualFile = file; - PrintStream out = null; - - try { - if (file.exists()) { - out = new PrintStream(new FileOutputStream(file, true), false, Const.CHAR_SET); - } - else { - out = new PrintStream(new FileOutputStream(file, true), false, Const.CHAR_SET); - String headerString = header.getIESDataFormatHeaderString(group, file.getName(), loggingInterval, - logChannelList); - - out.print(headerString); - out.flush(); - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return out; - } - - /** - * Returns the size of a DataType / ValueType. - * - * @param logChannel - * @param iterator - * @return size of DataType / ValueType. - */ - private int getDataTypeSize(LogChannel logChannel, int iterator) { - - int size = Const.VALUE_SIZE_MINIMAL; - - if (logChannel != null) { - boolean isByteArray = logChannel.getValueType().equals(ValueType.BYTE_ARRAY); - boolean isString = logChannel.getValueType().equals(ValueType.STRING); - - if ((isByteArray || isString)) { - // get length from channel for ByteString - size = logChannel.getValueTypeLength(); - } - else if (!(isByteArray || isString)) { - // get length from channel for simple value types - size = LoggerUtils.getLengthOfValueType(logChannel.getValueType()); - } - } - else { - // get length from file - ValueType vt = LoggerUtils.identifyValueType(iterator + Const.NUM_OF_TIME_TYPES_IN_HEADER + 1, actualFile); - size = LoggerUtils.getLengthOfValueType(vt); - if ((vt.equals(ValueType.BYTE_ARRAY) || (vt.equals(ValueType.STRING))) && size <= Const.VALUE_SIZE_MINIMAL) { - size = LoggerUtils.getValueTypeLengthFromFile(iterator + Const.NUM_OF_TIME_TYPES_IN_HEADER + 1, - actualFile); - } - } - return size; - } + private final String directoryPath; + private static final Logger logger = LoggerFactory.getLogger(LogFileWriter.class); + private final LogFileHeader header = new LogFileHeader(); + private File actualFile; + + public LogFileWriter() { + directoryPath = Const.DEFAULT_DIR; + } + + public LogFileWriter(String directoryPath) { + + this.directoryPath = directoryPath; + } + + /** + * Main logger writing controller. + * + * @param group + * @param loggingInterval + * @param date + * @param logChannelList + */ + public void log(LogIntervalContainerGroup group, int loggingInterval, int logTimeOffset, Date date, HashMap + logChannelList) { + + PrintStream out = getStream(group, loggingInterval, logTimeOffset, date, logChannelList); + + if (out == null) { + return; + } + + List logRecordContainer = group.getList(); + + // TODO match column with container id, so that they don't get mixed up + String logLine = setLoggingStringBuilder(logRecordContainer, logChannelList, date); + + out.print(logLine); // print because of println makes different newline char on different systems + out.flush(); + out.close(); + } + + private String setLoggingStringBuilder(List logRecordContainer, HashMap logChannelList, Date + date) { + + StringBuilder sb = new StringBuilder(); + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + calendar.setTime(date); + LoggerUtils.setLoggerTimestamps(sb, calendar); + + for (int i = 0; i < logRecordContainer.size(); i++) { + String value = ""; + int size = Const.VALUE_SIZE_MINIMAL; + boolean left = true; + + if (logRecordContainer.get(i).getRecord() != null) { + if (logRecordContainer.get(i).getRecord().getFlag() == Flag.VALID) { + if (logRecordContainer.get(i).getRecord().getValue() == null) { + // write error flag + value = LoggerUtils.buildError(Flag.CANNOT_WRITE_NULL_VALUE); + size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); + } else { + ValueType valueType = logChannelList.get(logRecordContainer.get(i).getChannelId()).getValueType(); + // logger.debug("channel: " + containers.get(i).getChannelId()); + switch (valueType) { + case BOOLEAN: + value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asShort()); + break; + case LONG: + value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asLong()); + size = Const.VALUE_SIZE_LONG; + break; + case INTEGER: + value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asInt()); + size = Const.VALUE_SIZE_INTEGER; + break; + case SHORT: + value = String.valueOf(logRecordContainer.get(i).getRecord().getValue().asShort()); + size = Const.VALUE_SIZE_SHORT; + break; + case DOUBLE: + case FLOAT: + size = Const.VALUE_SIZE_DOUBLE; + try { + value = IESDataFormatUtils + .convertDoubleToStringWithMaxLength(logRecordContainer.get(i).getRecord().getValue().asDouble(), + size); + } catch (WrongScalingException e) { + value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); + logger.error(e.getMessage() + " ChannelId: " + logRecordContainer.get(i).getChannelId()); + } + break; + case BYTE_ARRAY: + left = false; + size = checkMinimalValueSize( + logChannelList.get(logRecordContainer.get(i).getChannelId()).getValueTypeLength()); + byte[] byteArray = logRecordContainer.get(i).getRecord().getValue().asByteArray(); + if (byteArray.length > size) { + value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); + logger.error( + "The byte array is too big, length is " + byteArray.length + " but max. length allowed is " + + size + ", ChannelId: " + logRecordContainer + .get(i).getChannelId()); + } else { + value = Const.HEXADECIMAL + LoggerUtils.byteArrayToHexString(byteArray); + } + break; + case STRING: + left = false; + size = checkMinimalValueSize( + logChannelList.get(logRecordContainer.get(i).getChannelId()).getValueTypeLength()); + value = logRecordContainer.get(i).getRecord().getValue().toString(); + try { + checkStringValue(value); + } catch (WrongCharacterException e) { + value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); + logger.error(e.getMessage()); + } + if (value.length() > size) { + value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); + logger.error("The string is too big, length is " + value + .length() + " but max. length allowed is " + size + ", ChannelId: " + logRecordContainer.get(i) + .getChannelId()); + } + break; + case BYTE: + value = String.format("0x%02x", logRecordContainer.get(i).getRecord().getValue().asByte()); + break; + default: + throw new RuntimeException("unsupported valueType"); + } + } + } else { + // write errorflag + value = LoggerUtils.buildError(logRecordContainer.get(i).getRecord().getFlag()); + size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); + } + } else { + // got no data + value = LoggerUtils.buildError(Flag.UNKNOWN_ERROR); + size = getDataTypeSize(logChannelList.get(logRecordContainer.get(i).getChannelId()), i); + } + + if (left) { + value = LoggerUtils.addSpacesLeft(value, size); + } else { + value = LoggerUtils.addSpacesRight(value, size); + } + sb.append(value); + + if (LoggerUtils.hasNext(logRecordContainer, i)) { + sb.append(Const.SEPARATOR); + } + } + sb.append(Const.LINESEPARATOR); // All systems with the same newline charter + return sb.toString(); + } + + /** + * Checkes a string if it is IESData conform, f.e. wrong characters. If not it will drop a error. + * + * @param value the string value which should be checked + */ + private void checkStringValue(String value) throws WrongCharacterException { + + if (value.contains(Const.SEPARATOR)) { + throw new WrongCharacterException("Wrong character: String contains Seperator character: " + Const.SEPARATOR); + } else if (value.startsWith(Const.ERROR)) { + throw new WrongCharacterException("Wrong character: String begins with: " + Const.ERROR); + } else if (value.startsWith(Const.HEXADECIMAL)) { + throw new WrongCharacterException("Wrong character: String begins with: " + Const.HEXADECIMAL); + } else if (!value.matches("^[\\x00-\\x7F]*")) { + throw new WrongCharacterException("Wrong character: Non ASCII character in String."); + } + } + + private int checkMinimalValueSize(int size) { + + if (size < Const.VALUE_SIZE_MINIMAL) { + size = Const.VALUE_SIZE_MINIMAL; + } + return size; + } + + /** + * Returns the PrintStream for logging. + * + * @param group + * @param loggingInterval + * @param date + * @param logChannelList + * @return the PrintStream for logging. + */ + private PrintStream getStream(LogIntervalContainerGroup group, int loggingInterval, int logTimeOffset, Date date, HashMap logChannelList) { + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + calendar.setTime(date); + String filename = LoggerUtils.buildFilename(loggingInterval, logTimeOffset, calendar); + + File file = new File(directoryPath + filename); + actualFile = file; + PrintStream out = null; + + try { + if (file.exists()) { + out = new PrintStream(new FileOutputStream(file, true), false, Const.CHAR_SET); + } else { + out = new PrintStream(new FileOutputStream(file, true), false, Const.CHAR_SET); + String headerString = header.getIESDataFormatHeaderString(group, file.getName(), loggingInterval, logChannelList); + + out.print(headerString); + out.flush(); + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + return out; + } + + /** + * Returns the size of a DataType / ValueType. + * + * @param logChannel + * @param iterator + * @return size of DataType / ValueType. + */ + private int getDataTypeSize(LogChannel logChannel, int iterator) { + + int size = Const.VALUE_SIZE_MINIMAL; + + if (logChannel != null) { + boolean isByteArray = logChannel.getValueType().equals(ValueType.BYTE_ARRAY); + boolean isString = logChannel.getValueType().equals(ValueType.STRING); + + if ((isByteArray || isString)) { + // get length from channel for ByteString + size = logChannel.getValueTypeLength(); + } else if (!(isByteArray || isString)) { + // get length from channel for simple value types + size = LoggerUtils.getLengthOfValueType(logChannel.getValueType()); + } + } else { + // get length from file + ValueType vt = LoggerUtils.identifyValueType(iterator + Const.NUM_OF_TIME_TYPES_IN_HEADER + 1, actualFile); + size = LoggerUtils.getLengthOfValueType(vt); + if ((vt.equals(ValueType.BYTE_ARRAY) || (vt.equals(ValueType.STRING))) && size <= Const.VALUE_SIZE_MINIMAL) { + size = LoggerUtils.getValueTypeLengthFromFile(iterator + Const.NUM_OF_TIME_TYPES_IN_HEADER + 1, actualFile); + } + } + return size; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogIntervalContainerGroup.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogIntervalContainerGroup.java index 69fd615d..85e8d913 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogIntervalContainerGroup.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/LogIntervalContainerGroup.java @@ -20,28 +20,28 @@ */ package org.openmuc.framework.datalogger.ascii; +import org.openmuc.framework.datalogger.spi.LogRecordContainer; + import java.util.ArrayList; import java.util.List; -import org.openmuc.framework.datalogger.spi.LogRecordContainer; - public class LogIntervalContainerGroup { - List containers; + List containers; - public LogIntervalContainerGroup() { + public LogIntervalContainerGroup() { - containers = new ArrayList(); - } + containers = new ArrayList(); + } - public void add(LogRecordContainer container) { + public void add(LogRecordContainer container) { - containers.add(container); - } + containers.add(container); + } - public List getList() { + public List getList() { - return containers; - } + return containers; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongCharacterException.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongCharacterException.java index feb1a90c..13ee7d7e 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongCharacterException.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongCharacterException.java @@ -22,19 +22,19 @@ public class WrongCharacterException extends Exception { - /** - * - */ - private static final long serialVersionUID = -5561675714266963968L; - private final String message; + /** + * + */ + private static final long serialVersionUID = -5561675714266963968L; + private final String message; - public WrongCharacterException(String message) { - this.message = message; - } + public WrongCharacterException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongScalingException.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongScalingException.java index d365cf27..27a8284b 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongScalingException.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/exceptions/WrongScalingException.java @@ -22,19 +22,19 @@ public class WrongScalingException extends Exception { - /** - * - */ - private static final long serialVersionUID = -3182849323748644497L; - private final String message; + /** + * + */ + private static final long serialVersionUID = -3182849323748644497L; + private final String message; - public WrongScalingException(String message) { - this.message = message; - } + public WrongScalingException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/Const.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/Const.java index 89d397ed..af3be461 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/Const.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/Const.java @@ -22,42 +22,42 @@ public class Const { - public final static String CHAR_SET = "UTF-8"; - - public final static String DEFAULT_DIR = System.getProperty("user.dir") + "/asciidata/"; - public final static String FILEINFO = "generated by AsciiLoger of OpenMUC"; - public final static double ISEFORMATVERSION = 1.00; - - public final static String EXTENSION = ".dat"; - public final static String EXTENSION_OLD = ".old"; - - public static final String HEADER_SIGN = "##"; - public static final String COMMENT_SIGN = "#"; - public static final String COMMENT_NAME = "comment"; - public static final String TIMESTAMP_STRING = "unixtimestamp"; - public static final short INVALID_INDEX = -1; - public static final String DATE_FORMAT = "%1$tY%1$tm%1$td"; // Date in YYYYMMDD - public static final String TIME_FORMAT = "%1$tH%1$tM%1$tS"; // Time in HHMMSS - public static final String SEPARATOR = ";\t"; - public static final char LINESEPARATOR = '\n'; - public static final String LINESEPARATOR_STRING = "\n"; - public static final String ERROR = "err"; - public static final String COL_NUM = "col_no"; - public static final String DATATYPE_NAME = "value_type"; - public static final String VALUETYPE_ENDSIGN = ". "; - public static final String VALUETYPE_SIZE_SEPARATOR = ","; - public static final String HEXADECIMAL = "0x"; - - public static final char MINUS_SIGN = '-'; - public static final char PLUS_SIGN = '+'; - public static final char DECIMAL_SEPARATOR = '.'; - - public static final int SIZE_LEADING_SIGN = 1; - public static final int VALUE_SIZE_DOUBLE = 8 + SIZE_LEADING_SIGN; - public static final int VALUE_SIZE_INTEGER = 11 + SIZE_LEADING_SIGN; - public static final int VALUE_SIZE_LONG = 20 + SIZE_LEADING_SIGN; - public static final int VALUE_SIZE_SHORT = 6 + SIZE_LEADING_SIGN; - public static final int VALUE_SIZE_MINIMAL = 5 + SIZE_LEADING_SIGN; - - public static final int NUM_OF_TIME_TYPES_IN_HEADER = 3; + public final static String CHAR_SET = "UTF-8"; + + public final static String DEFAULT_DIR = System.getProperty("user.dir") + "/asciidata/"; + public final static String FILEINFO = "generated by AsciiLoger of OpenMUC"; + public final static double ISEFORMATVERSION = 1.00; + + public final static String EXTENSION = ".dat"; + public final static String EXTENSION_OLD = ".old"; + + public static final String HEADER_SIGN = "##"; + public static final String COMMENT_SIGN = "#"; + public static final String COMMENT_NAME = "comment"; + public static final String TIMESTAMP_STRING = "unixtimestamp"; + public static final short INVALID_INDEX = -1; + public static final String DATE_FORMAT = "%1$tY%1$tm%1$td"; // Date in YYYYMMDD + public static final String TIME_FORMAT = "%1$tH%1$tM%1$tS"; // Time in HHMMSS + public static final String SEPARATOR = ";\t"; + public static final char LINESEPARATOR = '\n'; + public static final String LINESEPARATOR_STRING = "\n"; + public static final String ERROR = "err"; + public static final String COL_NUM = "col_no"; + public static final String DATATYPE_NAME = "value_type"; + public static final String VALUETYPE_ENDSIGN = ". "; + public static final String VALUETYPE_SIZE_SEPARATOR = ","; + public static final String HEXADECIMAL = "0x"; + + public static final char MINUS_SIGN = '-'; + public static final char PLUS_SIGN = '+'; + public static final char DECIMAL_SEPARATOR = '.'; + + public static final int SIZE_LEADING_SIGN = 1; + public static final int VALUE_SIZE_DOUBLE = 8 + SIZE_LEADING_SIGN; + public static final int VALUE_SIZE_INTEGER = 11 + SIZE_LEADING_SIGN; + public static final int VALUE_SIZE_LONG = 20 + SIZE_LEADING_SIGN; + public static final int VALUE_SIZE_SHORT = 6 + SIZE_LEADING_SIGN; + public static final int VALUE_SIZE_MINIMAL = 5 + SIZE_LEADING_SIGN; + + public static final int NUM_OF_TIME_TYPES_IN_HEADER = 3; } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/IESDataFormatUtils.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/IESDataFormatUtils.java index 863f832e..6610d45b 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/IESDataFormatUtils.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/IESDataFormatUtils.java @@ -20,73 +20,68 @@ */ package org.openmuc.framework.datalogger.ascii.utils; +import org.openmuc.framework.datalogger.ascii.exceptions.WrongScalingException; + import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; -import org.openmuc.framework.datalogger.ascii.exceptions.WrongScalingException; - public class IESDataFormatUtils { - // private final static Logger logger = LoggerFactory.getLogger(IESDataFormatUtils.class); + // private final static Logger logger = LoggerFactory.getLogger(IESDataFormatUtils.class); - /** - * Convert a double value into a string with the maximal allowed length of maxlength. - * - * @param value - * @param maxLength - * The maximal allowed length with all signs. - * @return a double as string with max length. - * @throws WrongScalingException - */ - public static String convertDoubleToStringWithMaxLength(double value, int maxLength) throws WrongScalingException { + /** + * Convert a double value into a string with the maximal allowed length of maxlength. + * + * @param value + * @param maxLength The maximal allowed length with all signs. + * @return a double as string with max length. + * @throws WrongScalingException + */ + public static String convertDoubleToStringWithMaxLength(double value, int maxLength) throws WrongScalingException { - String ret; + String ret; - String format; - double valueWork = value; - long lValue = (long) (valueWork * 10000.0); - valueWork = lValue / 10000.0; + String format; + double valueWork = value; + long lValue = (long) (valueWork * 10000.0); + valueWork = lValue / 10000.0; - if (lValue >= 0) { + if (lValue >= 0) { - if (lValue >> 63 != 0) { - valueWork *= -1l; - } - format = '+' + getFormat(valueWork); - } - else { - format = getFormat(valueWork); - } + if (lValue >> 63 != 0) { + valueWork *= -1l; + } + format = '+' + getFormat(valueWork); + } else { + format = getFormat(valueWork); + } - DecimalFormat df = new DecimalFormat(format, new DecimalFormatSymbols(Locale.ENGLISH)); - ret = df.format(valueWork); + DecimalFormat df = new DecimalFormat(format, new DecimalFormatSymbols(Locale.ENGLISH)); + ret = df.format(valueWork); - if (ret.length() > maxLength) { - throw new WrongScalingException("Double value (" + value + ") too large for convertion into max length " - + maxLength + "! Try to scale value."); - } - return ret; - } + if (ret.length() > maxLength) { + throw new WrongScalingException( + "Double value (" + value + ") too large for convertion into max length " + maxLength + "! Try to scale value."); + } + return ret; + } - private static String getFormat(double value) { + private static String getFormat(double value) { - long lValue = (long) value; - String format; + long lValue = (long) value; + String format; - if (lValue > 999999 || lValue < -999999) { - format = "#######0"; - } - else if (lValue > 99999 || lValue < -99999) { - format = "#####0.0"; - } - else if (lValue > 9999 || lValue < -9999) { - format = "####0.00"; - } - else { - format = "###0.000"; - } + if (lValue > 999999 || lValue < -999999) { + format = "#######0"; + } else if (lValue > 99999 || lValue < -99999) { + format = "#####0.0"; + } else if (lValue > 9999 || lValue < -9999) { + format = "####0.00"; + } else { + format = "###0.000"; + } - return format; - } + return format; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LogRecordContainerAscii.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LogRecordContainerAscii.java index b0807d82..19572b1e 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LogRecordContainerAscii.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LogRecordContainerAscii.java @@ -25,25 +25,25 @@ public class LogRecordContainerAscii implements LogRecordContainer { - String channelId; - Record record; + String channelId; + Record record; - public LogRecordContainerAscii(String channelId, Record record) { + public LogRecordContainerAscii(String channelId, Record record) { - this.channelId = channelId; - this.record = record; - } + this.channelId = channelId; + this.record = record; + } - @Override - public String getChannelId() { + @Override + public String getChannelId() { - return channelId; - } + return channelId; + } - @Override - public Record getRecord() { + @Override + public Record getRecord() { - return record; - } + return record; + } } diff --git a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LoggerUtils.java b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LoggerUtils.java index ff866519..4626aad9 100644 --- a/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LoggerUtils.java +++ b/projects/datalogger/ascii/src/main/java/org/openmuc/framework/datalogger/ascii/utils/LoggerUtils.java @@ -20,806 +20,761 @@ */ package org.openmuc.framework.datalogger.ascii.utils; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import java.util.NoSuchElementException; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.datalogger.spi.LogRecordContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.util.*; + public class LoggerUtils { - private static final Logger logger = LoggerFactory.getLogger(LoggerUtils.class); - - /** - * Returns all filenames of the given timespan defined by the two dates - * - * @param loggingInterval - * @param startTimestamp - * @param endTimestamp - * @return a list of files which within the timespan - */ - public static List getFilenames(int loggingInterval, int logTimeOffset, long startTimestamp, - long endTimestamp) { - - Calendar calendarStart = new GregorianCalendar(Locale.getDefault()); - calendarStart.setTimeInMillis(startTimestamp); - Calendar calendarEnd = new GregorianCalendar(Locale.getDefault()); - calendarEnd.setTimeInMillis(endTimestamp); - - // Rename timespanToFilenames.... - // Filename YYYYMMDD_.dat - List filenames = new ArrayList(); - while (calendarStart.before(calendarEnd) || calendarStart.equals(calendarEnd)) { - String filename = buildFilename(loggingInterval, logTimeOffset, calendarStart); - filenames.add(filename); - - // set date to 00:00:00 of the next day - calendarStart.add(Calendar.DAY_OF_MONTH, 1); - calendarStart.set(Calendar.HOUR_OF_DAY, 0); - calendarStart.set(Calendar.MINUTE, 0); - calendarStart.set(Calendar.SECOND, 0); - calendarStart.set(Calendar.MILLISECOND, 0); - } - return filenames; - } - - /** - * Returns the filename, with the help of the timestamp and the interval. - * - * @param loggingInterval - * @param timestamp - * @return a filename from timestamp (date) and interval - */ - public static String getFilename(int loggingInterval, int logTimeOffset, long timestamp) { - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - calendar.setTimeInMillis(timestamp); - return buildFilename(loggingInterval, logTimeOffset, calendar); - } - - /** - * Builds the Logfile name from logging interval, logging time offset and the date of the calendar - * - * @param loggingInterval - * @param calendar - * @return logfile name - */ - public static String buildFilename(int loggingInterval, int logTimeOffset, Calendar calendar) { - - StringBuilder sb = new StringBuilder(); - sb.append(String.format(Const.DATE_FORMAT, calendar)); - sb.append('_'); - sb.append(String.valueOf(loggingInterval)); - - if (logTimeOffset != 0) { - sb.append('_'); - sb.append(logTimeOffset); - } - sb.append(Const.EXTENSION); - return sb.toString(); - } - - /** - * Builds the Logfile name from string interval_timeOffset and the date of the calendar - * - * @param loggingInterval - * @param calendar - * @return logfile name - */ - public static String buildFilename(String interval_timeOffset, Calendar calendar) { - - StringBuilder sb = new StringBuilder(); - sb.append(String.format(Const.DATE_FORMAT, calendar)); - sb.append('_'); - sb.append(interval_timeOffset); - - sb.append(Const.EXTENSION); - return sb.toString(); - } - - /** - * Checks if it has a next container entry. - * - * @param containers - * @param i - * @return true if it has a next container entry, if not else. - */ - public static boolean hasNext(List containers, int i) { - - boolean result = false; - if (i <= containers.size() - 2) { - result = true; - } - return result; - } - - /** - * This method rename all *.dat files with the date from today in directoryPath into a *.old0, *.old1, ... - * - * @param directoryPath - * @param calendar - */ - public static void renameOldFiles(String directoryPath, Calendar calendar) { - - String date = String.format(Const.DATE_FORMAT, calendar); - - File dir = new File(directoryPath); - File[] files = dir.listFiles(); - - for (File file : files) { - String currentName = file.getName(); - if (currentName.startsWith(date) && currentName.endsWith(Const.EXTENSION)) { - - String newName = currentName.substring(0, currentName.length() - Const.EXTENSION.length()); - newName += Const.EXTENSION_OLD; - int j = 0; - - File fileWithNewName = new File(directoryPath + newName + j); - - while (fileWithNewName.exists()) { - ++j; - fileWithNewName = new File(directoryPath + newName + j); - } - if (!file.renameTo(fileWithNewName)) { - logger.error("Could not rename file to " + newName); - } - } - } - } - - /** - * This method renames a singel <date>_<loggerIntervall>_<loggerTimeOffset>.dat file into a - * *.old0, *.old1, ... - * - * @param directoryPath - * @param calendar - */ - public static void renameToOldFile(String directoryPath, String loggerIntervall_loggerTimeOffset, Calendar calendar) { - - File file = new File(directoryPath + buildFilename(loggerIntervall_loggerTimeOffset, calendar)); - - if (file.exists()) { - String currentName = file.getName(); - - String newName = currentName.substring(0, currentName.length() - Const.EXTENSION.length()); - newName += Const.EXTENSION_OLD; - int j = 0; - - File fileWithNewName = new File(directoryPath + newName + j); - - while (fileWithNewName.exists()) { - ++j; - fileWithNewName = new File(directoryPath + newName + j); - } - if (!file.renameTo(fileWithNewName)) { - logger.error("Could not rename file to " + newName); - } - } - } - - /** - * Returns the calendar from today with the first hour, minute, second and millisecond. - * - * @param today - * @return the calendar from today with the first hour, minute, second and millisecond - */ - public static Calendar getCalendarTodayZero(Calendar today) { - - Calendar calendarZero = new GregorianCalendar(Locale.getDefault()); - calendarZero.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE), 0, 0, 0); - calendarZero.set(Calendar.MILLISECOND, 0); - - return calendarZero; - } - - /** - * This method adds a string value up with blank spaces from left to right. - * - * @param value - * String value to fill up - * @param size - * maximal allowed size - * @return the modified string. - */ - public static String addSpacesLeft(String value, int size) { - - StringBuilder sb = new StringBuilder(); - int i = value.length(); - while (i < size) { - sb.append(' '); - ++i; - } - sb.append(value); - return sb.toString(); - } - - /** - * This method adds a string value up with blank spaces from right to left. - * - * @param value - * String value to fill up - * @param size - * maximal allowed size - * @return the modified string. - */ - public static String addSpacesRight(String value, int size) { - - StringBuilder sb = new StringBuilder(); - sb.append(value); - int i = value.length(); - while (i < size) { - sb.append(' '); - ++i; - } - return sb.toString(); - } - - /** - * This method adds a string value up with blank spaces from left to right. - * - * @param value - * String value to fill up - * @param size - * maximal allowed size - */ - public static void appendSpaces(StringBuilder sb, int number) { - - for (int i = 0; i < number; ++i) { - sb.append(' '); - } - } - - /** - * Construct a error value with the flag. - * - * @param flag - * @return a string with the flag and the standard error prefix. - */ - public static String buildError(Flag flag) { - - return Const.ERROR + flag.getCode(); - } - - /** - * Get the column number by name. - * - * @param line - * @param name - * @return the column number as int. - */ - public static int getColumnNumberByName(String line, String name) { - - int channelColumn = -1; - - // erste Zeile ohne Kommentar finden dann den Spaltennamen suchen und dessen Possitionsnummer zurückgeben. - if (!line.startsWith(Const.COMMENT_SIGN)) { - String columns[] = line.split(Const.SEPARATOR); - int i = 0; - while (i < columns.length) { - if (name.equals(columns[i])) { - return i; - } - i++; - } - } - return channelColumn; - } - - /** - * Get the column number by name, in comments. It searches the line by his self. The BufferdReader has to be on the - * begin of the file. - * - * @param name - * the name to search - * @param br - * the BufferedReader - * @return column number as int, -1 if name not found - * @throws IOException - */ - public static int getCommentColumnNumberByName(String name, BufferedReader br) throws IOException, - NullPointerException { - - String line = br.readLine(); - - while (line != null && line.startsWith(Const.COMMENT_SIGN)) { - if (line.contains(name)) { - String columns[] = line.split(Const.SEPARATOR); - for (int i = 0; i < columns.length; i++) { - if (name.equals(columns[i])) { - return i; - } - } - } - try { - line = br.readLine(); - } catch (NullPointerException e) { - return -1; - } - } - return -1; - } - - /** - * - * @param col_no - * the number of the channel - * @param column - * the column - * @param br - * a BufferedReader - * @return the value of a column of a specific col_num - * @throws IOException - */ - public static String getCommentValue(int col_no, int column, BufferedReader br) throws IOException { - - String line = br.readLine(); - String columnName = String.format("%03d", col_no); - - while (line != null && line.startsWith(Const.COMMENT_SIGN)) { - if (line.startsWith(Const.COMMENT_SIGN + columnName)) { - String columns[] = line.split(Const.SEPARATOR); - return columns[column]; - } - line = br.readLine(); - } - return null; - } - - /** - * Identifies the ValueType of a logger value on a specific col_no - * - * @param columnNumber - * column number - * @param dataFile - * the logger data file - * @return the ValueType from col_num x - */ - public static ValueType identifyValueType(int columnNumber, File dataFile) { - - String valueType = getValueTypeAsString(columnNumber, dataFile); - String valueTypeArray[] = valueType.split(Const.VALUETYPE_ENDSIGN); - - return ValueType.valueOf(valueTypeArray[0]); - } - - public static int getValueTypeLengthFromFile(int columnNumber, File dataFile) { - - String valueType = getValueTypeAsString(columnNumber, dataFile); - return getByteStringLength(valueType); - } - - private static String getValueTypeAsString(int columnNumber, File dataFile) { - - BufferedReader br = null; - String value = ""; - - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "US-ASCII")); - int column = LoggerUtils.getCommentColumnNumberByName(Const.COMMENT_NAME, br); - - if (column != -1) { - value = LoggerUtils.getCommentValue(columnNumber, column, br); - value = value.split(Const.VALUETYPE_ENDSIGN)[0]; - } - else { - throw new NoSuchElementException("No element with name \"" + Const.COMMENT_NAME + "\" found."); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (NoSuchElementException e) { - e.printStackTrace(); - } finally { - closeBufferdReader(br); - } - return value; - } - - /** - * Returns the predefined size of a ValueType. - * - * @param valueType - * @return predefined size of a ValueType as int. - */ - public static int getLengthOfValueType(ValueType valueType) { - - int size; - - switch (valueType) { - case DOUBLE: - size = Const.VALUE_SIZE_DOUBLE; - break; - case FLOAT: - size = Const.VALUE_SIZE_DOUBLE; - break; - case INTEGER: - size = Const.VALUE_SIZE_INTEGER; - break; - case LONG: - size = Const.VALUE_SIZE_LONG; - break; - case SHORT: - size = Const.VALUE_SIZE_SHORT; - break; - case BYTE_ARRAY: - size = Const.VALUE_SIZE_MINIMAL; - break; - case STRING: - size = Const.VALUE_SIZE_MINIMAL; - break; - case BOOLEAN: - case BYTE: - default: - size = Const.VALUE_SIZE_MINIMAL; - break; - } - return size; - } - - /** - * Converts a byte array to an hexadecimal string - * - * @param byteArray - * @return hexadecimal string - */ - public static String byteArrayToHexString(byte[] byteArray) { - - char[] hexArray = "0123456789ABCDEF".toCharArray(); - char[] hexChars = new char[byteArray.length * 2]; - for (int j = 0; j < byteArray.length; j++) { - int v = byteArray[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } - - /** - * Constructs the timestamp for every log value into a StringBuilder. - * - * @param sb - * @param calendar - */ - public static void setLoggerTimestamps(StringBuilder sb, Calendar calendar) { - - double unixtimestamp_sec = calendar.getTimeInMillis() / 1000.0; // double for milliseconds, nanoseconds - - sb.append(String.format(Const.DATE_FORMAT, calendar)); - sb.append(Const.SEPARATOR); - sb.append(String.format(Const.TIME_FORMAT, calendar)); - sb.append(Const.SEPARATOR); - sb.append(String.format(Locale.ENGLISH, "%10.3f", unixtimestamp_sec)); - sb.append(Const.SEPARATOR); - } - - /** - * Constructs the timestamp for every log value into a StringBuilder. - * - * @param sb - * @param unixTimeStamp - * unix time stamp in ms - */ - public static void setLoggerTimestamps(StringBuilder sb, long unixTimeStamp) { - - Calendar calendar = new GregorianCalendar(Locale.getDefault()); - calendar.setTimeInMillis(unixTimeStamp); - double unixtimestamp_sec = unixTimeStamp / 1000.0; // double for milliseconds, nanoseconds - - sb.append(String.format(Const.DATE_FORMAT, calendar)); - sb.append(Const.SEPARATOR); - sb.append(String.format(Const.TIME_FORMAT, calendar)); - sb.append(Const.SEPARATOR); - sb.append(String.format(Locale.ENGLISH, "%10.3f", unixtimestamp_sec)); - sb.append(Const.SEPARATOR); - } - - public static String getHeaderFromFile(String filePath, String logIntervall_logTimeOffset) { - - BufferedReader br = LoggerUtils.getBufferedReader(new File(filePath)); - - if (br != null) { - StringBuilder sb = new StringBuilder(); - - try { - String line = br.readLine(); - - if (line != null) { - sb.append(line); - while (line != null && line.startsWith(Const.COMMENT_SIGN)) { - sb.append(Const.LINESEPARATOR); - line = br.readLine(); - sb.append(line); - } - } - } catch (IOException e) { - logger.error("Problems to handle file: " + filePath, e); - } finally { - - try { - br.close(); - } catch (IOException e) { - logger.error("Can not close file: " + filePath, e); - } - } - return sb.toString(); - } - else { - return ""; - } - } - - /** - * Returns a RandomAccessFile of the specified file. - * - * @param filePath - * @param accsesMode - * @return the RandomAccessFile of the specified file - */ - public static RandomAccessFile getRandomAccessFile(File file, String accsesMode) { - - RandomAccessFile raf = null; - try { - raf = new RandomAccessFile(file, accsesMode); - } catch (FileNotFoundException e) { - - logger.warn("Requested logfile: '" + file.getAbsolutePath() + "' not found."); - // e.printStackTrace(); - } - return raf; - } - - public static BufferedReader getBufferedReader(File file) { - - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Const.CHAR_SET)); - } catch (IOException e) { - logger.error("Can not open file: " + file.getAbsolutePath()); - } - return reader; - } - - public static PrintWriter getPrintWriter(File file, boolean append) { - - PrintWriter writer = null; - try { - writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, append), Const.CHAR_SET)); - } catch (IOException e) { - logger.error("Can not open file: " + file.getAbsolutePath()); - } - return writer; - } - - public static void fillUpFileWithErrorCode(String directoryPath, String loggerIntervall_loggerTimeOffset, - Calendar calendar) { - - String filename = buildFilename(loggerIntervall_loggerTimeOffset, calendar); - File file = new File(directoryPath + filename); - RandomAccessFile raf = LoggerUtils.getRandomAccessFile(file, "r"); - PrintWriter out = null; - - String firstLogLine = ""; - String lastLogLine = ""; - long loggingIntervall = 0; - - if (loggerIntervall_loggerTimeOffset.contains("_")) { - loggingIntervall = Long.parseLong(loggerIntervall_loggerTimeOffset.split("_")[0]); - } - else { - loggingIntervall = Long.parseLong(loggerIntervall_loggerTimeOffset); - } - - // String restOfLastLine = ""; - long unixTimeStamp = 0; - - if (raf != null) { - try { - String line = raf.readLine(); - if (line != null) { - - while (line.startsWith(Const.COMMENT_SIGN)) { - // do nothing with this data, only for finding the begin of logging - line = raf.readLine(); - } - firstLogLine = raf.readLine(); - } - - // read last line backwards and read last line - byte[] byti = new byte[1]; - long filePosition = file.length() - 2; - String charString; - while (lastLogLine.isEmpty() && filePosition > 0) { - - raf.seek(filePosition); - int readedBytes = raf.read(byti); - if (readedBytes == 1) { - charString = new String(byti, Const.CHAR_SET); - - if (charString.equals(Const.LINESEPARATOR_STRING)) { - lastLogLine = raf.readLine(); - } - else { - filePosition -= 1; - } - } - else { - filePosition = -1; // leave the while loop - } - } - raf.close(); - - int firstLogLineLength = firstLogLine.length(); - - int lastLogLineLength = lastLogLine.length(); - - if (firstLogLineLength != lastLogLineLength) { - /** - * TODO: different size of logging lines, probably the last one is corrupted we have to fill it up - * restOfLastLine = completeLastLine(firstLogLine, lastLogLine); raf.writeChars(restOfLastLine); - */ - // File is corrupted rename to old - renameToOldFile(directoryPath, loggerIntervall_loggerTimeOffset, calendar); - } - else { - - String lineArray[] = lastLogLine.split(Const.SEPARATOR); - - StringBuilder errorValues = getErrorValues(lineArray); - unixTimeStamp = ((long) Double.parseDouble(lineArray[2])) * 1000; - - // FileChannel fileChannel = raf.getChannel(); - out = getPrintWriter(file, true); - - long numberOfFillUpLines = getNumberOfFillUpLines(unixTimeStamp, loggingIntervall); - - while (numberOfFillUpLines > 0) { - - unixTimeStamp = fillUp(out, unixTimeStamp, loggingIntervall, lastLogLineLength, - numberOfFillUpLines, errorValues); - numberOfFillUpLines = getNumberOfFillUpLines(unixTimeStamp, loggingIntervall); - } - out.close(); - } - } catch (IOException e) { - logger.error("Could not read file " + file.getAbsolutePath(), e); - renameToOldFile(directoryPath, loggerIntervall_loggerTimeOffset, calendar); - } finally { - try { - - if (raf != null) { - raf.close(); - } - if (out != null) { - out.close(); - } - } catch (IOException e) { - logger.error("Could not close file " + file.getAbsolutePath()); - } - } - } - } - - private static long fillUp(PrintWriter out, long unixTimeStamp, long loggingIntervall, int lastLogLineLength, - long numberOfFillUpLines, StringBuilder errorValues) throws IOException { - - StringBuilder line = new StringBuilder(); - for (int i = 0; i < numberOfFillUpLines; i++) { - - line.setLength(0); - unixTimeStamp += loggingIntervall; - setLoggerTimestamps(line, unixTimeStamp); - line.append(errorValues); - line.append(Const.LINESEPARATOR); - - out.append(line.toString()); - } - - return unixTimeStamp; - } - - private static long getNumberOfFillUpLines(long lastUnixTimeStamp, long loggingIntervall) { - - long numberOfFillUpLines = 0; - long currentUnixTimeStamp = System.currentTimeMillis(); - - numberOfFillUpLines = (currentUnixTimeStamp - lastUnixTimeStamp) / loggingIntervall; - - return numberOfFillUpLines; - } - - /** - * - * @param errorValues - * has to be empty at begin - * @param logLine - * @return - */ - private static StringBuilder getErrorValues(String lineArray[]) { - - StringBuilder errorValues = new StringBuilder(); - int arrayLength = lineArray.length; - int errorCodeLength = Const.ERROR.length() + 2; - int separatorLength = Const.SEPARATOR.length(); - int length = 0; - - for (int i = 3; i < arrayLength; ++i) { - - length = lineArray[i].length(); - length -= errorCodeLength; - if (i > arrayLength - 1) { - length -= separatorLength; - } - appendSpaces(errorValues, length); - errorValues.append(Const.ERROR); - errorValues.append(Flag.DATA_LOGGING_NOT_ACTIVE.getCode()); - - if (i < arrayLength - 1) { - errorValues.append(Const.SEPARATOR); - } - } - return errorValues; - } - - // private static String completeLastLine(String firstLogLine, String lastLogLine) { - // - // // TODO different size of logging lines, probably the last one is corrupted we have to fill it up - // // TODO: wenn letzte Zeile zu defekt ist also ohne Timestamp, löschen und vorletzte Zeile nehmen und - // // dessen Zeit. - // int firstLogLineLength = firstLogLine.length(); - // int lastLogLineLength = lastLogLine.length(); - // - // return ""; - // } - - /** - * Get the length from a type+length tuple. Example: "Byte_String,95" - * - * @param string - * has to be a string with ByteType and length. - * @param dataFile - * the logger data file - * @return the length of a ByteString in int. - */ - private static int getByteStringLength(String string) { - - String stringArray[]; - int size; - - stringArray = string.split(Const.VALUETYPE_SIZE_SEPARATOR); - try { - size = Integer.parseInt(stringArray[1]); - } catch (NumberFormatException e) { - logger.warn("Not able to get ValueType length from String. Set length to minimal lenght " - + Const.VALUE_SIZE_MINIMAL + "."); - size = Const.VALUE_SIZE_MINIMAL; - } - return size; - } - - private static void closeBufferdReader(BufferedReader br) { - - try { - br.close(); - } catch (Exception e1) { - } - } + private static final Logger logger = LoggerFactory.getLogger(LoggerUtils.class); + + /** + * Returns all filenames of the given timespan defined by the two dates + * + * @param loggingInterval + * @param startTimestamp + * @param endTimestamp + * @return a list of files which within the timespan + */ + public static List getFilenames(int loggingInterval, int logTimeOffset, long startTimestamp, long endTimestamp) { + + Calendar calendarStart = new GregorianCalendar(Locale.getDefault()); + calendarStart.setTimeInMillis(startTimestamp); + Calendar calendarEnd = new GregorianCalendar(Locale.getDefault()); + calendarEnd.setTimeInMillis(endTimestamp); + + // Rename timespanToFilenames.... + // Filename YYYYMMDD_.dat + List filenames = new ArrayList(); + while (calendarStart.before(calendarEnd) || calendarStart.equals(calendarEnd)) { + String filename = buildFilename(loggingInterval, logTimeOffset, calendarStart); + filenames.add(filename); + + // set date to 00:00:00 of the next day + calendarStart.add(Calendar.DAY_OF_MONTH, 1); + calendarStart.set(Calendar.HOUR_OF_DAY, 0); + calendarStart.set(Calendar.MINUTE, 0); + calendarStart.set(Calendar.SECOND, 0); + calendarStart.set(Calendar.MILLISECOND, 0); + } + return filenames; + } + + /** + * Returns the filename, with the help of the timestamp and the interval. + * + * @param loggingInterval + * @param timestamp + * @return a filename from timestamp (date) and interval + */ + public static String getFilename(int loggingInterval, int logTimeOffset, long timestamp) { + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + calendar.setTimeInMillis(timestamp); + return buildFilename(loggingInterval, logTimeOffset, calendar); + } + + /** + * Builds the Logfile name from logging interval, logging time offset and the date of the calendar + * + * @param loggingInterval + * @param calendar + * @return logfile name + */ + public static String buildFilename(int loggingInterval, int logTimeOffset, Calendar calendar) { + + StringBuilder sb = new StringBuilder(); + sb.append(String.format(Const.DATE_FORMAT, calendar)); + sb.append('_'); + sb.append(String.valueOf(loggingInterval)); + + if (logTimeOffset != 0) { + sb.append('_'); + sb.append(logTimeOffset); + } + sb.append(Const.EXTENSION); + return sb.toString(); + } + + /** + * Builds the Logfile name from string interval_timeOffset and the date of the calendar + * + * @param loggingInterval + * @param calendar + * @return logfile name + */ + public static String buildFilename(String interval_timeOffset, Calendar calendar) { + + StringBuilder sb = new StringBuilder(); + sb.append(String.format(Const.DATE_FORMAT, calendar)); + sb.append('_'); + sb.append(interval_timeOffset); + + sb.append(Const.EXTENSION); + return sb.toString(); + } + + /** + * Checks if it has a next container entry. + * + * @param containers + * @param i + * @return true if it has a next container entry, if not else. + */ + public static boolean hasNext(List containers, int i) { + + boolean result = false; + if (i <= containers.size() - 2) { + result = true; + } + return result; + } + + /** + * This method rename all *.dat files with the date from today in directoryPath into a *.old0, *.old1, ... + * + * @param directoryPath + * @param calendar + */ + public static void renameOldFiles(String directoryPath, Calendar calendar) { + + String date = String.format(Const.DATE_FORMAT, calendar); + + File dir = new File(directoryPath); + File[] files = dir.listFiles(); + + for (File file : files) { + String currentName = file.getName(); + if (currentName.startsWith(date) && currentName.endsWith(Const.EXTENSION)) { + + String newName = currentName.substring(0, currentName.length() - Const.EXTENSION.length()); + newName += Const.EXTENSION_OLD; + int j = 0; + + File fileWithNewName = new File(directoryPath + newName + j); + + while (fileWithNewName.exists()) { + ++j; + fileWithNewName = new File(directoryPath + newName + j); + } + if (!file.renameTo(fileWithNewName)) { + logger.error("Could not rename file to " + newName); + } + } + } + } + + /** + * This method renames a singel <date>_<loggerIntervall>_<loggerTimeOffset>.dat file into a + * *.old0, *.old1, ... + * + * @param directoryPath + * @param calendar + */ + public static void renameToOldFile(String directoryPath, String loggerIntervall_loggerTimeOffset, Calendar calendar) { + + File file = new File(directoryPath + buildFilename(loggerIntervall_loggerTimeOffset, calendar)); + + if (file.exists()) { + String currentName = file.getName(); + + String newName = currentName.substring(0, currentName.length() - Const.EXTENSION.length()); + newName += Const.EXTENSION_OLD; + int j = 0; + + File fileWithNewName = new File(directoryPath + newName + j); + + while (fileWithNewName.exists()) { + ++j; + fileWithNewName = new File(directoryPath + newName + j); + } + if (!file.renameTo(fileWithNewName)) { + logger.error("Could not rename file to " + newName); + } + } + } + + /** + * Returns the calendar from today with the first hour, minute, second and millisecond. + * + * @param today + * @return the calendar from today with the first hour, minute, second and millisecond + */ + public static Calendar getCalendarTodayZero(Calendar today) { + + Calendar calendarZero = new GregorianCalendar(Locale.getDefault()); + calendarZero.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE), 0, 0, 0); + calendarZero.set(Calendar.MILLISECOND, 0); + + return calendarZero; + } + + /** + * This method adds a string value up with blank spaces from left to right. + * + * @param value String value to fill up + * @param size maximal allowed size + * @return the modified string. + */ + public static String addSpacesLeft(String value, int size) { + + StringBuilder sb = new StringBuilder(); + int i = value.length(); + while (i < size) { + sb.append(' '); + ++i; + } + sb.append(value); + return sb.toString(); + } + + /** + * This method adds a string value up with blank spaces from right to left. + * + * @param value String value to fill up + * @param size maximal allowed size + * @return the modified string. + */ + public static String addSpacesRight(String value, int size) { + + StringBuilder sb = new StringBuilder(); + sb.append(value); + int i = value.length(); + while (i < size) { + sb.append(' '); + ++i; + } + return sb.toString(); + } + + /** + * This method adds a string value up with blank spaces from left to right. + * + * @param value String value to fill up + * @param size maximal allowed size + */ + public static void appendSpaces(StringBuilder sb, int number) { + + for (int i = 0; i < number; ++i) { + sb.append(' '); + } + } + + /** + * Construct a error value with the flag. + * + * @param flag + * @return a string with the flag and the standard error prefix. + */ + public static String buildError(Flag flag) { + + return Const.ERROR + flag.getCode(); + } + + /** + * Get the column number by name. + * + * @param line + * @param name + * @return the column number as int. + */ + public static int getColumnNumberByName(String line, String name) { + + int channelColumn = -1; + + // erste Zeile ohne Kommentar finden dann den Spaltennamen suchen und dessen Possitionsnummer zurückgeben. + if (!line.startsWith(Const.COMMENT_SIGN)) { + String columns[] = line.split(Const.SEPARATOR); + int i = 0; + while (i < columns.length) { + if (name.equals(columns[i])) { + return i; + } + i++; + } + } + return channelColumn; + } + + /** + * Get the column number by name, in comments. It searches the line by his self. The BufferdReader has to be on the + * begin of the file. + * + * @param name the name to search + * @param br the BufferedReader + * @return column number as int, -1 if name not found + * @throws IOException + */ + public static int getCommentColumnNumberByName(String name, BufferedReader br) throws IOException, NullPointerException { + + String line = br.readLine(); + + while (line != null && line.startsWith(Const.COMMENT_SIGN)) { + if (line.contains(name)) { + String columns[] = line.split(Const.SEPARATOR); + for (int i = 0; i < columns.length; i++) { + if (name.equals(columns[i])) { + return i; + } + } + } + try { + line = br.readLine(); + } catch (NullPointerException e) { + return -1; + } + } + return -1; + } + + /** + * @param col_no the number of the channel + * @param column the column + * @param br a BufferedReader + * @return the value of a column of a specific col_num + * @throws IOException + */ + public static String getCommentValue(int col_no, int column, BufferedReader br) throws IOException { + + String line = br.readLine(); + String columnName = String.format("%03d", col_no); + + while (line != null && line.startsWith(Const.COMMENT_SIGN)) { + if (line.startsWith(Const.COMMENT_SIGN + columnName)) { + String columns[] = line.split(Const.SEPARATOR); + return columns[column]; + } + line = br.readLine(); + } + return null; + } + + /** + * Identifies the ValueType of a logger value on a specific col_no + * + * @param columnNumber column number + * @param dataFile the logger data file + * @return the ValueType from col_num x + */ + public static ValueType identifyValueType(int columnNumber, File dataFile) { + + String valueType = getValueTypeAsString(columnNumber, dataFile); + String valueTypeArray[] = valueType.split(Const.VALUETYPE_ENDSIGN); + + return ValueType.valueOf(valueTypeArray[0]); + } + + public static int getValueTypeLengthFromFile(int columnNumber, File dataFile) { + + String valueType = getValueTypeAsString(columnNumber, dataFile); + return getByteStringLength(valueType); + } + + private static String getValueTypeAsString(int columnNumber, File dataFile) { + + BufferedReader br = null; + String value = ""; + + try { + br = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "US-ASCII")); + int column = LoggerUtils.getCommentColumnNumberByName(Const.COMMENT_NAME, br); + + if (column != -1) { + value = LoggerUtils.getCommentValue(columnNumber, column, br); + value = value.split(Const.VALUETYPE_ENDSIGN)[0]; + } else { + throw new NoSuchElementException("No element with name \"" + Const.COMMENT_NAME + "\" found."); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } finally { + closeBufferdReader(br); + } + return value; + } + + /** + * Returns the predefined size of a ValueType. + * + * @param valueType + * @return predefined size of a ValueType as int. + */ + public static int getLengthOfValueType(ValueType valueType) { + + int size; + + switch (valueType) { + case DOUBLE: + size = Const.VALUE_SIZE_DOUBLE; + break; + case FLOAT: + size = Const.VALUE_SIZE_DOUBLE; + break; + case INTEGER: + size = Const.VALUE_SIZE_INTEGER; + break; + case LONG: + size = Const.VALUE_SIZE_LONG; + break; + case SHORT: + size = Const.VALUE_SIZE_SHORT; + break; + case BYTE_ARRAY: + size = Const.VALUE_SIZE_MINIMAL; + break; + case STRING: + size = Const.VALUE_SIZE_MINIMAL; + break; + case BOOLEAN: + case BYTE: + default: + size = Const.VALUE_SIZE_MINIMAL; + break; + } + return size; + } + + /** + * Converts a byte array to an hexadecimal string + * + * @param byteArray + * @return hexadecimal string + */ + public static String byteArrayToHexString(byte[] byteArray) { + + char[] hexArray = "0123456789ABCDEF".toCharArray(); + char[] hexChars = new char[byteArray.length * 2]; + for (int j = 0; j < byteArray.length; j++) { + int v = byteArray[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + /** + * Constructs the timestamp for every log value into a StringBuilder. + * + * @param sb + * @param calendar + */ + public static void setLoggerTimestamps(StringBuilder sb, Calendar calendar) { + + double unixtimestamp_sec = calendar.getTimeInMillis() / 1000.0; // double for milliseconds, nanoseconds + + sb.append(String.format(Const.DATE_FORMAT, calendar)); + sb.append(Const.SEPARATOR); + sb.append(String.format(Const.TIME_FORMAT, calendar)); + sb.append(Const.SEPARATOR); + sb.append(String.format(Locale.ENGLISH, "%10.3f", unixtimestamp_sec)); + sb.append(Const.SEPARATOR); + } + + /** + * Constructs the timestamp for every log value into a StringBuilder. + * + * @param sb + * @param unixTimeStamp unix time stamp in ms + */ + public static void setLoggerTimestamps(StringBuilder sb, long unixTimeStamp) { + + Calendar calendar = new GregorianCalendar(Locale.getDefault()); + calendar.setTimeInMillis(unixTimeStamp); + double unixtimestamp_sec = unixTimeStamp / 1000.0; // double for milliseconds, nanoseconds + + sb.append(String.format(Const.DATE_FORMAT, calendar)); + sb.append(Const.SEPARATOR); + sb.append(String.format(Const.TIME_FORMAT, calendar)); + sb.append(Const.SEPARATOR); + sb.append(String.format(Locale.ENGLISH, "%10.3f", unixtimestamp_sec)); + sb.append(Const.SEPARATOR); + } + + public static String getHeaderFromFile(String filePath, String logIntervall_logTimeOffset) { + + BufferedReader br = LoggerUtils.getBufferedReader(new File(filePath)); + + if (br != null) { + StringBuilder sb = new StringBuilder(); + + try { + String line = br.readLine(); + + if (line != null) { + sb.append(line); + while (line != null && line.startsWith(Const.COMMENT_SIGN)) { + sb.append(Const.LINESEPARATOR); + line = br.readLine(); + sb.append(line); + } + } + } catch (IOException e) { + logger.error("Problems to handle file: " + filePath, e); + } finally { + + try { + br.close(); + } catch (IOException e) { + logger.error("Can not close file: " + filePath, e); + } + } + return sb.toString(); + } else { + return ""; + } + } + + /** + * Returns a RandomAccessFile of the specified file. + * + * @param filePath + * @param accsesMode + * @return the RandomAccessFile of the specified file + */ + public static RandomAccessFile getRandomAccessFile(File file, String accsesMode) { + + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(file, accsesMode); + } catch (FileNotFoundException e) { + + logger.warn("Requested logfile: '" + file.getAbsolutePath() + "' not found."); + // e.printStackTrace(); + } + return raf; + } + + public static BufferedReader getBufferedReader(File file) { + + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Const.CHAR_SET)); + } catch (IOException e) { + logger.error("Can not open file: " + file.getAbsolutePath()); + } + return reader; + } + + public static PrintWriter getPrintWriter(File file, boolean append) { + + PrintWriter writer = null; + try { + writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, append), Const.CHAR_SET)); + } catch (IOException e) { + logger.error("Can not open file: " + file.getAbsolutePath()); + } + return writer; + } + + public static void fillUpFileWithErrorCode(String directoryPath, String loggerIntervall_loggerTimeOffset, Calendar calendar) { + + String filename = buildFilename(loggerIntervall_loggerTimeOffset, calendar); + File file = new File(directoryPath + filename); + RandomAccessFile raf = LoggerUtils.getRandomAccessFile(file, "r"); + PrintWriter out = null; + + String firstLogLine = ""; + String lastLogLine = ""; + long loggingIntervall = 0; + + if (loggerIntervall_loggerTimeOffset.contains("_")) { + loggingIntervall = Long.parseLong(loggerIntervall_loggerTimeOffset.split("_")[0]); + } else { + loggingIntervall = Long.parseLong(loggerIntervall_loggerTimeOffset); + } + + // String restOfLastLine = ""; + long unixTimeStamp = 0; + + if (raf != null) { + try { + String line = raf.readLine(); + if (line != null) { + + while (line.startsWith(Const.COMMENT_SIGN)) { + // do nothing with this data, only for finding the begin of logging + line = raf.readLine(); + } + firstLogLine = raf.readLine(); + } + + // read last line backwards and read last line + byte[] byti = new byte[1]; + long filePosition = file.length() - 2; + String charString; + while (lastLogLine.isEmpty() && filePosition > 0) { + + raf.seek(filePosition); + int readedBytes = raf.read(byti); + if (readedBytes == 1) { + charString = new String(byti, Const.CHAR_SET); + + if (charString.equals(Const.LINESEPARATOR_STRING)) { + lastLogLine = raf.readLine(); + } else { + filePosition -= 1; + } + } else { + filePosition = -1; // leave the while loop + } + } + raf.close(); + + int firstLogLineLength = firstLogLine.length(); + + int lastLogLineLength = lastLogLine.length(); + + if (firstLogLineLength != lastLogLineLength) { + /** + * TODO: different size of logging lines, probably the last one is corrupted we have to fill it up + * restOfLastLine = completeLastLine(firstLogLine, lastLogLine); raf.writeChars(restOfLastLine); + */ + // File is corrupted rename to old + renameToOldFile(directoryPath, loggerIntervall_loggerTimeOffset, calendar); + } else { + + String lineArray[] = lastLogLine.split(Const.SEPARATOR); + + StringBuilder errorValues = getErrorValues(lineArray); + unixTimeStamp = ((long) Double.parseDouble(lineArray[2])) * 1000; + + // FileChannel fileChannel = raf.getChannel(); + out = getPrintWriter(file, true); + + long numberOfFillUpLines = getNumberOfFillUpLines(unixTimeStamp, loggingIntervall); + + while (numberOfFillUpLines > 0) { + + unixTimeStamp = fillUp(out, unixTimeStamp, loggingIntervall, lastLogLineLength, numberOfFillUpLines, errorValues); + numberOfFillUpLines = getNumberOfFillUpLines(unixTimeStamp, loggingIntervall); + } + out.close(); + } + } catch (IOException e) { + logger.error("Could not read file " + file.getAbsolutePath(), e); + renameToOldFile(directoryPath, loggerIntervall_loggerTimeOffset, calendar); + } finally { + try { + + if (raf != null) { + raf.close(); + } + if (out != null) { + out.close(); + } + } catch (IOException e) { + logger.error("Could not close file " + file.getAbsolutePath()); + } + } + } + } + + private static long fillUp(PrintWriter out, long unixTimeStamp, long loggingIntervall, int lastLogLineLength, long numberOfFillUpLines, StringBuilder errorValues) throws IOException { + + StringBuilder line = new StringBuilder(); + for (int i = 0; i < numberOfFillUpLines; i++) { + + line.setLength(0); + unixTimeStamp += loggingIntervall; + setLoggerTimestamps(line, unixTimeStamp); + line.append(errorValues); + line.append(Const.LINESEPARATOR); + + out.append(line.toString()); + } + + return unixTimeStamp; + } + + private static long getNumberOfFillUpLines(long lastUnixTimeStamp, long loggingIntervall) { + + long numberOfFillUpLines = 0; + long currentUnixTimeStamp = System.currentTimeMillis(); + + numberOfFillUpLines = (currentUnixTimeStamp - lastUnixTimeStamp) / loggingIntervall; + + return numberOfFillUpLines; + } + + /** + * @param errorValues has to be empty at begin + * @param logLine + * @return + */ + private static StringBuilder getErrorValues(String lineArray[]) { + + StringBuilder errorValues = new StringBuilder(); + int arrayLength = lineArray.length; + int errorCodeLength = Const.ERROR.length() + 2; + int separatorLength = Const.SEPARATOR.length(); + int length = 0; + + for (int i = 3; i < arrayLength; ++i) { + + length = lineArray[i].length(); + length -= errorCodeLength; + if (i > arrayLength - 1) { + length -= separatorLength; + } + appendSpaces(errorValues, length); + errorValues.append(Const.ERROR); + errorValues.append(Flag.DATA_LOGGING_NOT_ACTIVE.getCode()); + + if (i < arrayLength - 1) { + errorValues.append(Const.SEPARATOR); + } + } + return errorValues; + } + + // private static String completeLastLine(String firstLogLine, String lastLogLine) { + // + // // TODO different size of logging lines, probably the last one is corrupted we have to fill it up + // // TODO: wenn letzte Zeile zu defekt ist also ohne Timestamp, löschen und vorletzte Zeile nehmen und + // // dessen Zeit. + // int firstLogLineLength = firstLogLine.length(); + // int lastLogLineLength = lastLogLine.length(); + // + // return ""; + // } + + /** + * Get the length from a type+length tuple. Example: "Byte_String,95" + * + * @param string has to be a string with ByteType and length. + * @param dataFile the logger data file + * @return the length of a ByteString in int. + */ + private static int getByteStringLength(String string) { + + String stringArray[]; + int size; + + stringArray = string.split(Const.VALUETYPE_SIZE_SEPARATOR); + try { + size = Integer.parseInt(stringArray[1]); + } catch (NumberFormatException e) { + logger.warn("Not able to get ValueType length from String. Set length to minimal lenght " + Const.VALUE_SIZE_MINIMAL + "."); + size = Const.VALUE_SIZE_MINIMAL; + } + return size; + } + + private static void closeBufferdReader(BufferedReader br) { + + try { + br.close(); + } catch (Exception e1) { + } + } } diff --git a/projects/datalogger/ascii/src/main/resources/OSGI-INF/components.xml b/projects/datalogger/ascii/src/main/resources/OSGI-INF/components.xml index 6871774c..7aa3f11a 100644 --- a/projects/datalogger/ascii/src/main/resources/OSGI-INF/components.xml +++ b/projects/datalogger/ascii/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogChannelTestImpl.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogChannelTestImpl.java index 2ba08fdb..ce28bb7e 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogChannelTestImpl.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogChannelTestImpl.java @@ -25,71 +25,71 @@ public class LogChannelTestImpl implements LogChannel { - private final String id; - private final String description; - private final String unit; - private final ValueType valueType; - private final Integer loggingInterval; - private final Integer loggingTimeOffset; - private Integer valueLength; + private final String id; + private final String description; + private final String unit; + private final ValueType valueType; + private final Integer loggingInterval; + private final Integer loggingTimeOffset; + private Integer valueLength; - public LogChannelTestImpl(String id, String description, String unit, ValueType valueType, Integer loggingInterval, - Integer loggingTimeOffset) { + public LogChannelTestImpl(String id, String description, String unit, ValueType valueType, Integer loggingInterval, Integer + loggingTimeOffset) { - this.id = id; - this.description = description; - this.unit = unit; - this.valueType = valueType; - this.loggingInterval = loggingInterval; - this.loggingTimeOffset = loggingTimeOffset; - } + this.id = id; + this.description = description; + this.unit = unit; + this.valueType = valueType; + this.loggingInterval = loggingInterval; + this.loggingTimeOffset = loggingTimeOffset; + } - public LogChannelTestImpl(String id, String description, String unit, ValueType valueType, Integer loggingInterval, - Integer loggingTimeOffset, int valueLength) { + public LogChannelTestImpl(String id, String description, String unit, ValueType valueType, Integer loggingInterval, Integer + loggingTimeOffset, int valueLength) { - this(id, description, unit, valueType, loggingInterval, loggingTimeOffset); - this.valueLength = valueLength; - } + this(id, description, unit, valueType, loggingInterval, loggingTimeOffset); + this.valueLength = valueLength; + } - @Override - public String getId() { + @Override + public String getId() { - return id; - } + return id; + } - @Override - public String getDescription() { + @Override + public String getDescription() { - return description; - } + return description; + } - @Override - public String getUnit() { + @Override + public String getUnit() { - return unit; - } + return unit; + } - @Override - public ValueType getValueType() { + @Override + public ValueType getValueType() { - return valueType; - } + return valueType; + } - @Override - public Integer getValueTypeLength() { + @Override + public Integer getValueTypeLength() { - return valueLength; - } + return valueLength; + } - @Override - public Integer getLoggingInterval() { + @Override + public Integer getLoggingInterval() { - return loggingInterval; - } + return loggingInterval; + } - @Override - public Integer getLoggingTimeOffset() { + @Override + public Integer getLoggingTimeOffset() { - return loggingTimeOffset; - } + return loggingTimeOffset; + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestBrokenFile.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestBrokenFile.java index 8a784df7..546c39e6 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestBrokenFile.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestBrokenFile.java @@ -20,114 +20,113 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import static org.junit.Assert.assertTrue; - -import java.util.List; - import org.junit.Test; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.datalogger.ascii.LogFileReader; +import java.util.List; + +import static org.junit.Assert.assertTrue; + public class LogFileReaderTestBrokenFile { - private String fileDate; - - String dateFormat = "yyyyMMdd HH:mm:ss"; - private final static int loggingInterval = 1000; // ms - static int loggingTimeOffset = 0; // ms - private final static String Channel0Name = "power"; - - LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); - - @Test - public void tc200_logfile_does_not_exist() { - - fileDate = "20131201"; - - long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 0; - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - - if (records.size() == expectedRecords) { - assertTrue(true); - } - else { - assertTrue(false); - } - - } - - // @Ignore - // @Test - // public void tc201_no_header_in_logfile() { - // - // fileDate = "20131202"; - // - // String ext = ".dat"; - // long startTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); - // long endTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:30").getTime(); - // String[] channelIds = new String[] { "power", "energy" }; - // - // String filename = TestUtils.TESTFOLDER + "/" + fileDate + "_" + loggingInterval + ext; - // createLogFileWithoutHeader(filename, channelIds, startTimestampFile, endTimestampFile, loggingInterval); - // - // long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); - // long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); - // - // LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - // List records = fr.getValues(t1, t2); - // - // long expectedRecords = 0; - // System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - // System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - // - // if (records.size() == expectedRecords) { - // assertTrue(true); - // } - // else { - // assertTrue(false); - // } - // - // } - - // @Ignore - // @Test - // public void tc202_channelId_not_in_header() { - // - // fileDate = "20131202"; - // - // String ext = ".dat"; - // long startTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); - // long endTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:30").getTime(); - // String[] channelIds = new String[] { "energy" }; - // - // String filename = TestUtils.TESTFOLDER + "/" + fileDate + "_" + loggingInterval + ext; - // createLogFile(filename, channelIds, startTimestampFile, endTimestampFile, loggingInterval); - // - // long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); - // long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); - // - // LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - // List records = fr.getValues(t1, t2); - // - // long expectedRecords = 0; - // System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - // System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - // - // if (records.size() == expectedRecords) { - // assertTrue(true); - // } - // else { - // assertTrue(false); - // } - // } + private String fileDate; + + String dateFormat = "yyyyMMdd HH:mm:ss"; + private final static int loggingInterval = 1000; // ms + static int loggingTimeOffset = 0; // ms + private final static String Channel0Name = "power"; + + LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); + + @Test + public void tc200_logfile_does_not_exist() { + + fileDate = "20131201"; + + long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 0; + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + + if (records.size() == expectedRecords) { + assertTrue(true); + } else { + assertTrue(false); + } + + } + + // @Ignore + // @Test + // public void tc201_no_header_in_logfile() { + // + // fileDate = "20131202"; + // + // String ext = ".dat"; + // long startTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); + // long endTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:30").getTime(); + // String[] channelIds = new String[] { "power", "energy" }; + // + // String filename = TestUtils.TESTFOLDER + "/" + fileDate + "_" + loggingInterval + ext; + // createLogFileWithoutHeader(filename, channelIds, startTimestampFile, endTimestampFile, loggingInterval); + // + // long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); + // long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); + // + // LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + // List records = fr.getValues(t1, t2); + // + // long expectedRecords = 0; + // System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + // System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + // + // if (records.size() == expectedRecords) { + // assertTrue(true); + // } + // else { + // assertTrue(false); + // } + // + // } + + // @Ignore + // @Test + // public void tc202_channelId_not_in_header() { + // + // fileDate = "20131202"; + // + // String ext = ".dat"; + // long startTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); + // long endTimestampFile = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:30").getTime(); + // String[] channelIds = new String[] { "energy" }; + // + // String filename = TestUtils.TESTFOLDER + "/" + fileDate + "_" + loggingInterval + ext; + // createLogFile(filename, channelIds, startTimestampFile, endTimestampFile, loggingInterval); + // + // long t1 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:00").getTime(); + // long t2 = TestUtils.stringToDate(dateFormat, fileDate + " 12:00:10").getTime(); + // + // LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + // List records = fr.getValues(t1, t2); + // + // long expectedRecords = 0; + // System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + // System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + // + // if (records.size() == expectedRecords) { + // assertTrue(true); + // } + // else { + // assertTrue(false); + // } + // } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestMultipleFiles.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestMultipleFiles.java index 9e6625df..5c69adee 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestMultipleFiles.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestMultipleFiles.java @@ -20,15 +20,6 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -42,117 +33,120 @@ import org.openmuc.framework.datalogger.spi.LogChannel; import org.openmuc.framework.datalogger.spi.LogRecordContainer; +import java.io.File; +import java.util.*; + +import static org.junit.Assert.assertTrue; + public class LogFileReaderTestMultipleFiles { - // t1 = start timestamp of requestet interval - // t2 = end timestamp of requestet interval + // t1 = start timestamp of requestet interval + // t2 = end timestamp of requestet interval - private static String fileDate0 = "20770707"; - private static String fileDate1 = "20770708"; - private static String fileDate2 = "20770709"; - private static int loggingInterval = 60000; // ms; - static int loggingTimeOffset = 0; // ms - private final static String Channel0Name = "power"; - private final static String EXT = ".dat"; - // private static String[] channelIds = new String[] { Channel0Name }; - private static String dateFormat = "yyyyMMdd HH:mm:ss"; - // private static String ext = ".dat"; + private static String fileDate0 = "20770707"; + private static String fileDate1 = "20770708"; + private static String fileDate2 = "20770709"; + private static int loggingInterval = 60000; // ms; + static int loggingTimeOffset = 0; // ms + private final static String Channel0Name = "power"; + private final static String EXT = ".dat"; + // private static String[] channelIds = new String[] { Channel0Name }; + private static String dateFormat = "yyyyMMdd HH:mm:ss"; + // private static String ext = ".dat"; - LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); + LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); - @BeforeClass - public static void setup() { + @BeforeClass + public static void setup() { - TestSuite.createTestFolder(); + TestSuite.createTestFolder(); - // drei Dateien + // drei Dateien - // 1 Kanal im Sekunden-Takt loggen über von 23 Uhr bis 1 Uhr des übernächsten Tages - // --> Ergebnis müssten drei - // Dateien sein die vom LogFileWriter erstellt wurden + // 1 Kanal im Sekunden-Takt loggen über von 23 Uhr bis 1 Uhr des übernächsten Tages + // --> Ergebnis müssten drei + // Dateien sein die vom LogFileWriter erstellt wurden - String filename0 = TestUtils.TESTFOLDERPATH + fileDate0 + "_" + loggingInterval + EXT; - String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + EXT; - String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + EXT; + String filename0 = TestUtils.TESTFOLDERPATH + fileDate0 + "_" + loggingInterval + EXT; + String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + EXT; + String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + EXT; - File file0 = new File(filename0); - File file1 = new File(filename1); - File file2 = new File(filename2); + File file0 = new File(filename0); + File file1 = new File(filename1); + File file2 = new File(filename2); - if (file0.exists()) { - System.out.println("Delete File " + filename2); - file0.delete(); - } - if (file1.exists()) { - System.out.println("Delete File " + filename1); - file1.delete(); - } - if (file2.exists()) { - System.out.println("Delete File " + filename2); - file2.delete(); - } + if (file0.exists()) { + System.out.println("Delete File " + filename2); + file0.delete(); + } + if (file1.exists()) { + System.out.println("Delete File " + filename1); + file1.delete(); + } + if (file2.exists()) { + System.out.println("Delete File " + filename2); + file2.delete(); + } - HashMap logChannelList = new HashMap(); + HashMap logChannelList = new HashMap(); - LogChannelTestImpl ch0 = new LogChannelTestImpl("power", "dummy description", "kW", ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); + LogChannelTestImpl ch0 = new LogChannelTestImpl("power", "dummy description", "kW", ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); - logChannelList.put(Channel0Name, ch0); + logChannelList.put(Channel0Name, ch0); - Date date = TestUtils.stringToDate(dateFormat, fileDate0 + " 23:00:00"); - Calendar calendar = new GregorianCalendar(); - calendar.setTime(date); + Date date = TestUtils.stringToDate(dateFormat, fileDate0 + " 23:00:00"); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); - int hour = 3600; + int hour = 3600; - for (int i = 0; i < ((hour * 24 + hour * 2) * (1000d / loggingInterval)); i++) { + for (int i = 0; i < ((hour * 24 + hour * 2) * (1000d / loggingInterval)); i++) { - LogRecordContainer container1 = new LogRecordContainerImpl(Channel0Name, new Record(new DoubleValue(1), - date.getTime())); + LogRecordContainer container1 = new LogRecordContainerImpl(Channel0Name, new Record(new DoubleValue(1), date.getTime())); - LogIntervalContainerGroup group = new LogIntervalContainerGroup(); - group.add(container1); + LogIntervalContainerGroup group = new LogIntervalContainerGroup(); + group.add(container1); - LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); - lfw.log(group, loggingInterval, 0, date, logChannelList); + LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); + lfw.log(group, loggingInterval, 0, date, logChannelList); - calendar.add(Calendar.MILLISECOND, loggingInterval); - date = calendar.getTime(); + calendar.add(Calendar.MILLISECOND, loggingInterval); + date = calendar.getTime(); - } - // } - } + } + // } + } - @AfterClass - public static void tearDown() { - System.out.println("tearing down"); - TestSuite.deleteTestFolder(); - } + @AfterClass + public static void tearDown() { + System.out.println("tearing down"); + TestSuite.deleteTestFolder(); + } - @Test - public void tc009_t1_t2_within_available_data_with_three_files() { + @Test + public void tc009_t1_t2_within_available_data_with_three_files() { - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 23:00:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate2 + " 00:59:" + (60 - loggingInterval / 1000)).getTime(); + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 23:00:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate2 + " 00:59:" + (60 - loggingInterval / 1000)).getTime(); - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); - int hour = 3600; - long expectedRecords = (hour * 24 + hour * 2) / (loggingInterval / 1000); - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + int hour = 3600; + long expectedRecords = (hour * 24 + hour * 2) / (loggingInterval / 1000); + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - boolean result; + boolean result; - if (records.size() == expectedRecords) { - result = true; - } - else { - result = false; - } - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected); "); - assertTrue(result); - } + if (records.size() == expectedRecords) { + result = true; + } else { + result = false; + } + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected); "); + assertTrue(result); + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestSingleFile.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestSingleFile.java index 6e6cf0d9..63eda638 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestSingleFile.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileReaderTestSingleFile.java @@ -20,14 +20,6 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -42,252 +34,247 @@ import org.openmuc.framework.datalogger.spi.LogChannel; import org.openmuc.framework.datalogger.spi.LogRecordContainer; +import java.util.*; + +import static org.junit.Assert.assertTrue; + public class LogFileReaderTestSingleFile { - // t1 = start timestamp of requested interval - // t2 = end timestamp of requested interval + // t1 = start timestamp of requested interval + // t2 = end timestamp of requested interval + + static String fileDate0 = "20660606"; + static int loggingInterval = 10000; // ms + static int loggingTimeOffset = 0; // ms + static String ext = ".dat"; + static long startTimestampFile; + static long endTimestampFile; + static String Channel0Name = "power"; + static String[] channelIds = {Channel0Name}; + static String dateFormat = "yyyyMMdd HH:mm:ss"; + + LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); + + @BeforeClass + public static void setup() { + + TestSuite.createTestFolder(); - static String fileDate0 = "20660606"; - static int loggingInterval = 10000; // ms - static int loggingTimeOffset = 0; // ms - static String ext = ".dat"; - static long startTimestampFile; - static long endTimestampFile; - static String Channel0Name = "power"; - static String[] channelIds = { Channel0Name }; - static String dateFormat = "yyyyMMdd HH:mm:ss"; + // File file = new File(TestUtils.TESTFOLDERPATH + fileDate0 + "_" + loggingInterval + ext); - LogChannelTestImpl channelTestImpl = new LogChannelTestImpl(Channel0Name, "Comment", "W", ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); + // if (file.exists()) { + // Do nothing, file exists. + // } + // else { + // eine Datei + channelIds = new String[]{"power"}; - @BeforeClass - public static void setup() { + // Logs 1 channel in second interval from 1 to 3 o'clock + + HashMap logChannelList = new HashMap(); - TestSuite.createTestFolder(); + LogChannelTestImpl ch1 = new LogChannelTestImpl(Channel0Name, "dummy description", "kW", ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); - // File file = new File(TestUtils.TESTFOLDERPATH + fileDate0 + "_" + loggingInterval + ext); + logChannelList.put(Channel0Name, ch1); + + Date date = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:00:00"); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + + for (int i = 0; i < ((60 * 60 * 2) * (1000d / loggingInterval)); i++) { - // if (file.exists()) { - // Do nothing, file exists. - // } - // else { - // eine Datei - channelIds = new String[] { "power" }; - - // Logs 1 channel in second interval from 1 to 3 o'clock - - HashMap logChannelList = new HashMap(); - - LogChannelTestImpl ch1 = new LogChannelTestImpl(Channel0Name, "dummy description", "kW", ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); - - logChannelList.put(Channel0Name, ch1); - - Date date = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:00:00"); - Calendar calendar = new GregorianCalendar(); - calendar.setTime(date); - - for (int i = 0; i < ((60 * 60 * 2) * (1000d / loggingInterval)); i++) { - - LogRecordContainer container1 = new LogRecordContainerImpl(Channel0Name, new Record(new DoubleValue(i), - date.getTime())); - - LogIntervalContainerGroup group = new LogIntervalContainerGroup(); - group.add(container1); - - LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); - lfw.log(group, loggingInterval, 0, date, logChannelList); - - calendar.add(Calendar.MILLISECOND, loggingInterval); - date = calendar.getTime(); - } - // } - } - - @AfterClass - public static void tearDown() { - System.out.println("tearing down"); - TestSuite.deleteTestFolder(); - } - - @Test - public void tc000_t1_t2_within_available_data() { - - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:50:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:51:00").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 7; - boolean result; - if (records.size() == expectedRecords) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - assertTrue(result); - } - - @Test - public void tc001_t1_before_available_data_t2_within() { - - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:10").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 0; - boolean result; - - if (records.size() == expectedRecords) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - assertTrue(result); - } - - @Test - public void tc002_t2_after_available_data() { - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:00:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 02:00:00").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 361; // - - boolean result; - if (records.size() == expectedRecords) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - assertTrue(result); - } - - @Test - public void tc003_t1_t2_before_available_data() { - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:00").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:59:59").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 0; - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - - boolean result = true; - int wrong = 0; - int ok = 0; - - for (int i = 0; records.size() > i; i++) { - if (records.get(i).getFlag().equals(Flag.NO_VALUE_RECEIVED_YET)) { - ++ok; - } - else { - ++wrong; - result = false; - } - } - System.out.print(" records = " + records.size() + " (" + expectedRecords + " expected); "); - System.out.println("wrong = " + wrong + ", ok(with Flag 7) = " + ok); - assertTrue(result); - } - - @Test - public void tc004_t1_t2_after_available_data() { - // test 5 - startTimestampRequest & endTimestampRequest after available logged data - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 03:00:01").getTime(); - long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 03:59:59").getTime(); - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - List records = fr.getValues(t1, t2); - - long expectedRecords = 0; - - boolean result; - if (records.size() == expectedRecords) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); - assertTrue(result); - } - - @Test - public void tc005_t1_within_available_data() { - - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:11:10").getTime(); - boolean result; - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - Record record = fr.getValue(t1); - - if (record != null) { - result = true; - - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" record = " + result + "record = "); - assertTrue(result); - } - - @Test - public void tc006_t1_before_available_data() { - - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:59:00").getTime(); - boolean result; - - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - Record record = fr.getValue(t1); - - if (record == null) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" no records = " + result); - assertTrue(result); - } - - // @Test - public void tc007_t1_within_available_data_with_loggingInterval() { - - boolean result; - long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 02:59:59").getTime(); - // get value looks from 02:59:59 to 3:00:00. before 3:00:00 a value exists - LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); - - Record record = fr.getValue(t1); - - if (record != null) { - result = true; - } - else { - result = false; - } - System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(" record = " + result); - assertTrue(result); - } + LogRecordContainer container1 = new LogRecordContainerImpl(Channel0Name, new Record(new DoubleValue(i), date.getTime())); + + LogIntervalContainerGroup group = new LogIntervalContainerGroup(); + group.add(container1); + + LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); + lfw.log(group, loggingInterval, 0, date, logChannelList); + + calendar.add(Calendar.MILLISECOND, loggingInterval); + date = calendar.getTime(); + } + // } + } + + @AfterClass + public static void tearDown() { + System.out.println("tearing down"); + TestSuite.deleteTestFolder(); + } + + @Test + public void tc000_t1_t2_within_available_data() { + + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:50:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:51:00").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 7; + boolean result; + if (records.size() == expectedRecords) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + assertTrue(result); + } + + @Test + public void tc001_t1_before_available_data_t2_within() { + + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:10").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 0; + boolean result; + + if (records.size() == expectedRecords) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + assertTrue(result); + } + + @Test + public void tc002_t2_after_available_data() { + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:00:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 02:00:00").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 361; // + + boolean result; + if (records.size() == expectedRecords) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + assertTrue(result); + } + + @Test + public void tc003_t1_t2_before_available_data() { + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:00:00").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:59:59").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 0; + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + + boolean result = true; + int wrong = 0; + int ok = 0; + + for (int i = 0; records.size() > i; i++) { + if (records.get(i).getFlag().equals(Flag.NO_VALUE_RECEIVED_YET)) { + ++ok; + } else { + ++wrong; + result = false; + } + } + System.out.print(" records = " + records.size() + " (" + expectedRecords + " expected); "); + System.out.println("wrong = " + wrong + ", ok(with Flag 7) = " + ok); + assertTrue(result); + } + + @Test + public void tc004_t1_t2_after_available_data() { + // test 5 - startTimestampRequest & endTimestampRequest after available logged data + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 03:00:01").getTime(); + long t2 = TestUtils.stringToDate(dateFormat, fileDate0 + " 03:59:59").getTime(); + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + List records = fr.getValues(t1, t2); + + long expectedRecords = 0; + + boolean result; + if (records.size() == expectedRecords) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" records = " + records.size() + " (" + expectedRecords + " expected)"); + assertTrue(result); + } + + @Test + public void tc005_t1_within_available_data() { + + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 01:11:10").getTime(); + boolean result; + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + Record record = fr.getValue(t1); + + if (record != null) { + result = true; + + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" record = " + result + "record = "); + assertTrue(result); + } + + @Test + public void tc006_t1_before_available_data() { + + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 00:59:00").getTime(); + boolean result; + + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + Record record = fr.getValue(t1); + + if (record == null) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" no records = " + result); + assertTrue(result); + } + + // @Test + public void tc007_t1_within_available_data_with_loggingInterval() { + + boolean result; + long t1 = TestUtils.stringToDate(dateFormat, fileDate0 + " 02:59:59").getTime(); + // get value looks from 02:59:59 to 3:00:00. before 3:00:00 a value exists + LogFileReader fr = new LogFileReader(TestUtils.TESTFOLDERPATH, channelTestImpl); + + Record record = fr.getValue(t1); + + if (record != null) { + result = true; + } else { + result = false; + } + System.out.print(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(" record = " + result); + assertTrue(result); + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileWriterTest.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileWriterTest.java index d5d79689..3cc8b295 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileWriterTest.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/LogFileWriterTest.java @@ -20,209 +20,191 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openmuc.framework.core.datamanager.LogRecordContainerImpl; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.ValueType; +import org.openmuc.framework.data.*; import org.openmuc.framework.datalogger.ascii.LogFileWriter; import org.openmuc.framework.datalogger.ascii.LogIntervalContainerGroup; import org.openmuc.framework.datalogger.ascii.utils.Const; import org.openmuc.framework.datalogger.spi.LogChannel; import org.openmuc.framework.datalogger.spi.LogRecordContainer; +import java.io.File; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; + +import static org.junit.Assert.assertTrue; + public class LogFileWriterTest { - // t1 = start timestamp of requestet interval - // t2 = end timestamp of requestet interval - - static int loggingInterval = 10000; // ms; - static int loggingTimeOffset = 0; // ms; - static String ext = ".dat"; - - static String dateFormat = "yyyyMMdd HH:mm:s"; - static String fileDate1 = "20880808"; - static String fileDate2 = "20880809"; - - static String ch01 = "FLOAT"; - static String ch02 = "DOUBLE"; - static String ch03 = "BOOLEAN"; - static String ch04 = "SHORT"; - static String ch05 = "INTEGER"; - static String ch06 = "LONG"; - static String ch07 = "BYTE"; - static String ch08 = "STRING"; - static String ch09 = "BYTE_ARRAY"; - static String dummy = "dummy"; - static String[] channelIds = new String[] { ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09 }; - static String time = " 23:55:00"; - static String testStringValueIncorrectASCII = "qwertzuiopü+asdfghjklöä#YXCVBNM;:_"; // 94 - // Zeichen - static String testStringValueCorrect = "qwertzuiop+asdfghjkl#YXCVBNM;:_"; - static String testStringValueIncorrect = "qwertzuiop+asdfghjkl#YXCVBNM;:_"; - static byte[] testByteArray = { 1, 2, 3, 4, -5, -9, 0 }; - - static int valueLength = 100; - static int valueLengthByteArray = testByteArray.length; - - @BeforeClass - public static void setup() { - - TestSuite.createTestFolder(); - - // 2 Kanäle im Stunden-Takt loggen über von 12 Uhr bis 12 Uhr des nächsten Tages - // --> Ergebnis müssten zwei Dateien sein die vom LogFileWriter erstellt wurden - - String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + ext; - String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + ext; - - File file1 = new File(filename1); - File file2 = new File(filename2); - - if (file1.exists()) { - System.out.println("Delete File " + filename1); - file1.delete(); - } - if (file2.exists()) { - System.out.println("Delete File " + filename2); - file2.delete(); - } - - HashMap logChannelList = new HashMap(); - - LogChannelTestImpl ch1 = new LogChannelTestImpl(ch01, "dummy description", dummy, ValueType.FLOAT, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch2 = new LogChannelTestImpl(ch02, "dummy description", dummy, ValueType.DOUBLE, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch3 = new LogChannelTestImpl(ch03, "dummy description", dummy, ValueType.BOOLEAN, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch4 = new LogChannelTestImpl(ch04, "dummy description", dummy, ValueType.SHORT, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch5 = new LogChannelTestImpl(ch05, "dummy description", dummy, ValueType.INTEGER, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch6 = new LogChannelTestImpl(ch06, "dummy description", dummy, ValueType.LONG, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch7 = new LogChannelTestImpl(ch07, "dummy description", dummy, ValueType.BYTE, - loggingInterval, loggingTimeOffset); - LogChannelTestImpl ch8 = new LogChannelTestImpl(ch08, "dummy description", dummy, ValueType.STRING, - loggingInterval, loggingTimeOffset, valueLength); - LogChannelTestImpl ch9 = new LogChannelTestImpl(ch09, "dummy description", dummy, ValueType.BYTE_ARRAY, - loggingInterval, loggingTimeOffset, valueLengthByteArray); - - logChannelList.put(ch01, ch1); - logChannelList.put(ch02, ch2); - logChannelList.put(ch03, ch3); - logChannelList.put(ch04, ch4); - logChannelList.put(ch05, ch5); - logChannelList.put(ch06, ch6); - logChannelList.put(ch07, ch7); - logChannelList.put(ch08, ch8); - logChannelList.put(ch09, ch9); - - Date date = TestUtils.stringToDate(dateFormat, fileDate1 + time); - Calendar calendar = new GregorianCalendar(); - calendar.setTime(date); - long time = date.getTime(); - boolean boolValue; - byte byteValue = 0; - - String testString; - - // writes 24 records for 2 channels from 12 o'clock till 12 o'clock of the other day - for (long i = 0; i < ((60 * 10) * (1000d / loggingInterval)); i++) { - - if ((i % 2) > 0) { - boolValue = true; - testString = testStringValueCorrect; - } - else { - boolValue = false; - testString = testStringValueIncorrect; - } - // System.out.println("TEST = " + (i+0.555F)); - LogRecordContainer container1 = new LogRecordContainerImpl(ch01, new Record( - new FloatValue(i * -7 - 0.555F), time)); - LogRecordContainer container2 = new LogRecordContainerImpl(ch02, new Record( - new DoubleValue(i * +7 - 0.555), time)); - LogRecordContainer container3 = new LogRecordContainerImpl(ch03, new Record(new BooleanValue(boolValue), - time)); - LogRecordContainer container4 = new LogRecordContainerImpl(ch04, - new Record(new ShortValue((short) i), time)); - LogRecordContainer container5 = new LogRecordContainerImpl(ch05, new Record(new IntValue((int) i), time)); - LogRecordContainer container6 = new LogRecordContainerImpl(ch06, new Record(new LongValue(i * 1000000), - time)); - LogRecordContainer container7 = new LogRecordContainerImpl(ch07, new Record(new ByteValue(byteValue), time)); - LogRecordContainer container8 = new LogRecordContainerImpl(ch08, new Record(new StringValue(testString), - time)); - LogRecordContainer container9 = new LogRecordContainerImpl(ch09, new Record(new ByteArrayValue( - testByteArray), time)); - - LogIntervalContainerGroup group = new LogIntervalContainerGroup(); - group.add(container1); - group.add(container2); - group.add(container3); - group.add(container4); - group.add(container5); - group.add(container6); - group.add(container7); - group.add(container8); - group.add(container9); - - LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); - lfw.log(group, loggingInterval, loggingTimeOffset, date, logChannelList); - - calendar.add(Calendar.MILLISECOND, loggingInterval); - date = calendar.getTime(); - - ++byteValue; - } - } - - @AfterClass - public static void tearDown() { - System.out.println("tearing down"); - TestSuite.deleteTestFolder(); - } - - @Test - public void tc300_check_if_new_file_is_created_on_day_change() { - - String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + ext; - String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + ext; - - File file1 = new File(filename1); - File file2 = new File(filename2); - - Boolean assertT; - if (file1.exists() && file2.exists()) { - assertT = true; - } - else { - assertT = false; - } - System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); - System.out.println(file1.getAbsolutePath()); - System.out.println(file2.getAbsolutePath() + "\nTwo files created = " + assertT); - - assertTrue(assertT); - } + // t1 = start timestamp of requestet interval + // t2 = end timestamp of requestet interval + + static int loggingInterval = 10000; // ms; + static int loggingTimeOffset = 0; // ms; + static String ext = ".dat"; + + static String dateFormat = "yyyyMMdd HH:mm:s"; + static String fileDate1 = "20880808"; + static String fileDate2 = "20880809"; + + static String ch01 = "FLOAT"; + static String ch02 = "DOUBLE"; + static String ch03 = "BOOLEAN"; + static String ch04 = "SHORT"; + static String ch05 = "INTEGER"; + static String ch06 = "LONG"; + static String ch07 = "BYTE"; + static String ch08 = "STRING"; + static String ch09 = "BYTE_ARRAY"; + static String dummy = "dummy"; + static String[] channelIds = new String[]{ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09}; + static String time = " 23:55:00"; + static String testStringValueIncorrectASCII = "qwertzuiopü+asdfghjklöä#YXCVBNM;:_"; // 94 + // Zeichen + static String testStringValueCorrect = "qwertzuiop+asdfghjkl#YXCVBNM;:_"; + static String testStringValueIncorrect = "qwertzuiop+asdfghjkl#YXCVBNM;:_"; + static byte[] testByteArray = {1, 2, 3, 4, -5, -9, 0}; + + static int valueLength = 100; + static int valueLengthByteArray = testByteArray.length; + + @BeforeClass + public static void setup() { + + TestSuite.createTestFolder(); + + // 2 Kanäle im Stunden-Takt loggen über von 12 Uhr bis 12 Uhr des nächsten Tages + // --> Ergebnis müssten zwei Dateien sein die vom LogFileWriter erstellt wurden + + String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + ext; + String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + ext; + + File file1 = new File(filename1); + File file2 = new File(filename2); + + if (file1.exists()) { + System.out.println("Delete File " + filename1); + file1.delete(); + } + if (file2.exists()) { + System.out.println("Delete File " + filename2); + file2.delete(); + } + + HashMap logChannelList = new HashMap(); + + LogChannelTestImpl ch1 = new LogChannelTestImpl(ch01, "dummy description", dummy, ValueType.FLOAT, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch2 = new LogChannelTestImpl(ch02, "dummy description", dummy, ValueType.DOUBLE, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch3 = new LogChannelTestImpl(ch03, "dummy description", dummy, ValueType.BOOLEAN, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch4 = new LogChannelTestImpl(ch04, "dummy description", dummy, ValueType.SHORT, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch5 = new LogChannelTestImpl(ch05, "dummy description", dummy, ValueType.INTEGER, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch6 = new LogChannelTestImpl(ch06, "dummy description", dummy, ValueType.LONG, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch7 = new LogChannelTestImpl(ch07, "dummy description", dummy, ValueType.BYTE, loggingInterval, + loggingTimeOffset); + LogChannelTestImpl ch8 = new LogChannelTestImpl(ch08, "dummy description", dummy, ValueType.STRING, loggingInterval, + loggingTimeOffset, valueLength); + LogChannelTestImpl ch9 = new LogChannelTestImpl(ch09, "dummy description", dummy, ValueType.BYTE_ARRAY, loggingInterval, + loggingTimeOffset, valueLengthByteArray); + + logChannelList.put(ch01, ch1); + logChannelList.put(ch02, ch2); + logChannelList.put(ch03, ch3); + logChannelList.put(ch04, ch4); + logChannelList.put(ch05, ch5); + logChannelList.put(ch06, ch6); + logChannelList.put(ch07, ch7); + logChannelList.put(ch08, ch8); + logChannelList.put(ch09, ch9); + + Date date = TestUtils.stringToDate(dateFormat, fileDate1 + time); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + long time = date.getTime(); + boolean boolValue; + byte byteValue = 0; + + String testString; + + // writes 24 records for 2 channels from 12 o'clock till 12 o'clock of the other day + for (long i = 0; i < ((60 * 10) * (1000d / loggingInterval)); i++) { + + if ((i % 2) > 0) { + boolValue = true; + testString = testStringValueCorrect; + } else { + boolValue = false; + testString = testStringValueIncorrect; + } + // System.out.println("TEST = " + (i+0.555F)); + LogRecordContainer container1 = new LogRecordContainerImpl(ch01, new Record(new FloatValue(i * -7 - 0.555F), time)); + LogRecordContainer container2 = new LogRecordContainerImpl(ch02, new Record(new DoubleValue(i * +7 - 0.555), time)); + LogRecordContainer container3 = new LogRecordContainerImpl(ch03, new Record(new BooleanValue(boolValue), time)); + LogRecordContainer container4 = new LogRecordContainerImpl(ch04, new Record(new ShortValue((short) i), time)); + LogRecordContainer container5 = new LogRecordContainerImpl(ch05, new Record(new IntValue((int) i), time)); + LogRecordContainer container6 = new LogRecordContainerImpl(ch06, new Record(new LongValue(i * 1000000), time)); + LogRecordContainer container7 = new LogRecordContainerImpl(ch07, new Record(new ByteValue(byteValue), time)); + LogRecordContainer container8 = new LogRecordContainerImpl(ch08, new Record(new StringValue(testString), time)); + LogRecordContainer container9 = new LogRecordContainerImpl(ch09, new Record(new ByteArrayValue(testByteArray), time)); + + LogIntervalContainerGroup group = new LogIntervalContainerGroup(); + group.add(container1); + group.add(container2); + group.add(container3); + group.add(container4); + group.add(container5); + group.add(container6); + group.add(container7); + group.add(container8); + group.add(container9); + + LogFileWriter lfw = new LogFileWriter(TestUtils.TESTFOLDERPATH); + lfw.log(group, loggingInterval, loggingTimeOffset, date, logChannelList); + + calendar.add(Calendar.MILLISECOND, loggingInterval); + date = calendar.getTime(); + + ++byteValue; + } + } + + @AfterClass + public static void tearDown() { + System.out.println("tearing down"); + TestSuite.deleteTestFolder(); + } + + @Test + public void tc300_check_if_new_file_is_created_on_day_change() { + + String filename1 = TestUtils.TESTFOLDERPATH + fileDate1 + "_" + loggingInterval + ext; + String filename2 = TestUtils.TESTFOLDERPATH + fileDate2 + "_" + loggingInterval + ext; + + File file1 = new File(filename1); + File file2 = new File(filename2); + + Boolean assertT; + if (file1.exists() && file2.exists()) { + assertT = true; + } else { + assertT = false; + } + System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); + System.out.println(file1.getAbsolutePath()); + System.out.println(file2.getAbsolutePath() + "\nTwo files created = " + assertT); + + assertTrue(assertT); + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/MiscTests.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/MiscTests.java index 4e74b90d..f0f5a8ac 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/MiscTests.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/MiscTests.java @@ -20,100 +20,100 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import java.util.Iterator; -import java.util.TreeMap; - import org.junit.Assert; import org.junit.Test; import org.openmuc.framework.datalogger.ascii.exceptions.WrongScalingException; import org.openmuc.framework.datalogger.ascii.utils.Const; import org.openmuc.framework.datalogger.ascii.utils.IESDataFormatUtils; +import java.util.Iterator; +import java.util.TreeMap; + public class MiscTests { - @Test - public void testDoubleFormattingOk() { + @Test + public void testDoubleFormattingOk() { - TreeMap testData = new TreeMap(); + TreeMap testData = new TreeMap(); - testData.put(-0.0, "+0.000"); // should be + - testData.put(0.0, "+0.000"); + testData.put(-0.0, "+0.000"); // should be + + testData.put(0.0, "+0.000"); - testData.put(1.0, "+1.000"); - testData.put(-1.0, "-1.000"); + testData.put(1.0, "+1.000"); + testData.put(-1.0, "-1.000"); - testData.put(10.0, "+10.000"); - testData.put(-10.0, "-10.000"); + testData.put(10.0, "+10.000"); + testData.put(-10.0, "-10.000"); - testData.put(10.123, "+10.123"); - testData.put(-10.123, "-10.123"); + testData.put(10.123, "+10.123"); + testData.put(-10.123, "-10.123"); - testData.put(9999.999, "+9999.999"); - testData.put(-9999.999, "-9999.999"); + testData.put(9999.999, "+9999.999"); + testData.put(-9999.999, "-9999.999"); - // decimal digits = 3 - testData.put(1000.123, "+1000.123"); - testData.put(-1000.123, "-1000.123"); + // decimal digits = 3 + testData.put(1000.123, "+1000.123"); + testData.put(-1000.123, "-1000.123"); - // decimal digits = 2 - testData.put(10000.123, "+10000.12"); - testData.put(-10000.123, "-10000.12"); + // decimal digits = 2 + testData.put(10000.123, "+10000.12"); + testData.put(-10000.123, "-10000.12"); - // decimal digits = 1 - testData.put(100000.123, "+100000.1"); - testData.put(-100000.123, "-100000.1"); + // decimal digits = 1 + testData.put(100000.123, "+100000.1"); + testData.put(-100000.123, "-100000.1"); - // decimal digits = 0 - testData.put(1000000.123, "+1000000"); - testData.put(-1000000.123, "-1000000"); + // decimal digits = 0 + testData.put(1000000.123, "+1000000"); + testData.put(-1000000.123, "-1000000"); - // max number 8 digits - testData.put(99999999.0, "+99999999"); - testData.put(-99999999.0, "-99999999"); + // max number 8 digits + testData.put(99999999.0, "+99999999"); + testData.put(-99999999.0, "-99999999"); - String expectedResult; - double input; + String expectedResult; + double input; - Iterator i = testData.keySet().iterator(); + Iterator i = testData.keySet().iterator(); - while (i.hasNext()) { + while (i.hasNext()) { - input = i.next(); - expectedResult = testData.get(input); + input = i.next(); + expectedResult = testData.get(input); - try { - String result = IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); + try { + String result = IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); - System.out.println(input + " --> " + result + " " + expectedResult); + System.out.println(input + " --> " + result + " " + expectedResult); - Assert.assertEquals(expectedResult, result); + Assert.assertEquals(expectedResult, result); - } catch (WrongScalingException e) { - e.printStackTrace(); - } - } + } catch (WrongScalingException e) { + e.printStackTrace(); + } + } - } + } - @Test - public void testWrongScalingException() { + @Test + public void testWrongScalingException() { - double input = 100000000.0; + double input = 100000000.0; - try { - IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); - Assert.assertTrue("Expected WrongScalingException", false); - } catch (WrongScalingException e) { - Assert.assertTrue(true); - } + try { + IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); + Assert.assertTrue("Expected WrongScalingException", false); + } catch (WrongScalingException e) { + Assert.assertTrue(true); + } - input = -100000000.0; + input = -100000000.0; - try { - IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); - Assert.assertTrue("Expected WrongScalingException", false); - } catch (WrongScalingException e) { - Assert.assertTrue(true); - } - } + try { + IESDataFormatUtils.convertDoubleToStringWithMaxLength(input, Const.VALUE_SIZE_DOUBLE); + Assert.assertTrue("Expected WrongScalingException", false); + } catch (WrongScalingException e) { + Assert.assertTrue(true); + } + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestSuite.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestSuite.java index 8d123d5b..d2e86884 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestSuite.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestSuite.java @@ -20,63 +20,63 @@ */ package org.openmuc.framework.datalogger.ascii.test; -import java.io.File; -import java.io.FileNotFoundException; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import java.io.File; +import java.io.FileNotFoundException; + @RunWith(Suite.class) -@SuiteClasses({ LogFileReaderTestSingleFile.class, LogFileReaderTestBrokenFile.class, - LogFileReaderTestMultipleFiles.class, LogFileWriterTest.class, MiscTests.class }) +@SuiteClasses({LogFileReaderTestSingleFile.class, LogFileReaderTestBrokenFile.class, LogFileReaderTestMultipleFiles.class, + LogFileWriterTest.class, MiscTests.class}) public class TestSuite { - private static final String TESTFOLDER = "test"; + private static final String TESTFOLDER = "test"; - @BeforeClass - public static void setUp() { - System.out.println("setting up"); - createTestFolder(); - } + @BeforeClass + public static void setUp() { + System.out.println("setting up"); + createTestFolder(); + } - @AfterClass - public static void tearDown() { - System.out.println("tearing down"); - deleteTestFolder(); - } + @AfterClass + public static void tearDown() { + System.out.println("tearing down"); + deleteTestFolder(); + } - public static void createTestFolder() { + public static void createTestFolder() { - File testFolder = new File(TESTFOLDER); - if (!testFolder.exists()) { - testFolder.mkdir(); - } - } + File testFolder = new File(TESTFOLDER); + if (!testFolder.exists()) { + testFolder.mkdir(); + } + } - public static void deleteTestFolder() { - File testFolder = new File(TESTFOLDER); - try { - deleteRecursive(testFolder); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public static void deleteTestFolder() { + File testFolder = new File(TESTFOLDER); + try { + deleteRecursive(testFolder); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - private static boolean deleteRecursive(File path) throws FileNotFoundException { - if (!path.exists()) { - throw new FileNotFoundException(path.getAbsolutePath()); - } - boolean ret = true; - if (path.isDirectory()) { - for (File f : path.listFiles()) { - ret = ret && deleteRecursive(f); - } - } - return ret && path.delete(); - } + private static boolean deleteRecursive(File path) throws FileNotFoundException { + if (!path.exists()) { + throw new FileNotFoundException(path.getAbsolutePath()); + } + boolean ret = true; + if (path.isDirectory()) { + for (File f : path.listFiles()) { + ret = ret && deleteRecursive(f); + } + } + return ret && path.delete(); + } } diff --git a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestUtils.java b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestUtils.java index 061dce67..f78435f8 100644 --- a/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestUtils.java +++ b/projects/datalogger/ascii/src/test/java/org/openmuc/framework/datalogger/ascii/test/TestUtils.java @@ -26,19 +26,19 @@ import java.util.Locale; public class TestUtils { - public static final String TESTFOLDER = "test"; - public static final String TESTFOLDERPATH = System.getProperty("user.dir") + "/" + TESTFOLDER + "/"; + public static final String TESTFOLDER = "test"; + public static final String TESTFOLDERPATH = System.getProperty("user.dir") + "/" + TESTFOLDER + "/"; - static Date stringToDate(String format, String strDate) { + static Date stringToDate(String format, String strDate) { - SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.GERMAN); - Date date = null; - try { - date = sdf.parse(strDate); - } catch (ParseException e) { - e.printStackTrace(); - } + SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.GERMAN); + Date date = null; + try { + date = sdf.parse(strDate); + } catch (ParseException e) { + e.printStackTrace(); + } - return date; - } + return date; + } } diff --git a/projects/datalogger/slotsdb/build.gradle b/projects/datalogger/slotsdb/build.gradle index 31c59180..26645c8a 100644 --- a/projects/datalogger/slotsdb/build.gradle +++ b/projects/datalogger/slotsdb/build.gradle @@ -1,12 +1,11 @@ - dependencies { - compile project(':openmuc-core-spi') + compile project(':openmuc-core-spi') } jar { - manifest { - name = "OpenMUC Data Logger - SlotsDB" - instruction 'Service-Component', 'OSGI-INF/components.xml' - instruction 'Export-Package', '' - } + manifest { + name = "OpenMUC Data Logger - SlotsDB" + instruction 'Service-Component', 'OSGI-INF/components.xml' + instruction 'Export-Package', '' + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObject.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObject.java index a2a266d3..25037c00 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObject.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObject.java @@ -21,420 +21,409 @@ package org.openmuc.framework.datalogger.slotsdb; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; +import org.openmuc.framework.data.DoubleValue; +import org.openmuc.framework.data.Flag; +import org.openmuc.framework.data.Record; + +import java.io.*; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; import java.util.Vector; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.Record; - public final class FileObject { - private long startTimeStamp; // byte 0-7 in file (cached) - private long storagePeriod; // byte 8-15 in file (cached) - private final File dataFile; - private DataOutputStream dos; - private BufferedOutputStream bos; - private FileOutputStream fos; - private DataInputStream dis; - private FileInputStream fis; - private boolean canWrite; - private boolean canRead; - /* - * File length will be cached to avoid system calls an improve I/O Performance - */ - private long length = 0; - - public FileObject(String filename) throws IOException { - canWrite = false; - canRead = false; - dataFile = new File(filename); - length = dataFile.length(); - if (dataFile.exists() && length >= 16) { - /* + private long startTimeStamp; // byte 0-7 in file (cached) + private long storagePeriod; // byte 8-15 in file (cached) + private final File dataFile; + private DataOutputStream dos; + private BufferedOutputStream bos; + private FileOutputStream fos; + private DataInputStream dis; + private FileInputStream fis; + private boolean canWrite; + private boolean canRead; + /* + * File length will be cached to avoid system calls an improve I/O Performance + */ + private long length = 0; + + public FileObject(String filename) throws IOException { + canWrite = false; + canRead = false; + dataFile = new File(filename); + length = dataFile.length(); + if (dataFile.exists() && length >= 16) { + /* * File already exists -> get file Header (startTime and step-frequency) TODO: compare to starttime and * frequency in constructor! new file needed? update to file-array! */ - try { - fis = new FileInputStream(dataFile); - try { - dis = new DataInputStream(fis); - try { - startTimeStamp = dis.readLong(); - storagePeriod = dis.readLong(); - } finally { - if (dis != null) { - dis.close(); - dis = null; - } - } - } finally { - if (dis != null) { - dis.close(); - dis = null; - } - } - } finally { - if (fis != null) { - fis.close(); - fis = null; - } - } - } - } - - public FileObject(File file) throws IOException { - canWrite = false; - canRead = false; - dataFile = file; - length = dataFile.length(); - if (dataFile.exists() && length >= 16) { + try { + fis = new FileInputStream(dataFile); + try { + dis = new DataInputStream(fis); + try { + startTimeStamp = dis.readLong(); + storagePeriod = dis.readLong(); + } finally { + if (dis != null) { + dis.close(); + dis = null; + } + } + } finally { + if (dis != null) { + dis.close(); + dis = null; + } + } + } finally { + if (fis != null) { + fis.close(); + fis = null; + } + } + } + } + + public FileObject(File file) throws IOException { + canWrite = false; + canRead = false; + dataFile = file; + length = dataFile.length(); + if (dataFile.exists() && length >= 16) { /* * File already exists -> get file Header (startTime and step-frequency) */ - fis = new FileInputStream(dataFile); - try { - dis = new DataInputStream(fis); - try { - startTimeStamp = dis.readLong(); - storagePeriod = dis.readLong(); - } finally { - if (dis != null) { - dis.close(); - dis = null; - } - } - } finally { - if (fis != null) { - fis.close(); - fis = null; - } - } - - } - } - - private void enableOutput() throws IOException { + fis = new FileInputStream(dataFile); + try { + dis = new DataInputStream(fis); + try { + startTimeStamp = dis.readLong(); + storagePeriod = dis.readLong(); + } finally { + if (dis != null) { + dis.close(); + dis = null; + } + } + } finally { + if (fis != null) { + fis.close(); + fis = null; + } + } + + } + } + + private void enableOutput() throws IOException { /* * Close Input Streams, for enabling output. */ - if (dis != null) { - dis.close(); - dis = null; - } - if (fis != null) { - fis.close(); - fis = null; - } + if (dis != null) { + dis.close(); + dis = null; + } + if (fis != null) { + fis.close(); + fis = null; + } /* * enabling output */ - if (fos == null || dos == null || bos == null) { - fos = new FileOutputStream(dataFile, true); - bos = new BufferedOutputStream(fos); - dos = new DataOutputStream(bos); - } - canRead = false; - canWrite = true; - } - - private void enableInput() throws IOException { + if (fos == null || dos == null || bos == null) { + fos = new FileOutputStream(dataFile, true); + bos = new BufferedOutputStream(fos); + dos = new DataOutputStream(bos); + } + canRead = false; + canWrite = true; + } + + private void enableInput() throws IOException { /* * Close Output Streams for enabling input. */ - if (dos != null) { - dos.flush(); - dos.close(); - dos = null; - } - if (bos != null) { - bos.close(); - bos = null; - } - if (fos != null) { - fos.close(); - fos = null; - } + if (dos != null) { + dos.flush(); + dos.close(); + dos = null; + } + if (bos != null) { + bos.close(); + bos = null; + } + if (fos != null) { + fos.close(); + fos = null; + } /* * enabling input */ - if (fis == null || dis == null) { - fis = new FileInputStream(dataFile); - dis = new DataInputStream(fis); - } - canWrite = false; - canRead = true; - } - - /** - * Return the Timestamp of the first stored Value in this File. - */ - public long getStartTimeStamp() { - return startTimeStamp; - } - - /** - * @return step frequency in seconds - */ - public long getStoringPeriod() { - return storagePeriod; - } - - /** - * creates the file, if it doesn't exist. - * - * @param startTimeStamp - * for file header - */ - public void createFileAndHeader(long startTimeStamp, long stepIntervall) throws IOException { - if (!dataFile.exists() || length < 16) { - dataFile.getParentFile().mkdirs(); - if (dataFile.exists() && length < 16) { - dataFile.delete(); // file corrupted (header shorter that 16 - } - // bytes) - dataFile.createNewFile(); - this.startTimeStamp = startTimeStamp; - storagePeriod = stepIntervall; + if (fis == null || dis == null) { + fis = new FileInputStream(dataFile); + dis = new DataInputStream(fis); + } + canWrite = false; + canRead = true; + } + + /** + * Return the Timestamp of the first stored Value in this File. + */ + public long getStartTimeStamp() { + return startTimeStamp; + } + + /** + * @return step frequency in seconds + */ + public long getStoringPeriod() { + return storagePeriod; + } + + /** + * creates the file, if it doesn't exist. + * + * @param startTimeStamp for file header + */ + public void createFileAndHeader(long startTimeStamp, long stepIntervall) throws IOException { + if (!dataFile.exists() || length < 16) { + dataFile.getParentFile().mkdirs(); + if (dataFile.exists() && length < 16) { + dataFile.delete(); // file corrupted (header shorter that 16 + } + // bytes) + dataFile.createNewFile(); + this.startTimeStamp = startTimeStamp; + storagePeriod = stepIntervall; /* * Do not close Output streams, because after writing the header -> data will follow! */ - fos = new FileOutputStream(dataFile); - bos = new BufferedOutputStream(fos); - dos = new DataOutputStream(bos); - dos.writeLong(startTimeStamp); - dos.writeLong(stepIntervall); - dos.flush(); - length += 16; /* wrote 2*8 Bytes */ - canWrite = true; - canRead = false; - } - } - - public void append(double value, long timestamp, byte flag) throws IOException { - long writePosition = getBytePosition(timestamp); - if (writePosition == length) { + fos = new FileOutputStream(dataFile); + bos = new BufferedOutputStream(fos); + dos = new DataOutputStream(bos); + dos.writeLong(startTimeStamp); + dos.writeLong(stepIntervall); + dos.flush(); + length += 16; /* wrote 2*8 Bytes */ + canWrite = true; + canRead = false; + } + } + + public void append(double value, long timestamp, byte flag) throws IOException { + long writePosition = getBytePosition(timestamp); + if (writePosition == length) { /* * value for this timeslot has not been saved yet "AND" some value has been stored in last timeslot */ - if (!canWrite) { - enableOutput(); - } - - dos.writeDouble(value); - dos.writeByte(flag); - length += 9; - } - else { - if (length > writePosition) { + if (!canWrite) { + enableOutput(); + } + + dos.writeDouble(value); + dos.writeByte(flag); + length += 9; + } else { + if (length > writePosition) { /* * value has already been stored for this timeslot -> handle? AVERAGE, MIN, MAX, LAST speichern?! */ - } - else { + } else { /* * there are missing some values missing -> fill up with NaN! */ - if (!canWrite) { - enableOutput(); - } - long rowsToFillWithNan = (writePosition - length) / 9;// TODO: - // stimmt - // Berechnung? - for (int i = 0; i < rowsToFillWithNan; i++) { - dos.writeDouble(Double.NaN); // TODO: festlegen welcher Wert - // undefined sein soll NaN - // ok? - dos.writeByte(Flag.NO_VALUE_RECEIVED_YET.getCode()); // TODO: - // festlegen - // welcher Wert - // undefined sein - // soll 00 ok? - length += 9; - } - dos.writeDouble(value); - dos.writeByte(flag); - length += 9; - } - } + if (!canWrite) { + enableOutput(); + } + long rowsToFillWithNan = (writePosition - length) / 9;// TODO: + // stimmt + // Berechnung? + for (int i = 0; i < rowsToFillWithNan; i++) { + dos.writeDouble(Double.NaN); // TODO: festlegen welcher Wert + // undefined sein soll NaN + // ok? + dos.writeByte(Flag.NO_VALUE_RECEIVED_YET.getCode()); // TODO: + // festlegen + // welcher Wert + // undefined sein + // soll 00 ok? + length += 9; + } + dos.writeDouble(value); + dos.writeByte(flag); + length += 9; + } + } /* * close(); OutputStreams will not be closed or flushed. Data will be written to disk after calling flush() * method. */ - } + } - public long getTimestampForLatestValue() { - return startTimeStamp + (((length - 16) / 9) - 1) * storagePeriod; - } + public long getTimestampForLatestValue() { + return startTimeStamp + (((length - 16) / 9) - 1) * storagePeriod; + } - /** - * calculates the position in a file for a certain timestamp - * - * @param timestamp - * @return position - */ - private long getBytePosition(long timestamp) { - if (timestamp >= startTimeStamp) { + /** + * calculates the position in a file for a certain timestamp + * + * @param timestamp + * @return position + */ + private long getBytePosition(long timestamp) { + if (timestamp >= startTimeStamp) { /* * get position for timestamp 117 000: 117 000 - 100 000 = 17 000 17 * 000 / 5 000 = 3.4 Math.round(3.4) = 3 * 3*(8+1) = 27 27 + 16 = 43 = position to store to! */ - // long pos = (Math.round((double) (timestamp - startTimeStamp) / - // storagePeriod) * 9) + 16; /* slower */ - - double pos = (double) (timestamp - startTimeStamp) / storagePeriod; - if (pos % 1 != 0) { /* faster */ - pos = Math.round(pos); - } - return (long) (pos * 9 + 16); - } - else { - // not in file! should never happen... - return -1; - } - } - - /* - * Calculates the closest timestamp to wanted timestamp getByteposition does a similar thing (Math.round()), for - * byte position. - */ - private long getClosestTimestamp(long timestamp) { - // return Math.round((double) (timestamp - - // startTimeStamp)/storagePeriod)*storagePeriod+startTimeStamp; /* - // slower */ - - double ts = (double) (timestamp - startTimeStamp) / storagePeriod; - if (ts % 1 != 0) { - ts = Math.round(ts); - } - return (long) ts * storagePeriod + startTimeStamp; - } - - public Record read(long timestamp) throws IOException { - timestamp = getClosestTimestamp(timestamp); // round to: startTimestamp - // + n*stepIntervall - if (timestamp >= startTimeStamp && timestamp <= getTimestampForLatestValue()) { - if (!canRead) { - enableInput(); - } - fis.getChannel().position(getBytePosition(timestamp)); - Double toReturn = dis.readDouble(); - if (!Double.isNaN(toReturn)) { - return new Record(new DoubleValue(toReturn), timestamp, Flag.newFlag(dis.readByte())); - } - } - return null; - } - - /** - * Returns a List of Value Objects containing the measured Values between provided start and end timestamp - * - * @param start - * @param end - * @throws IOException - */ - public List read(long start, long end) throws IOException { - start = getClosestTimestamp(start); // round to: startTimestamp + - // n*stepIntervall - end = getClosestTimestamp(end); // round to: startTimestamp + - // n*stepIntervall - - List toReturn = new Vector(); - - if (start < end) { - if (start < startTimeStamp) { - // of this file. - start = startTimeStamp; - } - if (end > getTimestampForLatestValue()) { - end = getTimestampForLatestValue(); - } - - if (!canRead) { - enableInput(); - } - - long timestampcounter = start; - long startPos = getBytePosition(start); - long endPos = getBytePosition(end); - - fis.getChannel().position(startPos); - - byte[] b = new byte[(int) (endPos - startPos) + 9]; - dis.read(b, 0, b.length); - ByteBuffer bb = ByteBuffer.wrap(b); - bb.rewind(); - - for (int i = 0; i <= (endPos - startPos) / 9; i++) { - double d = bb.getDouble(); - Flag s = Flag.newFlag(bb.get()); - if (!Double.isNaN(d)) { - toReturn.add(new Record(new DoubleValue(d), timestampcounter, s)); - } - timestampcounter += storagePeriod; - } - - } - else if (start == end) { - toReturn.add(read(start)); - toReturn.removeAll(Collections.singleton(null)); - } - return toReturn; // Always return a list -> might be empty -> never is - // null, to avoid NP's - } - - public List readFully() throws IOException { - return read(startTimeStamp, getTimestampForLatestValue()); - } - - /** - * Closes and Flushes underlying Input- and OutputStreams - * - * @throws IOException - */ - public void close() throws IOException { - canRead = false; - canWrite = false; - if (dos != null) { - dos.flush(); - dos.close(); - dos = null; - } - if (fos != null) { - fos.close(); - fos = null; - } - if (dis != null) { - dis.close(); - dis = null; - } - if (fis != null) { - fis.close(); - fis = null; - } - } - - /** - * Flushes the underlying Data Streams. - * - * @throws IOException - */ - public void flush() throws IOException { - if (dos != null) { - dos.flush(); - } - } + // long pos = (Math.round((double) (timestamp - startTimeStamp) / + // storagePeriod) * 9) + 16; /* slower */ + + double pos = (double) (timestamp - startTimeStamp) / storagePeriod; + if (pos % 1 != 0) { /* faster */ + pos = Math.round(pos); + } + return (long) (pos * 9 + 16); + } else { + // not in file! should never happen... + return -1; + } + } + + /* + * Calculates the closest timestamp to wanted timestamp getByteposition does a similar thing (Math.round()), for + * byte position. + */ + private long getClosestTimestamp(long timestamp) { + // return Math.round((double) (timestamp - + // startTimeStamp)/storagePeriod)*storagePeriod+startTimeStamp; /* + // slower */ + + double ts = (double) (timestamp - startTimeStamp) / storagePeriod; + if (ts % 1 != 0) { + ts = Math.round(ts); + } + return (long) ts * storagePeriod + startTimeStamp; + } + + public Record read(long timestamp) throws IOException { + timestamp = getClosestTimestamp(timestamp); // round to: startTimestamp + // + n*stepIntervall + if (timestamp >= startTimeStamp && timestamp <= getTimestampForLatestValue()) { + if (!canRead) { + enableInput(); + } + fis.getChannel().position(getBytePosition(timestamp)); + Double toReturn = dis.readDouble(); + if (!Double.isNaN(toReturn)) { + return new Record(new DoubleValue(toReturn), timestamp, Flag.newFlag(dis.readByte())); + } + } + return null; + } + + /** + * Returns a List of Value Objects containing the measured Values between provided start and end timestamp + * + * @param start + * @param end + * @throws IOException + */ + public List read(long start, long end) throws IOException { + start = getClosestTimestamp(start); // round to: startTimestamp + + // n*stepIntervall + end = getClosestTimestamp(end); // round to: startTimestamp + + // n*stepIntervall + + List toReturn = new Vector(); + + if (start < end) { + if (start < startTimeStamp) { + // of this file. + start = startTimeStamp; + } + if (end > getTimestampForLatestValue()) { + end = getTimestampForLatestValue(); + } + + if (!canRead) { + enableInput(); + } + + long timestampcounter = start; + long startPos = getBytePosition(start); + long endPos = getBytePosition(end); + + fis.getChannel().position(startPos); + + byte[] b = new byte[(int) (endPos - startPos) + 9]; + dis.read(b, 0, b.length); + ByteBuffer bb = ByteBuffer.wrap(b); + bb.rewind(); + + for (int i = 0; i <= (endPos - startPos) / 9; i++) { + double d = bb.getDouble(); + Flag s = Flag.newFlag(bb.get()); + if (!Double.isNaN(d)) { + toReturn.add(new Record(new DoubleValue(d), timestampcounter, s)); + } + timestampcounter += storagePeriod; + } + + } else if (start == end) { + toReturn.add(read(start)); + toReturn.removeAll(Collections.singleton(null)); + } + return toReturn; // Always return a list -> might be empty -> never is + // null, to avoid NP's + } + + public List readFully() throws IOException { + return read(startTimeStamp, getTimestampForLatestValue()); + } + + /** + * Closes and Flushes underlying Input- and OutputStreams + * + * @throws IOException + */ + public void close() throws IOException { + canRead = false; + canWrite = false; + if (dos != null) { + dos.flush(); + dos.close(); + dos = null; + } + if (fos != null) { + fos.close(); + fos = null; + } + if (dis != null) { + dis.close(); + dis = null; + } + if (fis != null) { + fis.close(); + fis = null; + } + } + + /** + * Flushes the underlying Data Streams. + * + * @throws IOException + */ + public void flush() throws IOException { + if (dos != null) { + dos.flush(); + } + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectList.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectList.java index 2251f30c..04efbea6 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectList.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectList.java @@ -39,254 +39,250 @@ * Usually there is only 1 File in a Folder/FileObjectList
    * But there might be more then 1 file in terms of reconfiguration.
    *
    - * */ public final class FileObjectList { - private List files; - // private File folder; - private String foldername; - private long firstTS; - private int size; + private List files; + // private File folder; + private String foldername; + private long firstTS; + private int size; - /** - * Creates a FileObjectList
    - * and creates a FileObject for every File - * - * @param foldername - * @throws IOException - */ - public FileObjectList(String foldername) throws IOException { - // File folder = new File(foldername); - this.foldername = foldername; - reLoadFolder(foldername); - } + /** + * Creates a FileObjectList
    + * and creates a FileObject for every File + * + * @param foldername + * @throws IOException + */ + public FileObjectList(String foldername) throws IOException { + // File folder = new File(foldername); + this.foldername = foldername; + reLoadFolder(foldername); + } - /** - * Reloads the List - * - * @param foldername - * containing Files - * @throws IOException - */ - public void reLoadFolder(String foldername) throws IOException { - this.foldername = foldername; - reLoadFolder(); - } + /** + * Reloads the List + * + * @param foldername containing Files + * @throws IOException + */ + public void reLoadFolder(String foldername) throws IOException { + this.foldername = foldername; + reLoadFolder(); + } - /** - * Reloads the List - * - * @throws IOException - */ - public void reLoadFolder() throws IOException { - File folder = new File(foldername); + /** + * Reloads the List + * + * @throws IOException + */ + public void reLoadFolder() throws IOException { + File folder = new File(foldername); - files = new Vector(1); - if (folder.isDirectory()) { - for (File file : folder.listFiles()) { - if (file.length() >= 16) { // otherwise is corrupted or empty - // file. - String[] split = file.getName().split("\\."); - if (("." + split[split.length - 1]).equals(SlotsDb.FILE_EXTENSION)) { - files.add(new FileObject(file)); - } - } - else { - file.delete(); - } - } - if (files.size() > 1) { - sortList(files); - } - } + files = new Vector(1); + if (folder.isDirectory()) { + for (File file : folder.listFiles()) { + if (file.length() >= 16) { // otherwise is corrupted or empty + // file. + String[] split = file.getName().split("\\."); + if (("." + split[split.length - 1]).equals(SlotsDb.FILE_EXTENSION)) { + files.add(new FileObject(file)); + } + } else { + file.delete(); + } + } + if (files.size() > 1) { + sortList(files); + } + } - size = files.size(); + size = files.size(); /* - * set first Timestamp for this FileObjectList if there are no files -> first TS = TS@ 00:00:00 o'clock. + * set first Timestamp for this FileObjectList if there are no files -> first TS = TS@ 00:00:00 o'clock. */ - if (size == 0) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); - try { - sdf.parse(folder.getParentFile().getName()); - } catch (ParseException e) { - throw new IOException("Unable to parse Timestamp from folder: " + folder.getParentFile().getName() - + ". Expected Folder in yyyyMMdd Format!"); - } - firstTS = sdf.getCalendar().getTimeInMillis(); - } - else { - firstTS = files.get(0).getStartTimeStamp(); - } - folder = null; - } + if (size == 0) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + try { + sdf.parse(folder.getParentFile().getName()); + } catch (ParseException e) { + throw new IOException("Unable to parse Timestamp from folder: " + folder.getParentFile() + .getName() + ". Expected Folder in yyyyMMdd " + + "Format!"); + } + firstTS = sdf.getCalendar().getTimeInMillis(); + } else { + firstTS = files.get(0).getStartTimeStamp(); + } + folder = null; + } - /* - * bubble sort to sort files in directory. usually there is only 1 file, might be 2... will also work for more. but - * not very fast. - */ - private void sortList(List toSort) { - int j = 0; - FileObject tmp; - boolean switched = true; - while (switched) { - switched = false; - j++; - for (int i = 0; i < toSort.size() - j; i++) { - if (toSort.get(i).getStartTimeStamp() > toSort.get(i + 1).getStartTimeStamp()) { - tmp = toSort.get(i); - toSort.set(i, toSort.get(i + 1)); - toSort.set(i + 1, tmp); - switched = true; - } - } - } - } + /* + * bubble sort to sort files in directory. usually there is only 1 file, might be 2... will also work for more. but + * not very fast. + */ + private void sortList(List toSort) { + int j = 0; + FileObject tmp; + boolean switched = true; + while (switched) { + switched = false; + j++; + for (int i = 0; i < toSort.size() - j; i++) { + if (toSort.get(i).getStartTimeStamp() > toSort.get(i + 1).getStartTimeStamp()) { + tmp = toSort.get(i); + toSort.set(i, toSort.get(i + 1)); + toSort.set(i + 1, tmp); + switched = true; + } + } + } + } - /** - * Returns the last created FileObject - */ - public FileObject getCurrentFileObject() { - return get(size - 1); - } + /** + * Returns the last created FileObject + */ + public FileObject getCurrentFileObject() { + return get(size - 1); + } - /** - * Returns the File Object at any position in list. - * - * @param position - */ - public FileObject get(int position) { - return files.get(position); - } + /** + * Returns the File Object at any position in list. + * + * @param position + */ + public FileObject get(int position) { + return files.get(position); + } - /** - * Returns the size (Number of Files in this Folder/FileObjectList) - */ - public int size() { - return size; - } + /** + * Returns the size (Number of Files in this Folder/FileObjectList) + */ + public int size() { + return size; + } - /** - * Closes all files in this List. This will also cause DataOutputStreams to be flushed. - * - * @throws IOException - */ - public void closeAllFiles() throws IOException { - for (FileObject f : files) { - f.close(); - } - } + /** + * Closes all files in this List. This will also cause DataOutputStreams to be flushed. + * + * @throws IOException + */ + public void closeAllFiles() throws IOException { + for (FileObject f : files) { + f.close(); + } + } - /** - * Returns a FileObject in this List for a certain Timestamp. If there is no FileObject containing this Value, null - * will be returned. - * - * @param timestamp - */ - public FileObject getFileObjectForTimestamp(long timestamp) { - if (files.size() > 1) { - for (FileObject f : files) { - if (f.getStartTimeStamp() <= timestamp && f.getTimestampForLatestValue() >= timestamp) { - // File - // found! - return f; - } - } - } - else if (files.size() == 1) { - if (files.get(0).getStartTimeStamp() <= timestamp && files.get(0).getTimestampForLatestValue() >= timestamp) { - // contains - // this - // TS - return files.get(0); - } - } - return null; - } + /** + * Returns a FileObject in this List for a certain Timestamp. If there is no FileObject containing this Value, null + * will be returned. + * + * @param timestamp + */ + public FileObject getFileObjectForTimestamp(long timestamp) { + if (files.size() > 1) { + for (FileObject f : files) { + if (f.getStartTimeStamp() <= timestamp && f.getTimestampForLatestValue() >= timestamp) { + // File + // found! + return f; + } + } + } else if (files.size() == 1) { + if (files.get(0).getStartTimeStamp() <= timestamp && files.get(0).getTimestampForLatestValue() >= timestamp) { + // contains + // this + // TS + return files.get(0); + } + } + return null; + } - /** - * Returns All FileObject in this List, which contain Data starting at given timestamp. - * - * @param timestamp - */ - public List getFileObjectsStartingAt(long timestamp) { - List toReturn = new Vector(1); - for (int i = 0; i < files.size(); i++) { - if (files.get(i).getTimestampForLatestValue() >= timestamp) { - toReturn.add(files.get(i)); - } - } - return toReturn; - } + /** + * Returns All FileObject in this List, which contain Data starting at given timestamp. + * + * @param timestamp + */ + public List getFileObjectsStartingAt(long timestamp) { + List toReturn = new Vector(1); + for (int i = 0; i < files.size(); i++) { + if (files.get(i).getTimestampForLatestValue() >= timestamp) { + toReturn.add(files.get(i)); + } + } + return toReturn; + } - /** - * Returns all FileObjects in this List. - */ - public List getAllFileObjects() { - return files; - } + /** + * Returns all FileObjects in this List. + */ + public List getAllFileObjects() { + return files; + } - /** - * Returns all FileObjects which contain Data before ending at given timestamp. - * - * @param timestamp - */ - public List getFileObjectsUntil(long timestamp) { - List toReturn = new Vector(1); - for (int i = 0; i < files.size(); i++) { - if (files.get(i).getStartTimeStamp() <= timestamp) { - toReturn.add(files.get(i)); - } - } - return toReturn; - } + /** + * Returns all FileObjects which contain Data before ending at given timestamp. + * + * @param timestamp + */ + public List getFileObjectsUntil(long timestamp) { + List toReturn = new Vector(1); + for (int i = 0; i < files.size(); i++) { + if (files.get(i).getStartTimeStamp() <= timestamp) { + toReturn.add(files.get(i)); + } + } + return toReturn; + } - /** - * Returns all FileObjects which contain Data from start to end timestamps - * - * @param start - * @param end - */ - public List getFileObjectsFromTo(long start, long end) { - List toReturn = new Vector(1); - if (files.size() > 1) { - for (int i = 0; i < files.size(); i++) { - if ((files.get(i).getStartTimeStamp() <= start && files.get(i).getTimestampForLatestValue() >= start) - || (files.get(i).getStartTimeStamp() <= end && files.get(i).getTimestampForLatestValue() >= end) - || (files.get(i).getStartTimeStamp() >= start && files.get(i).getTimestampForLatestValue() <= end)) { - // needed files. - toReturn.add(files.get(i)); - } - } - } - else if (files.size() == 1) { - if (files.get(0).getStartTimeStamp() <= end && files.get(0).getTimestampForLatestValue() >= start) { - // contains - // this - // TS - toReturn.add(files.get(0)); - } - } - return toReturn; - } + /** + * Returns all FileObjects which contain Data from start to end timestamps + * + * @param start + * @param end + */ + public List getFileObjectsFromTo(long start, long end) { + List toReturn = new Vector(1); + if (files.size() > 1) { + for (int i = 0; i < files.size(); i++) { + if ((files.get(i).getStartTimeStamp() <= start && files.get(i).getTimestampForLatestValue() >= start) || (files.get(i) + .getStartTimeStamp() <= end && files + .get(i).getTimestampForLatestValue() >= end) || (files.get(i).getStartTimeStamp() >= start && files.get(i) + .getTimestampForLatestValue() <= end)) { + // needed files. + toReturn.add(files.get(i)); + } + } + } else if (files.size() == 1) { + if (files.get(0).getStartTimeStamp() <= end && files.get(0).getTimestampForLatestValue() >= start) { + // contains + // this + // TS + toReturn.add(files.get(0)); + } + } + return toReturn; + } - /** - * Returns first recorded timestamp of oldest FileObject in this list. If List is empty, this timestamp will be set - * to 00:00:00 o'clock - */ - public long getFirstTS() { - return firstTS; - } + /** + * Returns first recorded timestamp of oldest FileObject in this list. If List is empty, this timestamp will be set + * to 00:00:00 o'clock + */ + public long getFirstTS() { + return firstTS; + } - /** - * Flushes all FileObjects in this list. - * - * @throws IOException - */ - public void flush() throws IOException { - for (FileObject f : files) { - f.flush(); - } - } + /** + * Flushes all FileObjects in this list. + * + * @throws IOException + */ + public void flush() throws IOException { + for (FileObject f : files) { + f.flush(); + } + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectProxy.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectProxy.java index b34be40f..4d6d6734 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectProxy.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/FileObjectProxy.java @@ -21,635 +21,607 @@ package org.openmuc.framework.datalogger.slotsdb; +import org.openmuc.framework.data.Record; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; -import java.util.Vector; - -import org.openmuc.framework.data.Record; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.*; public final class FileObjectProxy { - private final static Logger logger = LoggerFactory.getLogger(FileObjectProxy.class); - - private final File rootNode; - private HashMap openFilesHM; - private final HashMap encodedLabels; - private final SimpleDateFormat sdf; - private final Date date; - private final Timer timer; - private List days; - private long size; - - /* - * Flush Period in Seconds. if flush_period == 0 -> write directly to disk. - */ - private int flush_period = 0; - private int limit_days; - private int limit_size; - private int max_open_files; - - private String strCurrentDay; - private long currentDayFirstTS; - private long currentDayLastTS; - - /** - * Creates an instance of a FileObjectProxy
    - * The rootNodePath (output folder) usually is specified in JVM flag: org.openmuc.mux.dbprovider.slotsdb.dbfolder - */ - public FileObjectProxy(String rootNodePath) { - timer = new Timer(); - date = new Date(); - sdf = new SimpleDateFormat("yyyyMMdd"); - - if (!rootNodePath.endsWith("/")) { - rootNodePath += "/"; - } - logger.info("Storing to: " + rootNodePath); - - rootNode = new File(rootNodePath); - rootNode.mkdirs(); - openFilesHM = new HashMap(); - encodedLabels = new HashMap(); - - loadDays(); - - if (SlotsDb.FLUSH_PERIOD != null) { - flush_period = Integer.parseInt(SlotsDb.FLUSH_PERIOD); - logger.info("Flushing Data every: " + flush_period + "s. to disk."); - createScheduledFlusher(); - } - else { - logger.info("No Flush Period set. Writing Data directly to disk."); - } - - if (SlotsDb.DATA_LIFETIME_IN_DAYS != null) { - limit_days = Integer.parseInt(SlotsDb.DATA_LIFETIME_IN_DAYS); - logger.info("Maximum lifetime of stored Values: " + limit_days + " Days."); - createScheduledDeleteJob(); - } - else { - logger.info("Maximum lifetime of stored Values: UNLIMITED Days."); - } - - if (SlotsDb.MAX_DATABASE_SIZE != null) { - limit_size = Integer.parseInt(SlotsDb.MAX_DATABASE_SIZE); - if (limit_size < SlotsDb.MINIMUM_DATABASE_SIZE) { - limit_size = SlotsDb.MINIMUM_DATABASE_SIZE; - } - logger.info("Size Limit: " + limit_size + " MB."); - createScheduledSizeWatcher(); - } - else { - logger.info("Size Limit: UNLIMITED MB."); - } - - if (SlotsDb.MAX_OPEN_FOLDERS != null) { - max_open_files = Integer.parseInt(SlotsDb.MAX_OPEN_FOLDERS); - logger.info("Maximum open Files for Database changed to: " + max_open_files); - } - else { - max_open_files = SlotsDb.MAX_OPEN_FOLDERS_DEFAULT; - logger.info("Maximum open Files for Database is set to: " + max_open_files + " (default)."); - } - } - - /* - * loads a sorted list of all days in SLOTSDB. Necessary for search- and delete jobs. - */ - private void loadDays() { - days = new Vector(); - for (File f : rootNode.listFiles()) { - if (f.isDirectory()) { - days.add(f); - } - } - days = sortFolders(days); - } - - private List sortFolders(List days) { - Collections.sort(days, new Comparator() { - - @Override - public int compare(File f1, File f2) { - int i = 0; - try { - i = Long.valueOf(sdf.parse(f1.getName()).getTime()).compareTo(sdf.parse(f2.getName()).getTime()); - } catch (ParseException e) { - logger.error("Error during sorting Files: Folder doesn't match yyyymmdd Format?"); - } - return i; - } - }); - return days; - } - - /** - * Creates a Thread, that causes Data Streams to be flushed every x-seconds.
    - * Define flush-period in seconds with JVM flag: org.openmuc.mux.dbprovider.slotsdb.flushperiod - */ - private void createScheduledFlusher() { - timer.schedule(new Flusher(), flush_period * 1000, flush_period * 1000); - } - - class Flusher extends TimerTask { - - @Override - public void run() { - try { - flush(); - } catch (IOException e) { - logger.error("Flushing Data failed in IOException: " + e.getMessage()); - } - } - } - - private void createScheduledDeleteJob() { - timer.schedule(new DeleteJob(), SlotsDb.INITIAL_DELAY, SlotsDb.DATA_EXPIRATION_CHECK_INTERVAL); - } - - class DeleteJob extends TimerTask { - - @Override - public void run() { - try { - deleteFoldersOlderThen(limit_days); - } catch (IOException e) { - logger.error("Deleting old Data failed in IOException: " + e.getMessage()); - } - } - - private void deleteFoldersOlderThen(int limit_days) throws IOException { - Calendar limit = Calendar.getInstance(); - limit.setTimeInMillis(System.currentTimeMillis() - (86400000L * limit_days)); - Iterator iterator = days.iterator(); - try { - while (iterator.hasNext()) { - File curElement = iterator.next(); - if (sdf.parse(curElement.getName()).getTime() + 86400000 < limit.getTimeInMillis()) { /* - * compare + private final static Logger logger = LoggerFactory.getLogger(FileObjectProxy.class); + + private final File rootNode; + private HashMap openFilesHM; + private final HashMap encodedLabels; + private final SimpleDateFormat sdf; + private final Date date; + private final Timer timer; + private List days; + private long size; + + /* + * Flush Period in Seconds. if flush_period == 0 -> write directly to disk. + */ + private int flush_period = 0; + private int limit_days; + private int limit_size; + private int max_open_files; + + private String strCurrentDay; + private long currentDayFirstTS; + private long currentDayLastTS; + + /** + * Creates an instance of a FileObjectProxy
    + * The rootNodePath (output folder) usually is specified in JVM flag: org.openmuc.mux.dbprovider.slotsdb.dbfolder + */ + public FileObjectProxy(String rootNodePath) { + timer = new Timer(); + date = new Date(); + sdf = new SimpleDateFormat("yyyyMMdd"); + + if (!rootNodePath.endsWith("/")) { + rootNodePath += "/"; + } + logger.info("Storing to: " + rootNodePath); + + rootNode = new File(rootNodePath); + rootNode.mkdirs(); + openFilesHM = new HashMap(); + encodedLabels = new HashMap(); + + loadDays(); + + if (SlotsDb.FLUSH_PERIOD != null) { + flush_period = Integer.parseInt(SlotsDb.FLUSH_PERIOD); + logger.info("Flushing Data every: " + flush_period + "s. to disk."); + createScheduledFlusher(); + } else { + logger.info("No Flush Period set. Writing Data directly to disk."); + } + + if (SlotsDb.DATA_LIFETIME_IN_DAYS != null) { + limit_days = Integer.parseInt(SlotsDb.DATA_LIFETIME_IN_DAYS); + logger.info("Maximum lifetime of stored Values: " + limit_days + " Days."); + createScheduledDeleteJob(); + } else { + logger.info("Maximum lifetime of stored Values: UNLIMITED Days."); + } + + if (SlotsDb.MAX_DATABASE_SIZE != null) { + limit_size = Integer.parseInt(SlotsDb.MAX_DATABASE_SIZE); + if (limit_size < SlotsDb.MINIMUM_DATABASE_SIZE) { + limit_size = SlotsDb.MINIMUM_DATABASE_SIZE; + } + logger.info("Size Limit: " + limit_size + " MB."); + createScheduledSizeWatcher(); + } else { + logger.info("Size Limit: UNLIMITED MB."); + } + + if (SlotsDb.MAX_OPEN_FOLDERS != null) { + max_open_files = Integer.parseInt(SlotsDb.MAX_OPEN_FOLDERS); + logger.info("Maximum open Files for Database changed to: " + max_open_files); + } else { + max_open_files = SlotsDb.MAX_OPEN_FOLDERS_DEFAULT; + logger.info("Maximum open Files for Database is set to: " + max_open_files + " (default)."); + } + } + + /* + * loads a sorted list of all days in SLOTSDB. Necessary for search- and delete jobs. + */ + private void loadDays() { + days = new Vector(); + for (File f : rootNode.listFiles()) { + if (f.isDirectory()) { + days.add(f); + } + } + days = sortFolders(days); + } + + private List sortFolders(List days) { + Collections.sort(days, new Comparator() { + + @Override + public int compare(File f1, File f2) { + int i = 0; + try { + i = Long.valueOf(sdf.parse(f1.getName()).getTime()).compareTo(sdf.parse(f2.getName()).getTime()); + } catch (ParseException e) { + logger.error("Error during sorting Files: Folder doesn't match yyyymmdd Format?"); + } + return i; + } + }); + return days; + } + + /** + * Creates a Thread, that causes Data Streams to be flushed every x-seconds.
    + * Define flush-period in seconds with JVM flag: org.openmuc.mux.dbprovider.slotsdb.flushperiod + */ + private void createScheduledFlusher() { + timer.schedule(new Flusher(), flush_period * 1000, flush_period * 1000); + } + + class Flusher extends TimerTask { + + @Override + public void run() { + try { + flush(); + } catch (IOException e) { + logger.error("Flushing Data failed in IOException: " + e.getMessage()); + } + } + } + + private void createScheduledDeleteJob() { + timer.schedule(new DeleteJob(), SlotsDb.INITIAL_DELAY, SlotsDb.DATA_EXPIRATION_CHECK_INTERVAL); + } + + class DeleteJob extends TimerTask { + + @Override + public void run() { + try { + deleteFoldersOlderThen(limit_days); + } catch (IOException e) { + logger.error("Deleting old Data failed in IOException: " + e.getMessage()); + } + } + + private void deleteFoldersOlderThen(int limit_days) throws IOException { + Calendar limit = Calendar.getInstance(); + limit.setTimeInMillis(System.currentTimeMillis() - (86400000L * limit_days)); + Iterator iterator = days.iterator(); + try { + while (iterator.hasNext()) { + File curElement = iterator.next(); + if (sdf.parse(curElement.getName()).getTime() + 86400000 < limit.getTimeInMillis()) { /* + * compare * folder 's * oldest value * to limit */ - logger.info("Folder: " + curElement.getName() + " is older then " + limit_days - + " Days. Will be deleted."); - deleteRecursiveFolder(curElement); - } - else { + logger.info("Folder: " + curElement.getName() + " is older then " + limit_days + " Days. Will be deleted."); + deleteRecursiveFolder(curElement); + } else { /* oldest existing Folder is not to be deleted yet */ - break; - } - } - loadDays(); - } catch (ParseException e) { - logger.error("Error during sorting Files: Any Folder doesn't match yyyymmdd Format?"); - } - } - } - - private void createScheduledSizeWatcher() { - timer.schedule(new SizeWatcher(), SlotsDb.INITIAL_DELAY, SlotsDb.DATA_EXPIRATION_CHECK_INTERVAL); - } - - class SizeWatcher extends TimerTask { - - @Override - public void run() { - try { - while ((getDiskUsage(rootNode) / 1000000 > limit_size) && (days.size() >= 2)) { /* + break; + } + } + loadDays(); + } catch (ParseException e) { + logger.error("Error during sorting Files: Any Folder doesn't match yyyymmdd Format?"); + } + } + } + + private void createScheduledSizeWatcher() { + timer.schedule(new SizeWatcher(), SlotsDb.INITIAL_DELAY, SlotsDb.DATA_EXPIRATION_CHECK_INTERVAL); + } + + class SizeWatcher extends TimerTask { + + @Override + public void run() { + try { + while ((getDiskUsage(rootNode) / 1000000 > limit_size) && (days.size() >= 2)) { /* * avoid deleting * current folder */ - deleteOldestFolder(); - } - } catch (IOException e) { - logger.error("Deleting old Data failed in IOException: " + e.getMessage()); - } - } - - private void deleteOldestFolder() throws IOException { - if (days.size() >= 2) { - logger.info("Exceeded Maximum Database Size: " + limit_size + " MB. Current size: " + (size / 1000000) - + " MB. Deleting: " + days.get(0).getCanonicalPath()); - deleteRecursiveFolder(days.get(0)); - days.remove(0); - clearOpenFilesHashMap(); - } - } - } - - private synchronized void deleteRecursiveFolder(File folder) { - if (folder.exists()) { - for (File f : folder.listFiles()) { - if (f.isDirectory()) { - deleteRecursiveFolder(f); - if (f.delete()) { - ; - } - } - else { - f.delete(); - } - } - folder.delete(); - } - } - - /* - * recursive function to get the size of a folder. sums up all files. needs an initial LONG to store size to. - */ - private long getDiskUsage(File folder) throws IOException { - size = 0; - recursive_size_walker(folder); - return size; - } - - private void recursive_size_walker(File folder) throws IOException { - for (File f : folder.listFiles()) { - size += f.length(); - if (f.isDirectory()) { - recursive_size_walker(f); - } - } - } - - /** - * Appends a new Value to Slots Database. - * - * @param id - * @param value - * @param timestamp - * @param state - * @param storingPeriod - * @throws IOException - */ - public synchronized void appendValue(String id, double value, long timestamp, byte state, long storingPeriod) - throws IOException { - FileObject toStoreIn = null; - - id = encodeLabel(id); - - String strDate = getStrDate(timestamp); + deleteOldestFolder(); + } + } catch (IOException e) { + logger.error("Deleting old Data failed in IOException: " + e.getMessage()); + } + } + + private void deleteOldestFolder() throws IOException { + if (days.size() >= 2) { + logger.info( + "Exceeded Maximum Database Size: " + limit_size + " MB. Current size: " + (size / 1000000) + " MB. Deleting: " + + days + .get(0).getCanonicalPath()); + deleteRecursiveFolder(days.get(0)); + days.remove(0); + clearOpenFilesHashMap(); + } + } + } + + private synchronized void deleteRecursiveFolder(File folder) { + if (folder.exists()) { + for (File f : folder.listFiles()) { + if (f.isDirectory()) { + deleteRecursiveFolder(f); + if (f.delete()) { + ; + } + } else { + f.delete(); + } + } + folder.delete(); + } + } + + /* + * recursive function to get the size of a folder. sums up all files. needs an initial LONG to store size to. + */ + private long getDiskUsage(File folder) throws IOException { + size = 0; + recursive_size_walker(folder); + return size; + } + + private void recursive_size_walker(File folder) throws IOException { + for (File f : folder.listFiles()) { + size += f.length(); + if (f.isDirectory()) { + recursive_size_walker(f); + } + } + } + + /** + * Appends a new Value to Slots Database. + * + * @param id + * @param value + * @param timestamp + * @param state + * @param storingPeriod + * @throws IOException + */ + public synchronized void appendValue(String id, double value, long timestamp, byte state, long storingPeriod) throws IOException { + FileObject toStoreIn = null; + + id = encodeLabel(id); + + String strDate = getStrDate(timestamp); /* * If there is no FileObjectList for this folder, a new one will be created. (This will be the first value * stored for this day) Eventually existing FileObjectLists from the day before will be flushed and closed. Also * the Hashtable size will be monitored, to not have too many opened Filestreams. */ - if (!openFilesHM.containsKey(id + strDate)) { - deleteEntryFromLastDay(timestamp, id); - controlHashtableSize(); - FileObjectList first = new FileObjectList(rootNode.getPath() + "/" + strDate + "/" + id); - openFilesHM.put(id + strDate, first); + if (!openFilesHM.containsKey(id + strDate)) { + deleteEntryFromLastDay(timestamp, id); + controlHashtableSize(); + FileObjectList first = new FileObjectList(rootNode.getPath() + "/" + strDate + "/" + id); + openFilesHM.put(id + strDate, first); /* * If FileObjectList for this label does not contain any FileObjects yet, a new one will be created. Data * will be stored and List reloaded for next Value to store. */ - if (first.size() == 0) { - toStoreIn = new FileObject(rootNode.getPath() + "/" + strDate + "/" + id + "/" + timestamp - + SlotsDb.FILE_EXTENSION); - toStoreIn.createFileAndHeader(timestamp, storingPeriod); - toStoreIn.append(value, timestamp, state); - toStoreIn.close(); /* close() also calls flush(). */ - openFilesHM.get(id + strDate).reLoadFolder(); - return; - } - } + if (first.size() == 0) { + toStoreIn = new FileObject(rootNode.getPath() + "/" + strDate + "/" + id + "/" + timestamp + SlotsDb.FILE_EXTENSION); + toStoreIn.createFileAndHeader(timestamp, storingPeriod); + toStoreIn.append(value, timestamp, state); + toStoreIn.close(); /* close() also calls flush(). */ + openFilesHM.get(id + strDate).reLoadFolder(); + return; + } + } /* * There is a FileObjectList for this day. */ - FileObjectList listToStoreIn = openFilesHM.get(id + strDate); - if (listToStoreIn.size() > 0) { - toStoreIn = listToStoreIn.getCurrentFileObject(); + FileObjectList listToStoreIn = openFilesHM.get(id + strDate); + if (listToStoreIn.size() > 0) { + toStoreIn = listToStoreIn.getCurrentFileObject(); /* * If StartTimeStamp is newer then the Timestamp of the value to store, this value can't be stored. */ - if (toStoreIn.getStartTimeStamp() > timestamp) { - return; - } - } + if (toStoreIn.getStartTimeStamp() > timestamp) { + return; + } + } /* * The storing Period may have changed. In this case, a new FileObject must be created. */ - if (toStoreIn.getStoringPeriod() == storingPeriod || toStoreIn.getStoringPeriod() == 0) { - toStoreIn = openFilesHM.get(id + strDate).getCurrentFileObject(); - toStoreIn.append(value, timestamp, state); - if (flush_period == 0) { - toStoreIn.flush(); - } - else { - return; - } - } - else { + if (toStoreIn.getStoringPeriod() == storingPeriod || toStoreIn.getStoringPeriod() == 0) { + toStoreIn = openFilesHM.get(id + strDate).getCurrentFileObject(); + toStoreIn.append(value, timestamp, state); + if (flush_period == 0) { + toStoreIn.flush(); + } else { + return; + } + } else { /* * Intervall changed -> create new File (if there are no newer values for this day, or file) */ - if (toStoreIn.getTimestampForLatestValue() < timestamp) { - toStoreIn = new FileObject(rootNode.getPath() + "/" + strDate + "/" + id + "/" + timestamp - + SlotsDb.FILE_EXTENSION); - toStoreIn.createFileAndHeader(timestamp, storingPeriod); - toStoreIn.append(value, timestamp, state); - if (flush_period == 0) { - toStoreIn.flush(); - } - openFilesHM.get(id + strDate).reLoadFolder(); - } - } - } - - private String encodeLabel(String label) throws IOException { - String encodedLabel = encodedLabels.get(label); - if (encodedLabel == null) { - encodedLabel = URLEncoder.encode(label, Charset.defaultCharset().toString()); // encodes label to supported - // String for Filenames. - encodedLabels.put(label, encodedLabel); - } - return encodedLabel; - } - - public synchronized Record read(String label, long timestamp) throws IOException { - // label = URLEncoder.encode(label,Charset.defaultCharset().toString()); - // //encodes label to supported String for Filenames. - label = encodeLabel(label); - - String strDate = getStrDate(timestamp); - - if (!openFilesHM.containsKey(label + strDate)) { - controlHashtableSize(); - FileObjectList fol = new FileObjectList(rootNode.getPath() + "/" + strDate + "/" + label); - openFilesHM.put(label + strDate, fol); - } - FileObject toReadFrom = openFilesHM.get(label + strDate).getFileObjectForTimestamp(timestamp); - if (toReadFrom != null) { - return toReadFrom.read(timestamp); // null if no value for timestamp - // is available - } - return null; - } - - public synchronized List read(String label, long start, long end) throws IOException { - if (logger.isTraceEnabled()) { - logger.trace("Called: read(" + label + ", " + start + ", " + end + ")"); - } - - List toReturn = new Vector(); - - if (start > end) { - logger.trace("Invalid Read Request: startTS > endTS"); - return toReturn; - } - - if (start == end) { - toReturn.add(read(label, start)); // let other read function handle. - toReturn.removeAll(Collections.singleton(null)); - return toReturn; - } - if (end > 50000000000000L) { /* + if (toStoreIn.getTimestampForLatestValue() < timestamp) { + toStoreIn = new FileObject(rootNode.getPath() + "/" + strDate + "/" + id + "/" + timestamp + SlotsDb.FILE_EXTENSION); + toStoreIn.createFileAndHeader(timestamp, storingPeriod); + toStoreIn.append(value, timestamp, state); + if (flush_period == 0) { + toStoreIn.flush(); + } + openFilesHM.get(id + strDate).reLoadFolder(); + } + } + } + + private String encodeLabel(String label) throws IOException { + String encodedLabel = encodedLabels.get(label); + if (encodedLabel == null) { + encodedLabel = URLEncoder.encode(label, Charset.defaultCharset().toString()); // encodes label to supported + // String for Filenames. + encodedLabels.put(label, encodedLabel); + } + return encodedLabel; + } + + public synchronized Record read(String label, long timestamp) throws IOException { + // label = URLEncoder.encode(label,Charset.defaultCharset().toString()); + // //encodes label to supported String for Filenames. + label = encodeLabel(label); + + String strDate = getStrDate(timestamp); + + if (!openFilesHM.containsKey(label + strDate)) { + controlHashtableSize(); + FileObjectList fol = new FileObjectList(rootNode.getPath() + "/" + strDate + "/" + label); + openFilesHM.put(label + strDate, fol); + } + FileObject toReadFrom = openFilesHM.get(label + strDate).getFileObjectForTimestamp(timestamp); + if (toReadFrom != null) { + return toReadFrom.read(timestamp); // null if no value for timestamp + // is available + } + return null; + } + + public synchronized List read(String label, long start, long end) throws IOException { + if (logger.isTraceEnabled()) { + logger.trace("Called: read(" + label + ", " + start + ", " + end + ")"); + } + + List toReturn = new Vector(); + + if (start > end) { + logger.trace("Invalid Read Request: startTS > endTS"); + return toReturn; + } + + if (start == end) { + toReturn.add(read(label, start)); // let other read function handle. + toReturn.removeAll(Collections.singleton(null)); + return toReturn; + } + if (end > 50000000000000L) { /* * to prevent buffer overflows. in cases of multiplication */ - end = 50000000000000L; - } + end = 50000000000000L; + } - // label = URLEncoder.encode(label,Charset.defaultCharset().toString()); - // //encodes label to supported String for Filenames. - label = encodeLabel(label); + // label = URLEncoder.encode(label,Charset.defaultCharset().toString()); + // //encodes label to supported String for Filenames. + label = encodeLabel(label); - String strStartDate = getStrDate(start); - String strEndDate = getStrDate(end); + String strStartDate = getStrDate(start); + String strEndDate = getStrDate(end); - List toRead = new Vector(); + List toRead = new Vector(); - if (!strStartDate.equals(strEndDate)) { - logger.trace("Reading Multiple Days. Scanning for Folders."); - List days = new Vector(); + if (!strStartDate.equals(strEndDate)) { + logger.trace("Reading Multiple Days. Scanning for Folders."); + List days = new Vector(); /* * Check for Folders matching criteria: Folder contains data between start & end timestamp. Folder contains * label. */ - String strSubfolder; - for (File folder : rootNode.listFiles()) { - if (folder.isDirectory()) { - if (isFolderBetweenStartAndEnd(folder.getName(), start, end)) { - if (Arrays.asList(folder.list()).contains(label)) { - strSubfolder = rootNode.getPath() + "/" + folder.getName() + "/" + label; - days.add(new FileObjectList(strSubfolder)); - logger.trace(strSubfolder + " contains " + SlotsDb.FILE_EXTENSION + " files to read from."); - } - } - } - } + String strSubfolder; + for (File folder : rootNode.listFiles()) { + if (folder.isDirectory()) { + if (isFolderBetweenStartAndEnd(folder.getName(), start, end)) { + if (Arrays.asList(folder.list()).contains(label)) { + strSubfolder = rootNode.getPath() + "/" + folder.getName() + "/" + label; + days.add(new FileObjectList(strSubfolder)); + logger.trace(strSubfolder + " contains " + SlotsDb.FILE_EXTENSION + " files to read from."); + } + } + } + } /* * Sort days, because rootNode.listFiles() is unsorted. FileObjectLists MUST be sorted, otherwise data * output wouldn't be sorted. */ - Collections.sort(days, new Comparator() { + Collections.sort(days, new Comparator() { - @Override - public int compare(FileObjectList f1, FileObjectList f2) { - return Long.valueOf(f1.getFirstTS()).compareTo(f2.getFirstTS()); - } - }); + @Override + public int compare(FileObjectList f1, FileObjectList f2) { + return Long.valueOf(f1.getFirstTS()).compareTo(f2.getFirstTS()); + } + }); /* * Create a list with all file-objects that must be read for this reading request. */ - if (days.size() == 0) { - return toReturn; - } - else if (days.size() == 1) { - toRead.addAll(days.get(0).getFileObjectsFromTo(start, end)); - } - else { // days.size()>1 - toRead.addAll(days.get(0).getFileObjectsStartingAt(start)); - for (int i = 1; i < days.size() - 1; i++) { - toRead.addAll(days.get(i).getAllFileObjects()); - } - toRead.addAll(days.get(days.size() - 1).getFileObjectsUntil(end)); - } - toRead.removeAll(Collections.singleton(null)); - } - else { // Start == End Folder -> only 1 FileObjectList must be read. - File folder = new File(rootNode.getPath() + "/" + strStartDate + "/" + label); - FileObjectList fol; - if (folder.list() != null) { - if (folder.list().length > 0) { // Are there Files in the - // folder, that should be read? - fol = new FileObjectList(rootNode.getPath() + "/" + strStartDate + "/" + label); - toRead.addAll(fol.getFileObjectsFromTo(start, end)); - } - } - } - logger.trace("Found " + toRead.size() + " " + SlotsDb.FILE_EXTENSION + " files to read from."); + if (days.size() == 0) { + return toReturn; + } else if (days.size() == 1) { + toRead.addAll(days.get(0).getFileObjectsFromTo(start, end)); + } else { // days.size()>1 + toRead.addAll(days.get(0).getFileObjectsStartingAt(start)); + for (int i = 1; i < days.size() - 1; i++) { + toRead.addAll(days.get(i).getAllFileObjects()); + } + toRead.addAll(days.get(days.size() - 1).getFileObjectsUntil(end)); + } + toRead.removeAll(Collections.singleton(null)); + } else { // Start == End Folder -> only 1 FileObjectList must be read. + File folder = new File(rootNode.getPath() + "/" + strStartDate + "/" + label); + FileObjectList fol; + if (folder.list() != null) { + if (folder.list().length > 0) { // Are there Files in the + // folder, that should be read? + fol = new FileObjectList(rootNode.getPath() + "/" + strStartDate + "/" + label); + toRead.addAll(fol.getFileObjectsFromTo(start, end)); + } + } + } + logger.trace("Found " + toRead.size() + " " + SlotsDb.FILE_EXTENSION + " files to read from."); /* * Read all FileObjects: first (2nd,3rd,4th....n-1) last first and last will be read separately, to not exceed * timestamp range. */ - if (toRead != null) { - if (toRead.size() > 1) { - toReturn.addAll(toRead.get(0).read(start, toRead.get(0).getTimestampForLatestValue())); - toRead.get(0).close(); - for (int i = 1; i < toRead.size() - 1; i++) { - toReturn.addAll(toRead.get(i).readFully()); - toRead.get(i).close(); - } - toReturn.addAll(toRead.get(toRead.size() - 1).read(toRead.get(toRead.size() - 1).getStartTimeStamp(), - end)); - toRead.get(toRead.size() - 1).close(); + if (toRead != null) { + if (toRead.size() > 1) { + toReturn.addAll(toRead.get(0).read(start, toRead.get(0).getTimestampForLatestValue())); + toRead.get(0).close(); + for (int i = 1; i < toRead.size() - 1; i++) { + toReturn.addAll(toRead.get(i).readFully()); + toRead.get(i).close(); + } + toReturn.addAll(toRead.get(toRead.size() - 1).read(toRead.get(toRead.size() - 1).getStartTimeStamp(), end)); + toRead.get(toRead.size() - 1).close(); /* * Some Values might be null -> remove */ - toReturn.removeAll(Collections.singleton(null)); - - } - else if (toRead.size() == 1) { // single FileObject - toReturn.addAll(toRead.get(0).read(start, end)); - toReturn.removeAll(Collections.singleton(null)); - } - } - logger.trace("Selected " + SlotsDb.FILE_EXTENSION + " files contain " + toReturn.size() + " Values."); - return toReturn; - } - - /** - * Parses a Timestamp in Milliseconds from a String in yyyyMMdd Format
    - * e.g.: 25.Sept.2011: 20110925
    - * would return: 1316901600000 ms. equal to (25.09.2011 - 00:00:00)
    - * - * @param name - * in "yyyyMMdd" Format - * @param start - * @param end - * @return boolean - * @throws IOException - */ - private boolean isFolderBetweenStartAndEnd(String name, long start, long end) throws IOException { - try { - sdf.parse(name); - } catch (ParseException e) { - logger.error("Unable to parse Timestamp from: " + name + " folder. " + e.getMessage()); - } - if (start <= sdf.getCalendar().getTimeInMillis() + 86399999 && sdf.getCalendar().getTimeInMillis() <= end) { // if - // start - // <= - // folder.lastTSofDay - // && - // folder.firstTSofDay - // <= - // end - return true; - } - return false; - } - - /* - * strCurrentDay holds the current Day in yyyyMMdd format, because SimpleDateFormat uses a lot cpu-time. - * currentDayFirstTS and ... currentDayLastTS mark the first and last timestamp of this day. If a TS exceeds this - * range, strCurrentDay, currentDayFirstTS, currentDayLastTS will be updated. - */ - private String getStrDate(long timestamp) throws IOException { - if (strCurrentDay != null) { - if (timestamp >= currentDayFirstTS && timestamp <= currentDayLastTS) { - return strCurrentDay; - } - } + toReturn.removeAll(Collections.singleton(null)); + + } else if (toRead.size() == 1) { // single FileObject + toReturn.addAll(toRead.get(0).read(start, end)); + toReturn.removeAll(Collections.singleton(null)); + } + } + logger.trace("Selected " + SlotsDb.FILE_EXTENSION + " files contain " + toReturn.size() + " Values."); + return toReturn; + } + + /** + * Parses a Timestamp in Milliseconds from a String in yyyyMMdd Format
    + * e.g.: 25.Sept.2011: 20110925
    + * would return: 1316901600000 ms. equal to (25.09.2011 - 00:00:00)
    + * + * @param name in "yyyyMMdd" Format + * @param start + * @param end + * @return boolean + * @throws IOException + */ + private boolean isFolderBetweenStartAndEnd(String name, long start, long end) throws IOException { + try { + sdf.parse(name); + } catch (ParseException e) { + logger.error("Unable to parse Timestamp from: " + name + " folder. " + e.getMessage()); + } + if (start <= sdf.getCalendar().getTimeInMillis() + 86399999 && sdf.getCalendar().getTimeInMillis() <= end) { // if + // start + // <= + // folder.lastTSofDay + // && + // folder.firstTSofDay + // <= + // end + return true; + } + return false; + } + + /* + * strCurrentDay holds the current Day in yyyyMMdd format, because SimpleDateFormat uses a lot cpu-time. + * currentDayFirstTS and ... currentDayLastTS mark the first and last timestamp of this day. If a TS exceeds this + * range, strCurrentDay, currentDayFirstTS, currentDayLastTS will be updated. + */ + private String getStrDate(long timestamp) throws IOException { + if (strCurrentDay != null) { + if (timestamp >= currentDayFirstTS && timestamp <= currentDayLastTS) { + return strCurrentDay; + } + } /* * timestamp for other day or not initialized yet. */ - date.setTime(timestamp); - strCurrentDay = sdf.format(date); - try { - currentDayFirstTS = sdf.parse(strCurrentDay).getTime(); - } catch (ParseException e) { - logger.error("Unable to parse Timestamp from: " + currentDayFirstTS + " String."); - } - currentDayLastTS = currentDayFirstTS + 86399999; - return strCurrentDay; - } - - private void deleteEntryFromLastDay(long timestamp, String label) throws IOException { - String strDate = getStrDate(timestamp - 86400000); - if (openFilesHM.containsKey(label + strDate)) { + date.setTime(timestamp); + strCurrentDay = sdf.format(date); + try { + currentDayFirstTS = sdf.parse(strCurrentDay).getTime(); + } catch (ParseException e) { + logger.error("Unable to parse Timestamp from: " + currentDayFirstTS + " String."); + } + currentDayLastTS = currentDayFirstTS + 86399999; + return strCurrentDay; + } + + private void deleteEntryFromLastDay(long timestamp, String label) throws IOException { + String strDate = getStrDate(timestamp - 86400000); + if (openFilesHM.containsKey(label + strDate)) { /* * Value for new day has been registered! Close and flush all connections! Empty Hashtable! */ - clearOpenFilesHashMap(); - logger.info("Started logging to a new Day. <" + strDate - + "> Folder has been closed and flushed completely."); + clearOpenFilesHashMap(); + logger.info("Started logging to a new Day. <" + strDate + "> Folder has been closed and flushed completely."); /* reload days */ - loadDays(); - } - } - - private void clearOpenFilesHashMap() throws IOException { - Iterator itr = openFilesHM.values().iterator(); - while (itr.hasNext()) { // kick out everything - itr.next().closeAllFiles(); - } - openFilesHM = new HashMap(); - } - - private void controlHashtableSize() throws IOException { + loadDays(); + } + } + + private void clearOpenFilesHashMap() throws IOException { + Iterator itr = openFilesHM.values().iterator(); + while (itr.hasNext()) { // kick out everything + itr.next().closeAllFiles(); + } + openFilesHM = new HashMap(); + } + + private void controlHashtableSize() throws IOException { /* * hm.size() doesn't really represent the number of open files, because it contains FileObjectLists, which may * contain 1 ore more FileObjects. In most cases, there is only 1 File in a List. There will be a second File if * storage Intervall is reconfigured. Continuous reconfiguring of measurement points may lead to a * "Too many open files" Exception. In this case SlotsDb.MAX_OPEN_FOLDERS should be decreased... */ - if (openFilesHM.size() > max_open_files) { - logger.debug("More then " + max_open_files - + " DataStreams are opened. Flushing and closing some to not exceed OS-Limit."); - Iterator itr = openFilesHM.values().iterator(); - for (int i = 0; i < (max_open_files / 5); i++) { // randomly kick - // out some of - // the - // FileObjectLists. - // -> the needed - // ones will be - // reinitialized, - // no problem - // here. - itr.next().closeAllFiles(); - itr.remove(); - } - } - } - - /** - * Flushes all Datastreams from all FileObjectLists and FileObjects - * - * @throws IOException - */ - public synchronized void flush() throws IOException { - - Iterator itr = openFilesHM.values().iterator(); - while (itr.hasNext()) { - itr.next().flush(); - } - - logger.info("Data from " + openFilesHM.size() + " Folders flushed to disk."); - } + if (openFilesHM.size() > max_open_files) { + logger.debug("More then " + max_open_files + " DataStreams are opened. Flushing and closing some to not exceed OS-Limit."); + Iterator itr = openFilesHM.values().iterator(); + for (int i = 0; i < (max_open_files / 5); i++) { // randomly kick + // out some of + // the + // FileObjectLists. + // -> the needed + // ones will be + // reinitialized, + // no problem + // here. + itr.next().closeAllFiles(); + itr.remove(); + } + } + } + + /** + * Flushes all Datastreams from all FileObjectLists and FileObjects + * + * @throws IOException + */ + public synchronized void flush() throws IOException { + + Iterator itr = openFilesHM.values().iterator(); + while (itr.hasNext()) { + itr.next().flush(); + } + + logger.info("Data from " + openFilesHM.size() + " Folders flushed to disk."); + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDatabaseUtil.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDatabaseUtil.java index dfbf3048..ae9b59d3 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDatabaseUtil.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDatabaseUtil.java @@ -21,39 +21,38 @@ package org.openmuc.framework.datalogger.slotsdb; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public final class SlotsDatabaseUtil { - private final static Logger logger = LoggerFactory.getLogger(SlotsDatabaseUtil.class); + private final static Logger logger = LoggerFactory.getLogger(SlotsDatabaseUtil.class); - public static void printWholeFile(File file) throws IOException { - if (!file.getName().contains(SlotsDb.FILE_EXTENSION)) { - System.err.println(file.getName() + " is not a \"" + SlotsDb.FILE_EXTENSION + "\" file."); - return; - } - else { - DataInputStream dis = new DataInputStream(new FileInputStream(file)); - try { - if (file.length() >= 16) { - logger.debug("StartTimestamp: " + dis.readLong() + " - StepIntervall: " + dis.readLong()); - while (dis.available() >= 9) { - logger.debug(dis.readDouble() + " -\t Flag: " + dis.readByte()); - } - } - } finally { - dis.close(); - } - } - } + public static void printWholeFile(File file) throws IOException { + if (!file.getName().contains(SlotsDb.FILE_EXTENSION)) { + System.err.println(file.getName() + " is not a \"" + SlotsDb.FILE_EXTENSION + "\" file."); + return; + } else { + DataInputStream dis = new DataInputStream(new FileInputStream(file)); + try { + if (file.length() >= 16) { + logger.debug("StartTimestamp: " + dis.readLong() + " - StepIntervall: " + dis.readLong()); + while (dis.available() >= 9) { + logger.debug(dis.readDouble() + " -\t Flag: " + dis.readByte()); + } + } + } finally { + dis.close(); + } + } + } - public static void printWholeFile(String filename) throws IOException { - printWholeFile(new File(filename)); - } + public static void printWholeFile(String filename) throws IOException { + printWholeFile(new File(filename)); + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDb.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDb.java index 0fc4b5af..accb3dc1 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDb.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDb.java @@ -21,10 +21,6 @@ package org.openmuc.framework.datalogger.slotsdb; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; - import org.openmuc.framework.data.Record; import org.openmuc.framework.data.TypeConversionException; import org.openmuc.framework.datalogger.spi.DataLoggerService; @@ -34,141 +30,141 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; + public final class SlotsDb implements DataLoggerService { - private final static Logger logger = LoggerFactory.getLogger(SlotsDb.class); - - /* - * File extension for SlotsDB files. Only these Files will be loaded. - */ - public static String FILE_EXTENSION = ".slots"; - - /* - * Root folder for SlotsDB files - */ - public static String DB_ROOT_FOLDER = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() - + ".dbfolder"); - - /* - * If no other root folder is defined, data will be stored to this folder - */ - public static String DEFAULT_DB_ROOT_FOLDER = "slotsdbdata/"; - - /* - * Root Folder for JUnit Testcases - */ - public static String DB_TEST_ROOT_FOLDER = "testdata/"; - - /* - * limit open files in Hashmap - * - * Default Linux Configuration: (should be below) - * - * host:/#> ulimit -aH [...] open files (-n) 1024 [...] - */ - public static String MAX_OPEN_FOLDERS = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() - + ".max_open_folders"); - public static int MAX_OPEN_FOLDERS_DEFAULT = 512; - - /* - * configures the data flush period. The less you flush, the faster SLOTSDB will be. unset this System Property (or - * set to 0) to flush data directly to disk. - */ - public static String FLUSH_PERIOD = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() - + ".flushperiod"); - - /* - * configures how long data will at least be stored in the SLOTSDB. - */ - public static String DATA_LIFETIME_IN_DAYS = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() - + ".limit_days"); - - /* - * configures the maximum Database Size (in MB). - */ - public static String MAX_DATABASE_SIZE = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() - + ".limit_size"); - - /* - * Minimum Size for SLOTSDB (in MB). - */ - public static int MINIMUM_DATABASE_SIZE = 2; - - /* - * Initial delay for scheduled tasks (size watcher, data expiration, etc.) - */ - public static int INITIAL_DELAY = 10000; - - /* - * Interval for scanning expired, old data. Set this to 86400000 to scan every 24 hours. - */ - public static int DATA_EXPIRATION_CHECK_INTERVAL = 5000; - - private FileObjectProxy fileObjectProxy; - private final HashMap loggingIntervalsById = new HashMap();; - - protected void activate(ComponentContext context) { - String rootFolder = SlotsDb.DB_ROOT_FOLDER; - if (rootFolder == null) { - rootFolder = SlotsDb.DEFAULT_DB_ROOT_FOLDER; - logger.info("System property " + SlotsDb.class.getPackage().getName().toLowerCase() - + ".dbfolder not set. Storing to " + SlotsDb.DEFAULT_DB_ROOT_FOLDER); - } - - fileObjectProxy = new FileObjectProxy(rootFolder); - } - - protected void deactivate(ComponentContext context) { - // TODO - } - - @Override - public String getId() { - return "slotsdb"; - } - - @Override - public List getRecords(String channelId, long startTime, long endTime) throws IOException { - return fileObjectProxy.read(channelId, startTime, endTime); - } - - @Override - public void setChannelsToLog(List channels) { - loggingIntervalsById.clear(); - for (LogChannel channel : channels) { - loggingIntervalsById.put(channel.getId(), channel.getLoggingInterval()); - } - } - - @Override - public void log(List containers, long timestamp) { - - for (LogRecordContainer container : containers) { - Double value; - if (container.getRecord().getValue() == null) { - value = Double.NaN; - } - else { - try { - value = container.getRecord().getValue().asDouble(); - } catch (TypeConversionException e) { - value = Double.NaN; - } - } - - // Long timestamp = container.getRecord().getTimestamp(); - // if (timestamp == null) { - // timestamp = 0L; - // } - - try { - fileObjectProxy.appendValue(container.getChannelId(), value, timestamp, container.getRecord().getFlag() - .getCode(), loggingIntervalsById.get(container.getChannelId())); - } catch (IOException e) { - logger.error("error logging records"); - e.printStackTrace(); - } - } - } + private final static Logger logger = LoggerFactory.getLogger(SlotsDb.class); + + /* + * File extension for SlotsDB files. Only these Files will be loaded. + */ + public static String FILE_EXTENSION = ".slots"; + + /* + * Root folder for SlotsDB files + */ + public static String DB_ROOT_FOLDER = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() + ".dbfolder"); + + /* + * If no other root folder is defined, data will be stored to this folder + */ + public static String DEFAULT_DB_ROOT_FOLDER = "slotsdbdata/"; + + /* + * Root Folder for JUnit Testcases + */ + public static String DB_TEST_ROOT_FOLDER = "testdata/"; + + /* + * limit open files in Hashmap + * + * Default Linux Configuration: (should be below) + * + * host:/#> ulimit -aH [...] open files (-n) 1024 [...] + */ + public static String MAX_OPEN_FOLDERS = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() + ".max_open_folders"); + public static int MAX_OPEN_FOLDERS_DEFAULT = 512; + + /* + * configures the data flush period. The less you flush, the faster SLOTSDB will be. unset this System Property (or + * set to 0) to flush data directly to disk. + */ + public static String FLUSH_PERIOD = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() + ".flushperiod"); + + /* + * configures how long data will at least be stored in the SLOTSDB. + */ + public static String DATA_LIFETIME_IN_DAYS = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() + ".limit_days"); + + /* + * configures the maximum Database Size (in MB). + */ + public static String MAX_DATABASE_SIZE = System.getProperty(SlotsDb.class.getPackage().getName().toLowerCase() + ".limit_size"); + + /* + * Minimum Size for SLOTSDB (in MB). + */ + public static int MINIMUM_DATABASE_SIZE = 2; + + /* + * Initial delay for scheduled tasks (size watcher, data expiration, etc.) + */ + public static int INITIAL_DELAY = 10000; + + /* + * Interval for scanning expired, old data. Set this to 86400000 to scan every 24 hours. + */ + public static int DATA_EXPIRATION_CHECK_INTERVAL = 5000; + + private FileObjectProxy fileObjectProxy; + private final HashMap loggingIntervalsById = new HashMap(); + ; + + protected void activate(ComponentContext context) { + String rootFolder = SlotsDb.DB_ROOT_FOLDER; + if (rootFolder == null) { + rootFolder = SlotsDb.DEFAULT_DB_ROOT_FOLDER; + logger.info("System property " + SlotsDb.class.getPackage().getName() + .toLowerCase() + ".dbfolder not set. Storing to " + SlotsDb + .DEFAULT_DB_ROOT_FOLDER); + } + + fileObjectProxy = new FileObjectProxy(rootFolder); + } + + protected void deactivate(ComponentContext context) { + // TODO + } + + @Override + public String getId() { + return "slotsdb"; + } + + @Override + public List getRecords(String channelId, long startTime, long endTime) throws IOException { + return fileObjectProxy.read(channelId, startTime, endTime); + } + + @Override + public void setChannelsToLog(List channels) { + loggingIntervalsById.clear(); + for (LogChannel channel : channels) { + loggingIntervalsById.put(channel.getId(), channel.getLoggingInterval()); + } + } + + @Override + public void log(List containers, long timestamp) { + + for (LogRecordContainer container : containers) { + Double value; + if (container.getRecord().getValue() == null) { + value = Double.NaN; + } else { + try { + value = container.getRecord().getValue().asDouble(); + } catch (TypeConversionException e) { + value = Double.NaN; + } + } + + // Long timestamp = container.getRecord().getTimestamp(); + // if (timestamp == null) { + // timestamp = 0L; + // } + + try { + fileObjectProxy.appendValue(container.getChannelId(), value, timestamp, container.getRecord().getFlag().getCode(), + loggingIntervalsById.get(container.getChannelId())); + } catch (IOException e) { + logger.error("error logging records"); + e.printStackTrace(); + } + } + } } diff --git a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDbVisualizer.java b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDbVisualizer.java index 5c200d93..44d2065d 100644 --- a/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDbVisualizer.java +++ b/projects/datalogger/slotsdb/src/main/java/org/openmuc/framework/datalogger/slotsdb/SlotsDbVisualizer.java @@ -21,96 +21,87 @@ package org.openmuc.framework.datalogger.slotsdb; +import org.openmuc.framework.data.Record; + +import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.Calendar; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; - -import org.openmuc.framework.data.Record; - /** * Class providing a graphical UI to view the content of a .opm file - * */ public final class SlotsDbVisualizer extends JFrame { - private static final long serialVersionUID = 1L; - JFileChooser fc = new JFileChooser(); - File file; - String[][] rowData = { { "0", "0", "0" } }; - String[] columnNames = { "Time", "Value", "State" }; - JTable table = new JTable(rowData, columnNames); - JScrollPane content = new JScrollPane(table); - - public SlotsDbVisualizer() { - - JTextField fileNameField = new JTextField(15); - fileNameField.setEditable(false); - - JMenuBar menuBar = new JMenuBar(); - JMenu fileMenu = new JMenu("File"); - JMenuItem openItem = new JMenuItem("Open"); - openItem.addActionListener(new openFileListener()); - - menuBar.add(fileMenu); - fileMenu.add(openItem); - - setJMenuBar(menuBar); - setContentPane(content); - setTitle(SlotsDb.FILE_EXTENSION + " File Viewer"); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - pack(); - setLocationRelativeTo(null); - - } - - class openFileListener implements ActionListener { - - @Override - public void actionPerformed(ActionEvent e) { - int ret = fc.showOpenDialog(SlotsDbVisualizer.this); - if (ret == JFileChooser.APPROVE_OPTION) { - file = fc.getSelectedFile(); - java.util.List res = null; - try { - FileObject fo = new FileObject(file); - res = fo.readFully(); - } catch (IOException e1) { - e1.printStackTrace(); - } - if (res != null) { - String[][] tblData = new String[res.size()][3]; - Calendar cal = Calendar.getInstance(); - for (int i = 0; i < res.size(); i++) { - cal.setTimeInMillis(res.get(i).getTimestamp()); - - // tblData[i][0] = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(cal.getTime()); - tblData[i][0] = res.get(i).getTimestamp().toString(); - tblData[i][1] = Double.toString(res.get(i).getValue().asDouble()); - tblData[i][2] = Integer.toString(res.get(i).getFlag().getCode()); - } - table = new JTable(tblData, columnNames); - content = new JScrollPane(table); - setContentPane(content); - invalidate(); - validate(); - } - } - } - } - - public static void main(String[] args) { - JFrame window = new SlotsDbVisualizer(); - window.setVisible(true); - } + private static final long serialVersionUID = 1L; + JFileChooser fc = new JFileChooser(); + File file; + String[][] rowData = {{"0", "0", "0"}}; + String[] columnNames = {"Time", "Value", "State"}; + JTable table = new JTable(rowData, columnNames); + JScrollPane content = new JScrollPane(table); + + public SlotsDbVisualizer() { + + JTextField fileNameField = new JTextField(15); + fileNameField.setEditable(false); + + JMenuBar menuBar = new JMenuBar(); + JMenu fileMenu = new JMenu("File"); + JMenuItem openItem = new JMenuItem("Open"); + openItem.addActionListener(new openFileListener()); + + menuBar.add(fileMenu); + fileMenu.add(openItem); + + setJMenuBar(menuBar); + setContentPane(content); + setTitle(SlotsDb.FILE_EXTENSION + " File Viewer"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + pack(); + setLocationRelativeTo(null); + + } + + class openFileListener implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + int ret = fc.showOpenDialog(SlotsDbVisualizer.this); + if (ret == JFileChooser.APPROVE_OPTION) { + file = fc.getSelectedFile(); + java.util.List res = null; + try { + FileObject fo = new FileObject(file); + res = fo.readFully(); + } catch (IOException e1) { + e1.printStackTrace(); + } + if (res != null) { + String[][] tblData = new String[res.size()][3]; + Calendar cal = Calendar.getInstance(); + for (int i = 0; i < res.size(); i++) { + cal.setTimeInMillis(res.get(i).getTimestamp()); + + // tblData[i][0] = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(cal.getTime()); + tblData[i][0] = res.get(i).getTimestamp().toString(); + tblData[i][1] = Double.toString(res.get(i).getValue().asDouble()); + tblData[i][2] = Integer.toString(res.get(i).getFlag().getCode()); + } + table = new JTable(tblData, columnNames); + content = new JScrollPane(table); + setContentPane(content); + invalidate(); + validate(); + } + } + } + } + + public static void main(String[] args) { + JFrame window = new SlotsDbVisualizer(); + window.setVisible(true); + } } diff --git a/projects/datalogger/slotsdb/src/main/resources/OSGI-INF/components.xml b/projects/datalogger/slotsdb/src/main/resources/OSGI-INF/components.xml index ac522c13..89cdfd3e 100644 --- a/projects/datalogger/slotsdb/src/main/resources/OSGI-INF/components.xml +++ b/projects/datalogger/slotsdb/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/aggregator/build.gradle b/projects/driver/aggregator/build.gradle index 2f2e1fac..d478db2f 100644 --- a/projects/driver/aggregator/build.gradle +++ b/projects/driver/aggregator/build.gradle @@ -1,12 +1,12 @@ dependencies { - compile project(':openmuc-core-spi') - compile project(':openmuc-core-api') + compile project(':openmuc-core-spi') + compile project(':openmuc-core-api') } jar { - manifest { - name = "OpenMUC Driver - Aggregator" - instruction 'Service-Component', 'OSGI-INF/components.xml' - instruction 'Export-Package', '' - } + manifest { + name = "OpenMUC Driver - Aggregator" + instruction 'Service-Component', 'OSGI-INF/components.xml' + instruction 'Export-Package', '' + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/Aggregator.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/Aggregator.java index baf51755..33b11292 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/Aggregator.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/Aggregator.java @@ -20,14 +20,7 @@ */ package org.openmuc.framework.driver.aggregator; -import java.io.IOException; -import java.util.List; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.DoubleValue; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; @@ -38,36 +31,33 @@ import org.openmuc.framework.driver.aggregator.exeptions.ChannelNotAccessibleException; import org.openmuc.framework.driver.aggregator.exeptions.SomethingWrongWithRecordException; import org.openmuc.framework.driver.aggregator.exeptions.WrongChannelAddressFormatException; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.DriverDeviceScanListener; -import org.openmuc.framework.driver.spi.DriverService; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; +import org.openmuc.framework.driver.spi.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + /** * Driver which performs aggregation of logged values from a channel. It uses the DriverService and the * DataAccessService. It is therefore a kind of OpenMUC driver/application mix. The aggregator is fully configurable * through the channel config file. - *

    + *

    * Example:
    * Channel A (channelA) is sampled and logged every 10 seconds. - * + *

    *

      * <channelid="channelA">
      *   <samplingInterval>10s</samplingInterval>
      *   <loggingInterval>10s</loggingInterval>
      * </channel>
      * 
    - * - * + *

    + *

    * Now you want a channel B (channelB) which contains the same values as channel A but in a 1 minute resolution by using * the 'average' as aggregation type. You can achieve this by simply adding the aggregator driver to your channel config * file and define a the channel B as follows: - * + *

    *

      * <driver id="aggregator">
      *   <device id="aggregatordevice">
    @@ -79,19 +69,19 @@
      *   </device>
      * </driver>
      * 
    - * + *

    * The new (aggregated) channel has the id channelB. The channel address consists of the channel id of the original * channel and the aggregation type which is channelA:avg in this example. OpenMUC calls the read method of the * aggregator every minute. The aggregator then gets all logged records from channelA of the last minute, calculates the * average and sets this value for the record of channelB. - * - *

    - * + *

    + *

    + *

    * NOTE: It's recommended to specify the samplingTimeOffset for channelB. It should be between samplingIntervalB - * samplingIntervalA and samplingIntervalB. In this example: 50 < offset < 60. This constraint ensures that values are * AGGREGATED CORRECTLY. At hh:mm:55 the aggregator gets the logged values of channelA and at hh:mm:60 respectively * hh:mm:00 the aggregated value is logged. - * + *

    *

      * <driver id="aggregator">
      *   <device id="aggregatordevice">
    @@ -104,256 +94,249 @@
      *   </device>
      * </driver>
      * 
    - * - * */ // TODO: might add an adjustable percentage of errors in records accepted // TODO: works only on double values so far // TODO: some Unit / integration tests whould be nice public class Aggregator implements DriverService, Connection { - private final static Logger logger = LoggerFactory.getLogger(Aggregator.class); - - private DataAccessService dataAccessService; - - protected void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - protected void unsetDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = null; - } - - @Override - public DriverInfo getInfo() { - - String driverId = "aggregator"; - String description = "Is able to aggregate logged values of a channel and writes the aggregated value into a new channel. Different aggregation types supported."; - String deviceAddressSyntax = "not needed"; - String parametersSyntax = "not needed"; - String channelAddressSyntax = ":[:] + \n Supported types: " - + EAggregationType.getSupportedValues(); - String deviceScanParametersSyntax = "not supported"; - - return new DriverInfo(driverId, description, deviceAddressSyntax, parametersSyntax, channelAddressSyntax, - deviceScanParametersSyntax); - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - long currentTimestamp = getCurrentTimestamp(); - long endTimestamp = getEndTimestamp(currentTimestamp); - - for (ChannelRecordContainer container : containers) { - - try { - - Channel aggregatedChannel = container.getChannel(); - AggregatorChannelAddress address = new AggregatorChannelAddress(aggregatedChannel.getChannelAddress()); - - Channel sourceChannel = dataAccessService.getChannel(address.getSourceChannelId()); - checkIfChannelsNotNull(sourceChannel, aggregatedChannel); - - // NOTE: logging, not sampling interval because aggregator accesses logged values - long sourceLoggingInterval = sourceChannel.getLoggingInterval(); - long aggregationInterval = aggregatedChannel.getSamplingInterval(); - long aggregationSamplingTimeOffset = aggregatedChannel.getSamplingTimeOffset(); - checkIntervals(sourceLoggingInterval, aggregationInterval, aggregationSamplingTimeOffset); - - long startTimestamp = currentTimestamp - aggregationInterval; - List records = sourceChannel.getLoggedRecords(startTimestamp, endTimestamp); - - // for debugging - KEEP IT! - // if (records.size() > 0) { - // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); - // for (Record r : records) { - // logger.debug("List records: " + sdf.format(r.getTimestamp()) + " " + r.getValue().asDouble()); - // } - // logger.debug("start: " + sdf.format(startTimestamp) + " timestamp = " + startTimestamp); - // logger.debug("end: " + sdf.format(endTimestamp) + " timestamp = " + endTimestamp); - // logger.debug("List start: " + sdf.format(records.get(0).getTimestamp())); - // logger.debug("List end: " + sdf.format(records.get(records.size() - 1).getTimestamp())); - // } - - checkNumberOfRecords(records, sourceLoggingInterval, aggregationInterval); - - double aggregatedValue = performAggregation(sourceChannel, records, address, aggregatedChannel); - container.setRecord(new Record(new DoubleValue(aggregatedValue), currentTimestamp, Flag.VALID)); - - // for debugging - // logger.debug("set record: " + aggregatedValue + " valid."); - - } catch (WrongChannelAddressFormatException e) { - logger.error("WrongChannelAddressFormatException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } catch (ChannelNotAccessibleException e) { - logger.error("ChannelNotAccessibleException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } catch (DataLoggerNotAvailableException e) { - logger.error("DataLoggerNotAvailableException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } catch (IOException e) { - logger.error("IOException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } catch (SomethingWrongWithRecordException e) { - logger.error("SomethingWrongWithRecordException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } catch (AggregationException e) { - logger.error("AggregationException occurred " + e.getMessage()); - setRecordWithErrorFlag(container, currentTimestamp); - } - - } - return null; - } - - /** - * @return the current timestamp where milliseconds are set to 000: e.g. 10:45:00.015 --> 10:45:00.000 - */ - private long getCurrentTimestamp() { - return (System.currentTimeMillis() / 1000) * 1000; - } - - /** - * endTimestamp must be slightly before the currentTimestamp Example: Aggregate a channel from 10:30:00 to 10:45:00 - * to 15 min values. 10:45:00 should be the timestamp of the aggregated value therefore the aggregator has to get - * logged values from 10:30:00,000 till 10:44:59,999. 10:45:00 is part of the next 15 min interval. - * - * @param currentTimestamp - * @return - */ - private long getEndTimestamp(long currentTimestamp) { - return currentTimestamp - 1; - } - - /** - * Checks limitations of the sampling/aggregating intervals and sourceSamplingOffset - * - * @param sourceLoggingInterval - * @param aggregationInterval - * @param sourceSamplingOffset - * @throws AggregationException - */ - private void checkIntervals(long sourceLoggingInterval, long aggregationInterval, long aggregationSamplingTimeOffset) - throws AggregationException { - - // check 1 - // ------- - if (aggregationInterval < sourceLoggingInterval) { - throw new AggregationException( - "Sampling interval of aggregator channel must be bigger than logging interval of source channel"); - } - - // check 2 - // ------- - long remainder = aggregationInterval % sourceLoggingInterval; - if (remainder != 0) { - throw new AggregationException( - "Sampling interval of aggregator channel must be a multiple of the logging interval of the source channel"); - } - - // check 3 - // ------- - if (sourceLoggingInterval < 1000) { - // FIXME (priority low) milliseconds are cut from the endTimestamp (refer to read method). If the logging - // interval of the source channel is smaller than 1 second this might lead to errors. - throw new AggregationException("Logging interval of source channel musst be >= 1 second"); - } - - } - - private void checkNumberOfRecords(List records, long sourceSamplingInterval, long aggregationInterval) - throws AggregationException { - // The check if intervals are multiples of each other ist done in the checkIntervals Method - long expectedNumberOfRecords = aggregationInterval / sourceSamplingInterval; - - if (records.size() != expectedNumberOfRecords) { - throw new AggregationException("Expected " + expectedNumberOfRecords + " historical records but received " - + records.size()); - } - - } - - private void checkIfChannelsNotNull(Channel sourceChannel, Channel aggregatedChannel) - throws ChannelNotAccessibleException { - - if (aggregatedChannel == null || sourceChannel == null) { - throw new ChannelNotAccessibleException(""); - } - } - - private void setRecordWithErrorFlag(ChannelRecordContainer container, long endTimestamp) { - - container.setRecord(new Record(null, endTimestamp, Flag.DRIVER_ERROR_READ_FAILURE)); - } - - private double performAggregation(Channel sourceChannel, List recordList, AggregatorChannelAddress address, - Channel aggregatedChannel) throws SomethingWrongWithRecordException, WrongChannelAddressFormatException { - - double aggregatedValue; - - switch (address.getAggregationType()) { - case AVG: - aggregatedValue = AggregatorLogic.getAverage(recordList); - break; - case LAST: - aggregatedValue = AggregatorLogic.getLast(recordList); - break; - case DIFF: - aggregatedValue = AggregatorLogic.getDiffBetweenLastAndFirstRecord(recordList); - break; - case PULSES_ENERGY: - aggregatedValue = AggregatorLogic.getPulsesEnergy(sourceChannel, recordList, address, aggregatedChannel); - break; - default: - // TODO not the best exception type - throw new WrongChannelAddressFormatException("Aggregation type: " + address.getAggregationType().name() - + " not implemented yet"); - } - - return aggregatedValue; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ArgumentSyntaxException, ScanException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - // no connection needed so far - return this; - } - - @Override - public void disconnect() { - // no disconnect needed so far - } + private final static Logger logger = LoggerFactory.getLogger(Aggregator.class); + + private DataAccessService dataAccessService; + + protected void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + protected void unsetDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = null; + } + + @Override + public DriverInfo getInfo() { + + String driverId = "aggregator"; + String description = "Is able to aggregate logged values of a channel and writes the aggregated value into a new channel. " + + "Different aggregation types supported."; + String deviceAddressSyntax = "not needed"; + String parametersSyntax = "not needed"; + String channelAddressSyntax = ":[:] + \n Supported types: " + + EAggregationType + .getSupportedValues(); + String deviceScanParametersSyntax = "not supported"; + + return new DriverInfo(driverId, description, deviceAddressSyntax, parametersSyntax, channelAddressSyntax, + deviceScanParametersSyntax); + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + long currentTimestamp = getCurrentTimestamp(); + long endTimestamp = getEndTimestamp(currentTimestamp); + + for (ChannelRecordContainer container : containers) { + + try { + + Channel aggregatedChannel = container.getChannel(); + AggregatorChannelAddress address = new AggregatorChannelAddress(aggregatedChannel.getChannelAddress()); + + Channel sourceChannel = dataAccessService.getChannel(address.getSourceChannelId()); + checkIfChannelsNotNull(sourceChannel, aggregatedChannel); + + // NOTE: logging, not sampling interval because aggregator accesses logged values + long sourceLoggingInterval = sourceChannel.getLoggingInterval(); + long aggregationInterval = aggregatedChannel.getSamplingInterval(); + long aggregationSamplingTimeOffset = aggregatedChannel.getSamplingTimeOffset(); + checkIntervals(sourceLoggingInterval, aggregationInterval, aggregationSamplingTimeOffset); + + long startTimestamp = currentTimestamp - aggregationInterval; + List records = sourceChannel.getLoggedRecords(startTimestamp, endTimestamp); + + // for debugging - KEEP IT! + // if (records.size() > 0) { + // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS"); + // for (Record r : records) { + // logger.debug("List records: " + sdf.format(r.getTimestamp()) + " " + r.getValue().asDouble()); + // } + // logger.debug("start: " + sdf.format(startTimestamp) + " timestamp = " + startTimestamp); + // logger.debug("end: " + sdf.format(endTimestamp) + " timestamp = " + endTimestamp); + // logger.debug("List start: " + sdf.format(records.get(0).getTimestamp())); + // logger.debug("List end: " + sdf.format(records.get(records.size() - 1).getTimestamp())); + // } + + checkNumberOfRecords(records, sourceLoggingInterval, aggregationInterval); + + double aggregatedValue = performAggregation(sourceChannel, records, address, aggregatedChannel); + container.setRecord(new Record(new DoubleValue(aggregatedValue), currentTimestamp, Flag.VALID)); + + // for debugging + // logger.debug("set record: " + aggregatedValue + " valid."); + + } catch (WrongChannelAddressFormatException e) { + logger.error("WrongChannelAddressFormatException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } catch (ChannelNotAccessibleException e) { + logger.error("ChannelNotAccessibleException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } catch (DataLoggerNotAvailableException e) { + logger.error("DataLoggerNotAvailableException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } catch (IOException e) { + logger.error("IOException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } catch (SomethingWrongWithRecordException e) { + logger.error("SomethingWrongWithRecordException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } catch (AggregationException e) { + logger.error("AggregationException occurred " + e.getMessage()); + setRecordWithErrorFlag(container, currentTimestamp); + } + + } + return null; + } + + /** + * @return the current timestamp where milliseconds are set to 000: e.g. 10:45:00.015 --> 10:45:00.000 + */ + private long getCurrentTimestamp() { + return (System.currentTimeMillis() / 1000) * 1000; + } + + /** + * endTimestamp must be slightly before the currentTimestamp Example: Aggregate a channel from 10:30:00 to 10:45:00 + * to 15 min values. 10:45:00 should be the timestamp of the aggregated value therefore the aggregator has to get + * logged values from 10:30:00,000 till 10:44:59,999. 10:45:00 is part of the next 15 min interval. + * + * @param currentTimestamp + * @return + */ + private long getEndTimestamp(long currentTimestamp) { + return currentTimestamp - 1; + } + + /** + * Checks limitations of the sampling/aggregating intervals and sourceSamplingOffset + * + * @param sourceLoggingInterval + * @param aggregationInterval + * @param sourceSamplingOffset + * @throws AggregationException + */ + private void checkIntervals(long sourceLoggingInterval, long aggregationInterval, long aggregationSamplingTimeOffset) throws + AggregationException { + + // check 1 + // ------- + if (aggregationInterval < sourceLoggingInterval) { + throw new AggregationException( + "Sampling interval of aggregator channel must be bigger than logging interval of source channel"); + } + + // check 2 + // ------- + long remainder = aggregationInterval % sourceLoggingInterval; + if (remainder != 0) { + throw new AggregationException( + "Sampling interval of aggregator channel must be a multiple of the logging interval of the source channel"); + } + + // check 3 + // ------- + if (sourceLoggingInterval < 1000) { + // FIXME (priority low) milliseconds are cut from the endTimestamp (refer to read method). If the logging + // interval of the source channel is smaller than 1 second this might lead to errors. + throw new AggregationException("Logging interval of source channel musst be >= 1 second"); + } + + } + + private void checkNumberOfRecords(List records, long sourceSamplingInterval, long aggregationInterval) throws + AggregationException { + // The check if intervals are multiples of each other ist done in the checkIntervals Method + long expectedNumberOfRecords = aggregationInterval / sourceSamplingInterval; + + if (records.size() != expectedNumberOfRecords) { + throw new AggregationException("Expected " + expectedNumberOfRecords + " historical records but received " + records.size()); + } + + } + + private void checkIfChannelsNotNull(Channel sourceChannel, Channel aggregatedChannel) throws ChannelNotAccessibleException { + + if (aggregatedChannel == null || sourceChannel == null) { + throw new ChannelNotAccessibleException(""); + } + } + + private void setRecordWithErrorFlag(ChannelRecordContainer container, long endTimestamp) { + + container.setRecord(new Record(null, endTimestamp, Flag.DRIVER_ERROR_READ_FAILURE)); + } + + private double performAggregation(Channel sourceChannel, List recordList, AggregatorChannelAddress address, Channel + aggregatedChannel) throws SomethingWrongWithRecordException, WrongChannelAddressFormatException { + + double aggregatedValue; + + switch (address.getAggregationType()) { + case AVG: + aggregatedValue = AggregatorLogic.getAverage(recordList); + break; + case LAST: + aggregatedValue = AggregatorLogic.getLast(recordList); + break; + case DIFF: + aggregatedValue = AggregatorLogic.getDiffBetweenLastAndFirstRecord(recordList); + break; + case PULSES_ENERGY: + aggregatedValue = AggregatorLogic.getPulsesEnergy(sourceChannel, recordList, address, aggregatedChannel); + break; + default: + // TODO not the best exception type + throw new WrongChannelAddressFormatException( + "Aggregation type: " + address.getAggregationType().name() + " not implemented yet"); + } + + return aggregatedValue; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + // no connection needed so far + return this; + } + + @Override + public void disconnect() { + // no disconnect needed so far + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorChannelAddress.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorChannelAddress.java index f28973a3..dde75285 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorChannelAddress.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorChannelAddress.java @@ -27,69 +27,68 @@ */ public class AggregatorChannelAddress { - private static final int MAX_ADDRESS_PARTS_LENGTH = 3; - private static final int MIN_ADDRESS_PARTS_LENGTH = 2; - private static final String ADDRESS_SEPARATOR = ":"; + private static final int MAX_ADDRESS_PARTS_LENGTH = 3; + private static final int MIN_ADDRESS_PARTS_LENGTH = 2; + private static final String ADDRESS_SEPARATOR = ":"; - private static final int ADDRESS_SOURCECHANNELID_INDEX = 0; - private static final int ADDRESS_AGGREGATIONTYPE_INDEX = 1; - private static final int ADDRESS_OPTIONAL_SETIING_INDEX = 2; + private static final int ADDRESS_SOURCECHANNELID_INDEX = 0; + private static final int ADDRESS_AGGREGATIONTYPE_INDEX = 1; + private static final int ADDRESS_OPTIONAL_SETIING_INDEX = 2; - private EAggregationType aggregationType; - private String sourceChannelId; - private double optionalSetting; + private EAggregationType aggregationType; + private String sourceChannelId; + private double optionalSetting; - public AggregatorChannelAddress(String address) throws WrongChannelAddressFormatException { + public AggregatorChannelAddress(String address) throws WrongChannelAddressFormatException { - String[] addressParts = address.split(ADDRESS_SEPARATOR); - int addressPartsLength = addressParts.length; + String[] addressParts = address.split(ADDRESS_SEPARATOR); + int addressPartsLength = addressParts.length; - if (addressPartsLength <= MAX_ADDRESS_PARTS_LENGTH && addressPartsLength >= MIN_ADDRESS_PARTS_LENGTH) { - sourceChannelId = addressParts[ADDRESS_SOURCECHANNELID_INDEX]; - aggregationType = parseAggregationType(addressParts[ADDRESS_AGGREGATIONTYPE_INDEX]); + if (addressPartsLength <= MAX_ADDRESS_PARTS_LENGTH && addressPartsLength >= MIN_ADDRESS_PARTS_LENGTH) { + sourceChannelId = addressParts[ADDRESS_SOURCECHANNELID_INDEX]; + aggregationType = parseAggregationType(addressParts[ADDRESS_AGGREGATIONTYPE_INDEX]); - if (addressPartsLength == ADDRESS_OPTIONAL_SETIING_INDEX + 1) { - optionalSetting = parseOptionalSetting(addressParts[ADDRESS_OPTIONAL_SETIING_INDEX]); - } - } - else { - throw new WrongChannelAddressFormatException(""); - } + if (addressPartsLength == ADDRESS_OPTIONAL_SETIING_INDEX + 1) { + optionalSetting = parseOptionalSetting(addressParts[ADDRESS_OPTIONAL_SETIING_INDEX]); + } + } else { + throw new WrongChannelAddressFormatException(""); + } - } + } - private EAggregationType parseAggregationType(String typeAsString) throws WrongChannelAddressFormatException { + private EAggregationType parseAggregationType(String typeAsString) throws WrongChannelAddressFormatException { - EAggregationType type = EAggregationType.getEnumfromString(typeAsString); - if (type == null) { - throw new WrongChannelAddressFormatException("Aggregation type: " + typeAsString + " not supported."); - } - return type; - } + EAggregationType type = EAggregationType.getEnumfromString(typeAsString); + if (type == null) { + throw new WrongChannelAddressFormatException("Aggregation type: " + typeAsString + " not supported."); + } + return type; + } - private Double parseOptionalSetting(String optionalSettingAsString) throws WrongChannelAddressFormatException { + private Double parseOptionalSetting(String optionalSettingAsString) throws WrongChannelAddressFormatException { - Double optionalSetting = Double.parseDouble(optionalSettingAsString); - if (optionalSetting == null) { - throw new WrongChannelAddressFormatException("Optional setting: " + optionalSettingAsString - + " not supported. Is not a long number"); - } - return optionalSetting; - } + Double optionalSetting = Double.parseDouble(optionalSettingAsString); + if (optionalSetting == null) { + throw new WrongChannelAddressFormatException( + "Optional setting: " + optionalSettingAsString + " not supported. Is not a long number"); + } + return optionalSetting; + } - public EAggregationType getAggregationType() { + public EAggregationType getAggregationType() { - return aggregationType; - } + return aggregationType; + } - public String getSourceChannelId() { + public String getSourceChannelId() { - return sourceChannelId; - } + return sourceChannelId; + } - public double getOptionalSeting() { + public double getOptionalSeting() { - return optionalSetting; - } + return optionalSetting; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorLogic.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorLogic.java index aa5a0d52..29fd5dc9 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorLogic.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorLogic.java @@ -20,139 +20,129 @@ */ package org.openmuc.framework.driver.aggregator; -import java.util.List; - import org.openmuc.framework.data.Record; import org.openmuc.framework.dataaccess.Channel; import org.openmuc.framework.driver.aggregator.exeptions.SomethingWrongWithRecordException; import org.openmuc.framework.driver.aggregator.exeptions.WrongChannelAddressFormatException; +import java.util.List; + /** * Provides static methods which perform the aggregation according to the aggregation type. */ public class AggregatorLogic { - final static double SHORT_MAX = 65535.0; - - /** - * Calculates the average of the all records - * - * @param recordList - * @return the average - * @throws SomethingWrongWithRecordException - */ - public static double getAverage(List recordList) throws SomethingWrongWithRecordException { - - double sum = 0; - - for (Record record : recordList) { - sum = sum + AggregatorUtil.getDoubleRecordValue(record); - } - - double average = sum / recordList.size(); - - return average; - } - - /** - * Returns the value of the last record of the list - *

    - * Can be used for energy aggregation. Smart meter sums the energy automatically therefore the last value contains - * the aggregated value - * - * @param recordList - * @return the value of the last record of the list - * @throws SomethingWrongWithRecordException - */ - public static double getLast(List recordList) throws SomethingWrongWithRecordException { - return AggregatorUtil.getDoubleRecordValue(getLastRecordOfList(recordList)); - } - - /** - * Calculates the difference between the last and first value of the list. - *

    - * Can be used to determine the energy per interval - * - * @param recordList - * @return the difference - * @throws SomethingWrongWithRecordException - */ - public static double getDiffBetweenLastAndFirstRecord(List recordList) - throws SomethingWrongWithRecordException { - - if (recordList.size() < 2) { - throw new SomethingWrongWithRecordException( - "List holds less than 2 records, calculation of difference not possible."); - } - - double end = AggregatorUtil.getDoubleRecordValue(getLastRecordOfList(recordList)); - double start = AggregatorUtil.getDoubleRecordValue(recordList.get(0)); - double diff = end - start; - return diff; - } - - public static double getPulsesEnergy(Channel sourceChannel, List recordList, - AggregatorChannelAddress address, Channel aggregatedChannel) throws SomethingWrongWithRecordException, - WrongChannelAddressFormatException { - - double aggregatedValue; - double pulsesPerWh = address.getOptionalSeting(); - if (pulsesPerWh > 0) { - aggregatedValue = AggregatorLogic.getImpulsValue(sourceChannel, recordList, - aggregatedChannel.getSamplingInterval(), pulsesPerWh); - } - else { - throw new WrongChannelAddressFormatException( - "optionalLongSetting (pulses per Wh) has to be greater then 0."); - } - - return aggregatedValue; - } - - private static double getImpulsValue(Channel sourceChannel, List recordList, long samplingInterval, - double pulsesPerX) throws SomethingWrongWithRecordException { - - if (recordList.size() < 1) { - throw new SomethingWrongWithRecordException( - "List holds less than 1 records, calculation of pulses not possible."); - } - - Record lastRecord = getLastRecordOfList(recordList); - double past = AggregatorUtil.getDoubleRecordValue(lastRecord); - double actual = AggregatorUtil.getWaitForLatestRecordValue(sourceChannel, lastRecord); - double power = calcPulsesValue(actual, past, pulsesPerX, samplingInterval); - return power; - } - - private static Record getLastRecordOfList(List recordList) throws SomethingWrongWithRecordException { - - if (recordList.isEmpty()) { - throw new SomethingWrongWithRecordException("Empty record list."); - } - else if (recordList.size() == 1) { - // only one record in list which is automatically the last one. - return recordList.get(0); - } - else { - return recordList.get(recordList.size() - 1); - } - } - - private static double calcPulsesValue(double actualPulses, double pulsesHist, double pulsesPerX, - long loggingInterval) { - - double power; - double pulses = actualPulses - pulsesHist; - - if (pulses >= 0.0) { - pulses = actualPulses - pulsesHist; - } - else { - pulses = (SHORT_MAX - pulsesHist) + actualPulses; - } - power = pulses / pulsesPerX * (loggingInterval / 1000.); - - return power; - } + final static double SHORT_MAX = 65535.0; + + /** + * Calculates the average of the all records + * + * @param recordList + * @return the average + * @throws SomethingWrongWithRecordException + */ + public static double getAverage(List recordList) throws SomethingWrongWithRecordException { + + double sum = 0; + + for (Record record : recordList) { + sum = sum + AggregatorUtil.getDoubleRecordValue(record); + } + + double average = sum / recordList.size(); + + return average; + } + + /** + * Returns the value of the last record of the list + *

    + * Can be used for energy aggregation. Smart meter sums the energy automatically therefore the last value contains + * the aggregated value + * + * @param recordList + * @return the value of the last record of the list + * @throws SomethingWrongWithRecordException + */ + public static double getLast(List recordList) throws SomethingWrongWithRecordException { + return AggregatorUtil.getDoubleRecordValue(getLastRecordOfList(recordList)); + } + + /** + * Calculates the difference between the last and first value of the list. + *

    + * Can be used to determine the energy per interval + * + * @param recordList + * @return the difference + * @throws SomethingWrongWithRecordException + */ + public static double getDiffBetweenLastAndFirstRecord(List recordList) throws SomethingWrongWithRecordException { + + if (recordList.size() < 2) { + throw new SomethingWrongWithRecordException("List holds less than 2 records, calculation of difference not possible."); + } + + double end = AggregatorUtil.getDoubleRecordValue(getLastRecordOfList(recordList)); + double start = AggregatorUtil.getDoubleRecordValue(recordList.get(0)); + double diff = end - start; + return diff; + } + + public static double getPulsesEnergy(Channel sourceChannel, List recordList, AggregatorChannelAddress address, Channel + aggregatedChannel) throws SomethingWrongWithRecordException, WrongChannelAddressFormatException { + + double aggregatedValue; + double pulsesPerWh = address.getOptionalSeting(); + if (pulsesPerWh > 0) { + aggregatedValue = AggregatorLogic + .getImpulsValue(sourceChannel, recordList, aggregatedChannel.getSamplingInterval(), pulsesPerWh); + } else { + throw new WrongChannelAddressFormatException("optionalLongSetting (pulses per Wh) has to be greater then 0."); + } + + return aggregatedValue; + } + + private static double getImpulsValue(Channel sourceChannel, List recordList, long samplingInterval, double pulsesPerX) throws + SomethingWrongWithRecordException { + + if (recordList.size() < 1) { + throw new SomethingWrongWithRecordException("List holds less than 1 records, calculation of pulses not possible."); + } + + Record lastRecord = getLastRecordOfList(recordList); + double past = AggregatorUtil.getDoubleRecordValue(lastRecord); + double actual = AggregatorUtil.getWaitForLatestRecordValue(sourceChannel, lastRecord); + double power = calcPulsesValue(actual, past, pulsesPerX, samplingInterval); + return power; + } + + private static Record getLastRecordOfList(List recordList) throws SomethingWrongWithRecordException { + + if (recordList.isEmpty()) { + throw new SomethingWrongWithRecordException("Empty record list."); + } else if (recordList.size() == 1) { + // only one record in list which is automatically the last one. + return recordList.get(0); + } else { + return recordList.get(recordList.size() - 1); + } + } + + private static double calcPulsesValue(double actualPulses, double pulsesHist, double pulsesPerX, long loggingInterval) { + + double power; + double pulses = actualPulses - pulsesHist; + + if (pulses >= 0.0) { + pulses = actualPulses - pulsesHist; + } else { + pulses = (SHORT_MAX - pulsesHist) + actualPulses; + } + power = pulses / pulsesPerX * (loggingInterval / 1000.); + + return power; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorUtil.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorUtil.java index 29f73143..05f6e969 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorUtil.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/AggregatorUtil.java @@ -31,56 +31,53 @@ */ public class AggregatorUtil { - /** - * Performs some tests on the record and returns its value as double on success
    - * - tests if record != null
    - * - tests if flag is valid
    - * - tests if value != null
    - * - * @param record - * @return the value as double - * @throws SomethingWrongWithRecordException - */ - public static double getDoubleRecordValue(Record record) throws SomethingWrongWithRecordException { + /** + * Performs some tests on the record and returns its value as double on success
    + * - tests if record != null
    + * - tests if flag is valid
    + * - tests if value != null
    + * + * @param record + * @return the value as double + * @throws SomethingWrongWithRecordException + */ + public static double getDoubleRecordValue(Record record) throws SomethingWrongWithRecordException { - double result; + double result; - if (record != null) { - Flag flag = record.getFlag(); - if (flag == Flag.VALID) { - Value value = record.getValue(); - if (value != null) { - result = value.asDouble(); - } - else { - throw new SomethingWrongWithRecordException("Value is null"); - } - } - else { - throw new SomethingWrongWithRecordException("Flag != Valid - " + flag.toString()); - } - } - else { - throw new SomethingWrongWithRecordException("Record is null"); - } + if (record != null) { + Flag flag = record.getFlag(); + if (flag == Flag.VALID) { + Value value = record.getValue(); + if (value != null) { + result = value.asDouble(); + } else { + throw new SomethingWrongWithRecordException("Value is null"); + } + } else { + throw new SomethingWrongWithRecordException("Flag != Valid - " + flag.toString()); + } + } else { + throw new SomethingWrongWithRecordException("Record is null"); + } - return result; - } + return result; + } - public static double getWaitForLatestRecordValue(Channel sourceChannel, Record lastRecord) { + public static double getWaitForLatestRecordValue(Channel sourceChannel, Record lastRecord) { - double returnValue; + double returnValue; - do { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } while (sourceChannel.getLatestRecord().getTimestamp().equals(lastRecord.getTimestamp())); + do { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } while (sourceChannel.getLatestRecord().getTimestamp().equals(lastRecord.getTimestamp())); - returnValue = sourceChannel.getLatestRecord().getValue().asDouble(); - return returnValue; - } + returnValue = sourceChannel.getLatestRecord().getValue().asDouble(); + return returnValue; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/EAggregationType.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/EAggregationType.java index 3b4677b2..0bc3f2c5 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/EAggregationType.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/EAggregationType.java @@ -20,73 +20,72 @@ */ package org.openmuc.framework.driver.aggregator; -import java.util.Locale; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Locale; + /** * Enum which defines the aggregation types - * */ public enum EAggregationType { - AVG, // - LAST, // - DIFF, // - PULSES_ENERGY; // + AVG, // + LAST, // + DIFF, // + PULSES_ENERGY; // - private final static Logger logger = LoggerFactory.getLogger(EAggregationType.class); + private final static Logger logger = LoggerFactory.getLogger(EAggregationType.class); - /** - * Parses the name of the aggregation type to the corresponding aggregation type object - * - * @param enumAsString - * @return aggregation type object on success, otherwise null - */ - public static EAggregationType getEnumfromString(String enumAsString) { - EAggregationType returnValue = null; - if (enumAsString != null) { - for (EAggregationType value : EAggregationType.values()) { - if (enumAsString.equalsIgnoreCase(value.toString())) { - returnValue = EAggregationType.valueOf(enumAsString.toUpperCase(Locale.ENGLISH)); - break; - } - } - } - if (returnValue == null) { - logger.error(enumAsString + " is not supported. Use one of the following values: " + getSupportedValues()); - } - return returnValue; - } + /** + * Parses the name of the aggregation type to the corresponding aggregation type object + * + * @param enumAsString + * @return aggregation type object on success, otherwise null + */ + public static EAggregationType getEnumfromString(String enumAsString) { + EAggregationType returnValue = null; + if (enumAsString != null) { + for (EAggregationType value : EAggregationType.values()) { + if (enumAsString.equalsIgnoreCase(value.toString())) { + returnValue = EAggregationType.valueOf(enumAsString.toUpperCase(Locale.ENGLISH)); + break; + } + } + } + if (returnValue == null) { + logger.error(enumAsString + " is not supported. Use one of the following values: " + getSupportedValues()); + } + return returnValue; + } - /** - * @return all supported values as a comma separated string. - */ - public static String getSupportedValues() { - StringBuilder supported = new StringBuilder(); - for (EAggregationType value : EAggregationType.values()) { - supported.append(value.toString()); - supported.append(", "); - } - return supported.toString(); - } + /** + * @return all supported values as a comma separated string. + */ + public static String getSupportedValues() { + StringBuilder supported = new StringBuilder(); + for (EAggregationType value : EAggregationType.values()) { + supported.append(value.toString()); + supported.append(", "); + } + return supported.toString(); + } - /** - * Checks if the string matches with one of the enum values. - * - * @param enumAsString - * @return true on success, otherwise false - */ - public static boolean isValidValue(String enumAsString) { - boolean returnValue = false; - for (EAggregationType type : EAggregationType.values()) { - if (type.toString().equalsIgnoreCase(enumAsString)) { - returnValue = true; - break; - } - } - return returnValue; - } + /** + * Checks if the string matches with one of the enum values. + * + * @param enumAsString + * @return true on success, otherwise false + */ + public static boolean isValidValue(String enumAsString) { + boolean returnValue = false; + for (EAggregationType type : EAggregationType.values()) { + if (type.toString().equalsIgnoreCase(enumAsString)) { + returnValue = true; + break; + } + } + return returnValue; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/AggregationException.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/AggregationException.java index 62b83627..932973b8 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/AggregationException.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/AggregationException.java @@ -22,14 +22,14 @@ public class AggregationException extends Exception { - private final String message; + private final String message; - public AggregationException(String message) { - this.message = message; - } + public AggregationException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/ChannelNotAccessibleException.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/ChannelNotAccessibleException.java index 36d0fb01..ccebf741 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/ChannelNotAccessibleException.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/ChannelNotAccessibleException.java @@ -22,14 +22,14 @@ public class ChannelNotAccessibleException extends Exception { - private final String message; + private final String message; - public ChannelNotAccessibleException(String message) { - this.message = message; - } + public ChannelNotAccessibleException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/RecordsWithNullAsValueException.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/RecordsWithNullAsValueException.java index 4d149e56..311008ef 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/RecordsWithNullAsValueException.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/RecordsWithNullAsValueException.java @@ -22,14 +22,14 @@ public class RecordsWithNullAsValueException extends Exception { - private final String message; + private final String message; - public RecordsWithNullAsValueException(String message) { - this.message = message; - } + public RecordsWithNullAsValueException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/SomethingWrongWithRecordException.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/SomethingWrongWithRecordException.java index 8402af71..045fead4 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/SomethingWrongWithRecordException.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/SomethingWrongWithRecordException.java @@ -22,14 +22,14 @@ public class SomethingWrongWithRecordException extends Exception { - private final String message; + private final String message; - public SomethingWrongWithRecordException(String message) { - this.message = message; - } + public SomethingWrongWithRecordException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/WrongChannelAddressFormatException.java b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/WrongChannelAddressFormatException.java index ae20c66d..255f307f 100644 --- a/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/WrongChannelAddressFormatException.java +++ b/projects/driver/aggregator/src/main/java/org/openmuc/framework/driver/aggregator/exeptions/WrongChannelAddressFormatException.java @@ -22,14 +22,14 @@ public class WrongChannelAddressFormatException extends Exception { - private final String message; + private final String message; - public WrongChannelAddressFormatException(String message) { - this.message = message; - } + public WrongChannelAddressFormatException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/aggregator/src/main/resources/OSGI-INF/components.xml b/projects/driver/aggregator/src/main/resources/OSGI-INF/components.xml index 9afaafca..9a45d6ab 100644 --- a/projects/driver/aggregator/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/aggregator/src/main/resources/OSGI-INF/components.xml @@ -1,11 +1,11 @@ - - - - + + + + + interface="org.openmuc.framework.dataaccess.DataAccessService" + bind="setDataAccessService" + unbind="unsetDataAccessService"/> diff --git a/projects/driver/dlms/build.gradle b/projects/driver/dlms/build.gradle index 304fe856..ced8f7cd 100644 --- a/projects/driver/dlms/build.gradle +++ b/projects/driver/dlms/build.gradle @@ -1,29 +1,28 @@ - configurations.create('embed') def jdlmsversion = "0.9.1-SNAPSHOT" def jasn1berversion = "1.3" dependencies { - compile project(':openmuc-core-spi') - compile group: 'org.openmuc.jdlms', name: 'jdlms', version: jdlmsversion - - embed group: 'org.openmuc.jdlms', name: 'jdlms', version: jdlmsversion - embed group: 'org.openmuc', name: 'jasn1-ber', version: jasn1berversion + compile project(':openmuc-core-spi') + compile group: 'org.openmuc.jdlms', name: 'jdlms', version: jdlmsversion + + embed group: 'org.openmuc.jdlms', name: 'jdlms', version: jdlmsversion + embed group: 'org.openmuc', name: 'jasn1-ber', version: jasn1berversion } jar { - manifest { - name = "OpenMUC Driver - DLMS/COSEM" - instruction 'Bundle-ClassPath', '.,lib/jdlms-' + jdlmsversion + '.jar, lib/jasn1-ber-' + jasn1berversion + '.jar' - instruction 'Export-Package', '' - instruction 'Import-Package', '!org.openmuc.jdlms*,!org.openmuc.jasn1*,gnu.io,*' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - DLMS/COSEM" + instruction 'Bundle-ClassPath', '.,lib/jdlms-' + jdlmsversion + '.jar, lib/jasn1-ber-' + jasn1berversion + '.jar' + instruction 'Export-Package', '' + instruction 'Import-Package', '!org.openmuc.jdlms*,!org.openmuc.jasn1*,gnu.io,*' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/AddressParser.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/AddressParser.java index 0e027fc0..a2596bee 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/AddressParser.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/AddressParser.java @@ -20,10 +20,6 @@ */ package org.openmuc.driver.dlms; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.jdlms.client.ClientConnectionSettings; import org.openmuc.jdlms.client.ClientConnectionSettings.Authentication; @@ -33,156 +29,153 @@ import org.openmuc.jdlms.client.ip.TcpClientConnectionSettings; import org.openmuc.jdlms.client.ip.UdpClientConnectionSettings; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + public class AddressParser { - public ClientConnectionSettings parse(String deviceAddress, SettingsHelper settings) - throws UnknownHostException, ArgumentSyntaxException { - - String[] deviceTokens = deviceAddress.split(":"); - - if (deviceTokens.length < 4 || deviceTokens.length > 5) { - throw new ArgumentSyntaxException("Device address has less than 4 or more than 5 parameters."); - } - - String protocol = deviceTokens[0].toLowerCase(); - - ClientConnectionSettings result = null; - - ReferencingMethod referencing = ReferencingMethod.LN; - - referencing = ReferencingMethod.valueOf(settings.getReferencing()); - - String oldInterfaceAddress; - String oldDeviceAddress; - if (deviceTokens.length == 4) { - oldInterfaceAddress = deviceTokens[0] + ":" + deviceTokens[1]; - oldDeviceAddress = deviceTokens[2] + ":" + deviceTokens[3]; - } - else { - oldInterfaceAddress = deviceTokens[0] + ":" + deviceTokens[1] + ":" + deviceTokens[2]; - oldDeviceAddress = deviceTokens[3] + ":" + deviceTokens[4]; - } - - if (protocol.equals("hdlc")) { - result = parseHdlc(oldInterfaceAddress, oldDeviceAddress, referencing, settings); - } - else if (protocol.equals("udp")) { - result = parseUdp(oldInterfaceAddress, oldDeviceAddress, referencing, settings); - } - else if (protocol.equals("tcp")) { - result = parseTcp(oldInterfaceAddress, oldDeviceAddress, referencing, settings); - } - - if (settings.getPassword() != null) { - result.setAuthentication(Authentication.LOW); - } - - return result; - } - - private HdlcClientConnectionSettings parseHdlc(String interfaceAddress, String deviceAddress, - ReferencingMethod referencing, SettingsHelper settings) { - HdlcClientConnectionSettings result = null; - - String[] interfaceTokens = interfaceAddress.split(":"); - String[] deviceTokens = deviceAddress.split(":"); - - if (interfaceTokens.length < 2 || interfaceTokens.length > 3) { - throw new IllegalArgumentException( - "InterfaceAddress has unknown format. Use hdlc:port[:serverPhysical] as pattern"); - } - if (deviceTokens.length != 2) { - throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverLogical:clientLogical"); - } - - String serialPort = interfaceTokens[1]; - HdlcAddress clientAddress = new HdlcAddress(Integer.parseInt(deviceTokens[1])); - HdlcAddress serverAddress = null; - - if (interfaceTokens.length == 2) { - serverAddress = new HdlcAddress(Integer.parseInt(deviceTokens[0])); - } - else { - int logical = Integer.parseInt(deviceTokens[0]); - int physical = Integer.parseInt(interfaceTokens[2]); - - int addressSize = 2; - if (logical > 127 || physical > 127) { - addressSize = 4; - } - - serverAddress = new HdlcAddress(logical, physical, addressSize); - } - - if (clientAddress.isValidAddress() == false) { - throw new IllegalArgumentException("Client logical address must be in range [1, 127]"); - } - if (serverAddress.isValidAddress() == false) { - throw new IllegalArgumentException("Server address is invalid"); - } - - boolean useHandshake = settings.useHandshake(); - int baudrate = settings.getBaudrate(); - - result = new HdlcClientConnectionSettings(serialPort, clientAddress, serverAddress, referencing).setBaudrate( - baudrate).setUseHandshake(useHandshake); - - return result; - } - - private UdpClientConnectionSettings parseUdp(String interfaceAddress, String deviceAddress, - ReferencingMethod referencing, SettingsHelper settings) throws UnknownHostException { - UdpClientConnectionSettings result = null; - - String[] interfaceTokens = interfaceAddress.split(":"); - String[] deviceTokens = deviceAddress.split(":"); - - if (interfaceTokens.length < 2 && interfaceTokens.length > 3) { - throw new IllegalArgumentException( - "InterfaceAddress has unknown format. Use udp:serverIp[:serverPort] as a pattern"); - } - if (deviceTokens.length != 2) { - throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverWPort:clientWPort"); - } - - int serverPort = 4059; - if (interfaceTokens.length == 3) { - serverPort = Integer.parseInt(interfaceTokens[2]); - } - int clientWPort = Integer.parseInt(deviceTokens[1]); - InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName(interfaceTokens[1]), serverPort); - int serverWPort = Integer.parseInt(deviceTokens[0]); - - result = new UdpClientConnectionSettings(serverAddress, serverWPort, clientWPort, referencing); - - return result; - } - - private TcpClientConnectionSettings parseTcp(String interfaceAddress, String deviceAddress, - ReferencingMethod referencing, SettingsHelper settings) throws UnknownHostException { - TcpClientConnectionSettings result = null; - - String[] interfaceTokens = interfaceAddress.split(":"); - String[] deviceTokens = deviceAddress.split(":"); - - if (interfaceTokens.length < 2 && interfaceTokens.length > 3) { - throw new IllegalArgumentException( - "InterfaceAddress has unknown format. Use tcp:serverIp[:serverPort] as a pattern"); - } - if (deviceTokens.length != 2) { - throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverWPort:clientWPort"); - } - - int serverPort = 4059; - if (interfaceTokens.length == 3) { - serverPort = Integer.parseInt(interfaceTokens[2]); - } - int clientWPort = Integer.parseInt(deviceTokens[1]); - InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName(interfaceTokens[1]), serverPort); - int serverWPort = Integer.parseInt(deviceTokens[0]); - - result = new TcpClientConnectionSettings(serverAddress, serverWPort, clientWPort, referencing); - - return result; - } + public ClientConnectionSettings parse(String deviceAddress, SettingsHelper settings) throws UnknownHostException, + ArgumentSyntaxException { + + String[] deviceTokens = deviceAddress.split(":"); + + if (deviceTokens.length < 4 || deviceTokens.length > 5) { + throw new ArgumentSyntaxException("Device address has less than 4 or more than 5 parameters."); + } + + String protocol = deviceTokens[0].toLowerCase(); + + ClientConnectionSettings result = null; + + ReferencingMethod referencing = ReferencingMethod.LN; + + referencing = ReferencingMethod.valueOf(settings.getReferencing()); + + String oldInterfaceAddress; + String oldDeviceAddress; + if (deviceTokens.length == 4) { + oldInterfaceAddress = deviceTokens[0] + ":" + deviceTokens[1]; + oldDeviceAddress = deviceTokens[2] + ":" + deviceTokens[3]; + } else { + oldInterfaceAddress = deviceTokens[0] + ":" + deviceTokens[1] + ":" + deviceTokens[2]; + oldDeviceAddress = deviceTokens[3] + ":" + deviceTokens[4]; + } + + if (protocol.equals("hdlc")) { + result = parseHdlc(oldInterfaceAddress, oldDeviceAddress, referencing, settings); + } else if (protocol.equals("udp")) { + result = parseUdp(oldInterfaceAddress, oldDeviceAddress, referencing, settings); + } else if (protocol.equals("tcp")) { + result = parseTcp(oldInterfaceAddress, oldDeviceAddress, referencing, settings); + } + + if (settings.getPassword() != null) { + result.setAuthentication(Authentication.LOW); + } + + return result; + } + + private HdlcClientConnectionSettings parseHdlc(String interfaceAddress, String deviceAddress, ReferencingMethod referencing, + SettingsHelper settings) { + HdlcClientConnectionSettings result = null; + + String[] interfaceTokens = interfaceAddress.split(":"); + String[] deviceTokens = deviceAddress.split(":"); + + if (interfaceTokens.length < 2 || interfaceTokens.length > 3) { + throw new IllegalArgumentException("InterfaceAddress has unknown format. Use hdlc:port[:serverPhysical] as pattern"); + } + if (deviceTokens.length != 2) { + throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverLogical:clientLogical"); + } + + String serialPort = interfaceTokens[1]; + HdlcAddress clientAddress = new HdlcAddress(Integer.parseInt(deviceTokens[1])); + HdlcAddress serverAddress = null; + + if (interfaceTokens.length == 2) { + serverAddress = new HdlcAddress(Integer.parseInt(deviceTokens[0])); + } else { + int logical = Integer.parseInt(deviceTokens[0]); + int physical = Integer.parseInt(interfaceTokens[2]); + + int addressSize = 2; + if (logical > 127 || physical > 127) { + addressSize = 4; + } + + serverAddress = new HdlcAddress(logical, physical, addressSize); + } + + if (clientAddress.isValidAddress() == false) { + throw new IllegalArgumentException("Client logical address must be in range [1, 127]"); + } + if (serverAddress.isValidAddress() == false) { + throw new IllegalArgumentException("Server address is invalid"); + } + + boolean useHandshake = settings.useHandshake(); + int baudrate = settings.getBaudrate(); + + result = new HdlcClientConnectionSettings(serialPort, clientAddress, serverAddress, referencing).setBaudrate(baudrate) + .setUseHandshake(useHandshake); + + return result; + } + + private UdpClientConnectionSettings parseUdp(String interfaceAddress, String deviceAddress, ReferencingMethod referencing, + SettingsHelper settings) throws UnknownHostException { + UdpClientConnectionSettings result = null; + + String[] interfaceTokens = interfaceAddress.split(":"); + String[] deviceTokens = deviceAddress.split(":"); + + if (interfaceTokens.length < 2 && interfaceTokens.length > 3) { + throw new IllegalArgumentException("InterfaceAddress has unknown format. Use udp:serverIp[:serverPort] as a pattern"); + } + if (deviceTokens.length != 2) { + throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverWPort:clientWPort"); + } + + int serverPort = 4059; + if (interfaceTokens.length == 3) { + serverPort = Integer.parseInt(interfaceTokens[2]); + } + int clientWPort = Integer.parseInt(deviceTokens[1]); + InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName(interfaceTokens[1]), serverPort); + int serverWPort = Integer.parseInt(deviceTokens[0]); + + result = new UdpClientConnectionSettings(serverAddress, serverWPort, clientWPort, referencing); + + return result; + } + + private TcpClientConnectionSettings parseTcp(String interfaceAddress, String deviceAddress, ReferencingMethod referencing, + SettingsHelper settings) throws UnknownHostException { + TcpClientConnectionSettings result = null; + + String[] interfaceTokens = interfaceAddress.split(":"); + String[] deviceTokens = deviceAddress.split(":"); + + if (interfaceTokens.length < 2 && interfaceTokens.length > 3) { + throw new IllegalArgumentException("InterfaceAddress has unknown format. Use tcp:serverIp[:serverPort] as a pattern"); + } + if (deviceTokens.length != 2) { + throw new IllegalArgumentException("DeviceAddress has unknown format. Use serverWPort:clientWPort"); + } + + int serverPort = 4059; + if (interfaceTokens.length == 3) { + serverPort = Integer.parseInt(interfaceTokens[2]); + } + int clientWPort = Integer.parseInt(deviceTokens[1]); + InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName(interfaceTokens[1]), serverPort); + int serverWPort = Integer.parseInt(deviceTokens[0]); + + result = new TcpClientConnectionSettings(serverAddress, serverWPort, clientWPort, referencing); + + return result; + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/ChannelAddress.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/ChannelAddress.java index ed0a5671..6c146a5b 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/ChannelAddress.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/ChannelAddress.java @@ -25,92 +25,88 @@ public class ChannelAddress { - private final int classId; - private final ObisCode instanceId; - private final String printableInstanceId; - private final int attributeId; - - public ChannelAddress(int classId, String instanceId, int attributeId) { - this.classId = classId; - printableInstanceId = instanceId; - this.instanceId = parseInstanceId(instanceId); - this.attributeId = attributeId; - } - - public ChannelAddress(int classId, byte[] instanceId, int attributeId) { - this.classId = classId; - printableInstanceId = parseInstanceId(instanceId); - this.instanceId = parseInstanceId(printableInstanceId); - this.attributeId = attributeId; - } - - public static ChannelAddress parse(String input) { - String[] tokens = input.split("/"); - if (tokens.length != 3) { - throw new IllegalArgumentException("Channel address must be of format 'classId/logicalName/attributeId'"); - } - - int classId = Integer.parseInt(tokens[0]); - int attributeId = Integer.parseInt(tokens[2]); - String instanceId = tokens[1]; - - return new ChannelAddress(classId, instanceId, attributeId); - } - - private static ObisCode parseInstanceId(String idString) { - ObisCode result = null; - - String tokens[] = idString.split("\\."); - - if (tokens.length == 1 && idString.length() == 12) { - byte instanceId[] = new byte[6]; - for (int i = 0; i < idString.length(); i += 2) { - instanceId[i / 2] = (byte) Integer.parseInt(idString.substring(i, i + 2), 16); - } - result = new ObisCode(instanceId[0], instanceId[1], instanceId[2], instanceId[3], instanceId[4], - instanceId[5]); - } - else if (tokens.length == 6) { - result = new ObisCode(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), - Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[4]), - Integer.parseInt(tokens[5])); - } - else { - throw new IllegalArgumentException("Reduced ID codes are not supported"); - } - - return result; - } - - private static String parseInstanceId(byte[] instanceId) { - StringBuilder result = new StringBuilder(); - - result.append(Integer.toString(instanceId[0] & 0xff)); - for (int i = 1; i < instanceId.length; i++) { - result.append(".").append(Integer.toString(instanceId[i] & 0xff)); - } - - return result.toString(); - } - - public int getClassId() { - return classId; - } - - public ObisCode getInstanceId() { - return instanceId; - } - - public int getAttributeId() { - return attributeId; - } - - public GetRequest createGetRequest() { - return new GetRequest(classId, instanceId, attributeId); - } - - @Override - public String toString() { - return classId + "/" + printableInstanceId + "/" + attributeId; - } + private final int classId; + private final ObisCode instanceId; + private final String printableInstanceId; + private final int attributeId; + + public ChannelAddress(int classId, String instanceId, int attributeId) { + this.classId = classId; + printableInstanceId = instanceId; + this.instanceId = parseInstanceId(instanceId); + this.attributeId = attributeId; + } + + public ChannelAddress(int classId, byte[] instanceId, int attributeId) { + this.classId = classId; + printableInstanceId = parseInstanceId(instanceId); + this.instanceId = parseInstanceId(printableInstanceId); + this.attributeId = attributeId; + } + + public static ChannelAddress parse(String input) { + String[] tokens = input.split("/"); + if (tokens.length != 3) { + throw new IllegalArgumentException("Channel address must be of format 'classId/logicalName/attributeId'"); + } + + int classId = Integer.parseInt(tokens[0]); + int attributeId = Integer.parseInt(tokens[2]); + String instanceId = tokens[1]; + + return new ChannelAddress(classId, instanceId, attributeId); + } + + private static ObisCode parseInstanceId(String idString) { + ObisCode result = null; + + String tokens[] = idString.split("\\."); + + if (tokens.length == 1 && idString.length() == 12) { + byte instanceId[] = new byte[6]; + for (int i = 0; i < idString.length(); i += 2) { + instanceId[i / 2] = (byte) Integer.parseInt(idString.substring(i, i + 2), 16); + } + result = new ObisCode(instanceId[0], instanceId[1], instanceId[2], instanceId[3], instanceId[4], instanceId[5]); + } else if (tokens.length == 6) { + result = new ObisCode(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]), + Integer.parseInt(tokens[3]), Integer.parseInt(tokens[4]), Integer.parseInt(tokens[5])); + } else { + throw new IllegalArgumentException("Reduced ID codes are not supported"); + } + + return result; + } + + private static String parseInstanceId(byte[] instanceId) { + StringBuilder result = new StringBuilder(); + + result.append(Integer.toString(instanceId[0] & 0xff)); + for (int i = 1; i < instanceId.length; i++) { + result.append(".").append(Integer.toString(instanceId[i] & 0xff)); + } + + return result.toString(); + } + + public int getClassId() { + return classId; + } + + public ObisCode getInstanceId() { + return instanceId; + } + + public int getAttributeId() { + return attributeId; + } + + public GetRequest createGetRequest() { + return new GetRequest(classId, instanceId, attributeId); + } + + @Override + public String toString() { + return classId + "/" + printableInstanceId + "/" + attributeId; + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsConnection.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsConnection.java index 1b1d2024..a336a75b 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsConnection.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsConnection.java @@ -20,309 +20,277 @@ */ package org.openmuc.driver.dlms; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.data.*; +import org.openmuc.framework.driver.spi.*; +import org.openmuc.jdlms.client.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.Value; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import org.openmuc.jdlms.client.AccessResultCode; -import org.openmuc.jdlms.client.Data; -import org.openmuc.jdlms.client.GetRequest; -import org.openmuc.jdlms.client.GetResult; -import org.openmuc.jdlms.client.IClientConnection; -import org.openmuc.jdlms.client.ObisCode; -import org.openmuc.jdlms.client.SetRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class DlmsConnection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(DlmsConnection.class); - - private final IClientConnection connection; - private final SettingsHelper settings; - - public final static int timeout = 10000; - - public DlmsConnection(IClientConnection connection, SettingsHelper settings) { - this.connection = connection; - this.settings = settings; - } - - // public IClientConnection getConnection() { - // return connection; - // } - // - // public SettingsHelper getSettings() { - // return settings; - // } - - @Override - public void disconnect() { - connection.disconnect(settings.sendDisconnect()); - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - if (!connection.isConnected()) { - throw new ConnectionException(); - } - - List writeList = new ArrayList(containers); - Iterator iter = writeList.iterator(); - - long timestamp = System.currentTimeMillis(); - while (iter.hasNext()) { - ChannelRecordContainer c = iter.next(); - if (c.getChannelHandle() == null) { - try { - GetRequest channelHandle = ChannelAddress.parse(c.getChannelAddress()).createGetRequest(); - c.setChannelHandle(channelHandle); - } catch (IllegalArgumentException e) { - c.setRecord(new Record(null, timestamp, Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); - iter.remove(); - } - } - } - - GetRequest[] getParams = new GetRequest[writeList.size()]; - int index = 0; - for (ChannelRecordContainer c : writeList) { - getParams[index++] = (GetRequest) c.getChannelHandle(); - } - - try { - List results = null; - if (settings.forceSingle()) { - synchronized (connection) { - results = new ArrayList(getParams.length); - for (GetRequest param : getParams) { - results.addAll(connection.get(timeout, param)); - } - } - } - else { - results = connection.get(timeout, getParams); - } - timestamp = System.currentTimeMillis(); - - index = 0; - - for (GetResult result : results) { - Value resultValue = null; - Flag resultFlag = Flag.VALID; - if (result.isSuccess()) { - Data data = result.getResultData(); - if (data.isBoolean()) { - resultValue = new BooleanValue(data.getBoolean()); - } - else if (data.isNumber()) { - resultValue = new DoubleValue(data.getNumber().doubleValue()); - } - else if (data.isCalendar()) { - resultValue = new LongValue(data.getCalendar().getTimeInMillis()); - } - else if (data.isByteArray()) { - resultValue = new ByteArrayValue(data.getByteArray()); - } - } - else { - AccessResultCode code = result.getResultCode(); - if (code == AccessResultCode.HARDWARE_FAULT) { - resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - } - else if (code == AccessResultCode.TEMPORARY_FAILURE) { - resultFlag = Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE; - } - else if (code == AccessResultCode.READ_WRITE_DENIED) { - resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - } - else if (code == AccessResultCode.OBJECT_UNDEFINED) { - resultFlag = Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND; - } - else if (code == AccessResultCode.OBJECT_UNAVAILABLE) { - resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - } - else { - resultFlag = Flag.UNKNOWN_ERROR; - } - } - writeList.get(index++).setRecord(new Record(resultValue, timestamp, resultFlag)); - } - } catch (IOException ex) { - logger.error("Cannot read from device. Reason: " + ex); - timestamp = System.currentTimeMillis(); - for (ChannelRecordContainer c : containers) { - c.setRecord(new Record(null, timestamp, Flag.COMM_DEVICE_NOT_CONNECTED)); - } - throw new ConnectionException(ex.getMessage()); - } - - return null; - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - // TODO Test with multiple channels simultaneously - - if (!connection.isConnected()) { - throw new ConnectionException(); - } - - int size = 0; - List writeHandles = new ArrayList(containers.size()); - for (ChannelValueContainer container : containers) { - WriteHandle handle = new WriteHandle(container); - if (handle.createGetRequest() != null) { - size++; - } - writeHandles.add(new WriteHandle(container)); - } - - GetRequest[] getParams = new GetRequest[size]; - int index = 0; - for (WriteHandle handle : writeHandles) { - GetRequest getRequest = handle.createGetRequest(); - if (getRequest != null) { - getParams[index] = getRequest; - handle.setReadIndex(index); - index++; - } - } - - try { - List getResults = null; - if (settings.forceSingle()) { - synchronized (connection) { - getResults = new ArrayList(getParams.length); - for (GetRequest param : getParams) { - getResults.addAll(connection.get(timeout, param)); - } - } - } - else { - getResults = connection.get(timeout, getParams); - } - - size = 0; - for (WriteHandle handle : writeHandles) { - if (handle.getReadIndex() != -1) { - GetResult getResult = getResults.get(handle.getReadIndex()); - handle.setGetResult(getResult); - if (handle.createSetRequest() != null) { - size++; - } - } - } - - index = 0; - SetRequest[] setParams = new SetRequest[size]; - for (WriteHandle handle : writeHandles) { - SetRequest setRequest = handle.createSetRequest(); - if (setRequest != null) { - setParams[index] = setRequest; - handle.setWriteIndex(index); - index++; - } - } - - List setResults = null; - if (settings.forceSingle()) { - synchronized (connection) { - setResults = new ArrayList(setParams.length); - for (SetRequest param : setParams) { - setResults.addAll(connection.set(timeout, param)); - } - } - } - else { - setResults = connection.set(timeout, setParams); - } - - for (WriteHandle handle : writeHandles) { - if (handle.getWriteIndex() != -1) { - handle.setSetResult(setResults.get(handle.getWriteIndex())); - } - handle.writeFlag(); - } - - } catch (IOException ex) { - logger.error("Cannot write to device. Reason: " + ex); - for (ChannelValueContainer c : containers) { - c.setFlag(Flag.COMM_DEVICE_NOT_CONNECTED); - } - } - - return null; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - - GetRequest scanChannels = new GetRequest(15, new ObisCode(0, 0, 40, 0, 0, 255), 2); - GetResult getResult = null; - try { - if (this.settings.forceSingle()) { - synchronized (connection) { - getResult = connection.get(20000, scanChannels).get(0); - } - } - else { - getResult = connection.get(20000, scanChannels).get(0); - } - } catch (IOException ex) { - logger.debug("Cannot scan device for channels. Reason: " + ex); - throw new ConnectionException(ex); - } - - if (!getResult.isSuccess()) { - throw new ConnectionException("Device sent error code " + getResult.getResultCode().name()); - } - - List result = new LinkedList(); - Data root = getResult.getResultData(); - List objectArray = root.getComplex(); - for (Data objectDef : objectArray) { - List defItems = objectDef.getComplex(); - int classId = defItems.get(0).getNumber().intValue(); - byte[] logicalName = defItems.get(2).getByteArray(); - List attributes = defItems.get(3).getComplex().get(0).getComplex(); - for (Data attributeAccess : attributes) { - int attributeId = attributeAccess.getComplex().get(0).getNumber().intValue(); - int accessRights = attributeAccess.getComplex().get(1).getNumber().intValue(); - boolean readable = accessRights % 2 == 1; - boolean writable = accessRights >= 2; - ChannelAddress channelAddress = new ChannelAddress(classId, logicalName, attributeId); - result.add(new ChannelScanInfo(channelAddress.toString(), "", ValueType.DOUBLE, 0, readable, writable)); - } - } - - return result; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } + private final static Logger logger = LoggerFactory.getLogger(DlmsConnection.class); + + private final IClientConnection connection; + private final SettingsHelper settings; + + public final static int timeout = 10000; + + public DlmsConnection(IClientConnection connection, SettingsHelper settings) { + this.connection = connection; + this.settings = settings; + } + + // public IClientConnection getConnection() { + // return connection; + // } + // + // public SettingsHelper getSettings() { + // return settings; + // } + + @Override + public void disconnect() { + connection.disconnect(settings.sendDisconnect()); + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + if (!connection.isConnected()) { + throw new ConnectionException(); + } + + List writeList = new ArrayList(containers); + Iterator iter = writeList.iterator(); + + long timestamp = System.currentTimeMillis(); + while (iter.hasNext()) { + ChannelRecordContainer c = iter.next(); + if (c.getChannelHandle() == null) { + try { + GetRequest channelHandle = ChannelAddress.parse(c.getChannelAddress()).createGetRequest(); + c.setChannelHandle(channelHandle); + } catch (IllegalArgumentException e) { + c.setRecord(new Record(null, timestamp, Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); + iter.remove(); + } + } + } + + GetRequest[] getParams = new GetRequest[writeList.size()]; + int index = 0; + for (ChannelRecordContainer c : writeList) { + getParams[index++] = (GetRequest) c.getChannelHandle(); + } + + try { + List results = null; + if (settings.forceSingle()) { + synchronized (connection) { + results = new ArrayList(getParams.length); + for (GetRequest param : getParams) { + results.addAll(connection.get(timeout, param)); + } + } + } else { + results = connection.get(timeout, getParams); + } + timestamp = System.currentTimeMillis(); + + index = 0; + + for (GetResult result : results) { + Value resultValue = null; + Flag resultFlag = Flag.VALID; + if (result.isSuccess()) { + Data data = result.getResultData(); + if (data.isBoolean()) { + resultValue = new BooleanValue(data.getBoolean()); + } else if (data.isNumber()) { + resultValue = new DoubleValue(data.getNumber().doubleValue()); + } else if (data.isCalendar()) { + resultValue = new LongValue(data.getCalendar().getTimeInMillis()); + } else if (data.isByteArray()) { + resultValue = new ByteArrayValue(data.getByteArray()); + } + } else { + AccessResultCode code = result.getResultCode(); + if (code == AccessResultCode.HARDWARE_FAULT) { + resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + } else if (code == AccessResultCode.TEMPORARY_FAILURE) { + resultFlag = Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE; + } else if (code == AccessResultCode.READ_WRITE_DENIED) { + resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + } else if (code == AccessResultCode.OBJECT_UNDEFINED) { + resultFlag = Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND; + } else if (code == AccessResultCode.OBJECT_UNAVAILABLE) { + resultFlag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + } else { + resultFlag = Flag.UNKNOWN_ERROR; + } + } + writeList.get(index++).setRecord(new Record(resultValue, timestamp, resultFlag)); + } + } catch (IOException ex) { + logger.error("Cannot read from device. Reason: " + ex); + timestamp = System.currentTimeMillis(); + for (ChannelRecordContainer c : containers) { + c.setRecord(new Record(null, timestamp, Flag.COMM_DEVICE_NOT_CONNECTED)); + } + throw new ConnectionException(ex.getMessage()); + } + + return null; + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + // TODO Test with multiple channels simultaneously + + if (!connection.isConnected()) { + throw new ConnectionException(); + } + + int size = 0; + List writeHandles = new ArrayList(containers.size()); + for (ChannelValueContainer container : containers) { + WriteHandle handle = new WriteHandle(container); + if (handle.createGetRequest() != null) { + size++; + } + writeHandles.add(new WriteHandle(container)); + } + + GetRequest[] getParams = new GetRequest[size]; + int index = 0; + for (WriteHandle handle : writeHandles) { + GetRequest getRequest = handle.createGetRequest(); + if (getRequest != null) { + getParams[index] = getRequest; + handle.setReadIndex(index); + index++; + } + } + + try { + List getResults = null; + if (settings.forceSingle()) { + synchronized (connection) { + getResults = new ArrayList(getParams.length); + for (GetRequest param : getParams) { + getResults.addAll(connection.get(timeout, param)); + } + } + } else { + getResults = connection.get(timeout, getParams); + } + + size = 0; + for (WriteHandle handle : writeHandles) { + if (handle.getReadIndex() != -1) { + GetResult getResult = getResults.get(handle.getReadIndex()); + handle.setGetResult(getResult); + if (handle.createSetRequest() != null) { + size++; + } + } + } + + index = 0; + SetRequest[] setParams = new SetRequest[size]; + for (WriteHandle handle : writeHandles) { + SetRequest setRequest = handle.createSetRequest(); + if (setRequest != null) { + setParams[index] = setRequest; + handle.setWriteIndex(index); + index++; + } + } + + List setResults = null; + if (settings.forceSingle()) { + synchronized (connection) { + setResults = new ArrayList(setParams.length); + for (SetRequest param : setParams) { + setResults.addAll(connection.set(timeout, param)); + } + } + } else { + setResults = connection.set(timeout, setParams); + } + + for (WriteHandle handle : writeHandles) { + if (handle.getWriteIndex() != -1) { + handle.setSetResult(setResults.get(handle.getWriteIndex())); + } + handle.writeFlag(); + } + + } catch (IOException ex) { + logger.error("Cannot write to device. Reason: " + ex); + for (ChannelValueContainer c : containers) { + c.setFlag(Flag.COMM_DEVICE_NOT_CONNECTED); + } + } + + return null; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + + GetRequest scanChannels = new GetRequest(15, new ObisCode(0, 0, 40, 0, 0, 255), 2); + GetResult getResult = null; + try { + if (this.settings.forceSingle()) { + synchronized (connection) { + getResult = connection.get(20000, scanChannels).get(0); + } + } else { + getResult = connection.get(20000, scanChannels).get(0); + } + } catch (IOException ex) { + logger.debug("Cannot scan device for channels. Reason: " + ex); + throw new ConnectionException(ex); + } + + if (!getResult.isSuccess()) { + throw new ConnectionException("Device sent error code " + getResult.getResultCode().name()); + } + + List result = new LinkedList(); + Data root = getResult.getResultData(); + List objectArray = root.getComplex(); + for (Data objectDef : objectArray) { + List defItems = objectDef.getComplex(); + int classId = defItems.get(0).getNumber().intValue(); + byte[] logicalName = defItems.get(2).getByteArray(); + List attributes = defItems.get(3).getComplex().get(0).getComplex(); + for (Data attributeAccess : attributes) { + int attributeId = attributeAccess.getComplex().get(0).getNumber().intValue(); + int accessRights = attributeAccess.getComplex().get(1).getNumber().intValue(); + boolean readable = accessRights % 2 == 1; + boolean writable = accessRights >= 2; + ChannelAddress channelAddress = new ChannelAddress(classId, logicalName, attributeId); + result.add(new ChannelScanInfo(channelAddress.toString(), "", ValueType.DOUBLE, 0, readable, writable)); + } + } + + return result; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsDriver.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsDriver.java index 96b18bdf..bfff4650 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsDriver.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/DlmsDriver.java @@ -20,9 +20,6 @@ */ package org.openmuc.driver.dlms; -import java.io.IOException; -import java.net.UnknownHostException; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.DriverInfo; import org.openmuc.framework.config.ScanException; @@ -37,73 +34,76 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.net.UnknownHostException; + public class DlmsDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(DlmsDriver.class); - - private final IClientConnectionFactory connectionFactory = new OsgiClientConnectionFactory(); - private final AddressParser addressParser = new AddressParser(); - - private final static DriverInfo info = new DriverInfo("dlms", // id - // description - "This is a driver to communicate with smart meter over the IEC 62056 DLMS/COSEM protocol.", - // device address - "N.A.", - // parameters - "N.A", - // channel address - "N.A", - // device scan parameters - "N.A"); - - public DlmsDriver() { - logger.debug("DLMS Driver instantiated. Expecting rxtxserial.so in: " + System.getProperty("java.library.path") - + " for serial (HDLC) connections."); - } - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ConnectionException, - ArgumentSyntaxException { - - SettingsHelper settingsHelper = new SettingsHelper(settings); - - IClientConnection connection; - try { - ClientConnectionSettings params = addressParser.parse(deviceAddress, settingsHelper); - connection = connectionFactory.createClientConnection(params); - } catch (UnknownHostException uhEx) { - throw new ConnectionException("Device " + deviceAddress + " not found"); - } catch (IOException ioEx) { - throw new ConnectionException("Cannot create connection object. Reason: " + ioEx); - } - - logger.debug("Connecting to device:" + deviceAddress); - try { - connection.connect(DlmsConnection.timeout, settingsHelper.getPassword()); - } catch (IOException ex) { - throw new ConnectionException(ex.getMessage()); - } - logger.debug("Connected to device: " + deviceAddress); - - DlmsConnection handle = new DlmsConnection(connection, settingsHelper); - - return handle; - } + private final static Logger logger = LoggerFactory.getLogger(DlmsDriver.class); + + private final IClientConnectionFactory connectionFactory = new OsgiClientConnectionFactory(); + private final AddressParser addressParser = new AddressParser(); + + private final static DriverInfo info = new DriverInfo("dlms", // id + // description + "This is a driver to communicate with smart meter over the IEC 62056 DLMS/COSEM" + + " protocol.", + // device address + "N.A.", + // parameters + "N.A", + // channel address + "N.A", + // device scan parameters + "N.A"); + + public DlmsDriver() { + logger.debug("DLMS Driver instantiated. Expecting rxtxserial.so in: " + System + .getProperty("java.library.path") + " for serial (HDLC) connections."); + } + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ConnectionException, ArgumentSyntaxException { + + SettingsHelper settingsHelper = new SettingsHelper(settings); + + IClientConnection connection; + try { + ClientConnectionSettings params = addressParser.parse(deviceAddress, settingsHelper); + connection = connectionFactory.createClientConnection(params); + } catch (UnknownHostException uhEx) { + throw new ConnectionException("Device " + deviceAddress + " not found"); + } catch (IOException ioEx) { + throw new ConnectionException("Cannot create connection object. Reason: " + ioEx); + } + + logger.debug("Connecting to device:" + deviceAddress); + try { + connection.connect(DlmsConnection.timeout, settingsHelper.getPassword()); + } catch (IOException ex) { + throw new ConnectionException(ex.getMessage()); + } + logger.debug("Connected to device: " + deviceAddress); + + DlmsConnection handle = new DlmsConnection(connection, settingsHelper); + + return handle; + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/OsgiClientConnectionFactory.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/OsgiClientConnectionFactory.java index 5c5cbf0c..88712d8a 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/OsgiClientConnectionFactory.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/OsgiClientConnectionFactory.java @@ -20,9 +20,6 @@ */ package org.openmuc.driver.dlms; -import java.util.ArrayList; -import java.util.List; - import org.openmuc.jdlms.client.ClientConnectionFactory; import org.openmuc.jdlms.client.ClientConnectionSettings; import org.openmuc.jdlms.client.ILowerLayerFactory; @@ -30,31 +27,34 @@ import org.openmuc.jdlms.client.ip.TcpClientLayerFactory; import org.openmuc.jdlms.client.ip.UdpClientLayerFactory; +import java.util.ArrayList; +import java.util.List; + /** * Implementation of {@link ILowerLayerFactory} statically loading all available LowerLayerFactories. - * + * * @author Karsten Mueller-Bier */ public final class OsgiClientConnectionFactory extends ClientConnectionFactory { - private final List factories; + private final List factories; - public OsgiClientConnectionFactory() { - factories = new ArrayList(3); - factories.add(new HdlcClientLayerFactory()); - factories.add(new UdpClientLayerFactory()); - factories.add(new TcpClientLayerFactory()); - } + public OsgiClientConnectionFactory() { + factories = new ArrayList(3); + factories.add(new HdlcClientLayerFactory()); + factories.add(new UdpClientLayerFactory()); + factories.add(new TcpClientLayerFactory()); + } - @Override - protected ILowerLayerFactory getLowerLayerFactory( - @SuppressWarnings("rawtypes") Class settingsClass) { - for (ILowerLayerFactory factory : factories) { - if (factory.accepts(settingsClass)) { - return factory; - } - } + @Override + protected ILowerLayerFactory getLowerLayerFactory(@SuppressWarnings("rawtypes") Class + settingsClass) { + for (ILowerLayerFactory factory : factories) { + if (factory.accepts(settingsClass)) { + return factory; + } + } - return null; - } + return null; + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/SettingsHelper.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/SettingsHelper.java index 2331c399..099d8a8e 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/SettingsHelper.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/SettingsHelper.java @@ -26,85 +26,85 @@ public class SettingsHelper { - private static final String SEND_DISCONNECT_KEY = "senddisconnect"; - private static final boolean SEND_DISCONNECT_DEFAULT = true; + private static final String SEND_DISCONNECT_KEY = "senddisconnect"; + private static final boolean SEND_DISCONNECT_DEFAULT = true; - private static final String REFERENCING_KEY = "referencing"; - private static final String REFERENCING_DEFAULT = "LN"; + private static final String REFERENCING_KEY = "referencing"; + private static final String REFERENCING_DEFAULT = "LN"; - private static final String USE_HANDSHAKE_KEY = "usehandshake"; - private static final boolean USE_HANDSHAKE_DEFAULT = true; + private static final String USE_HANDSHAKE_KEY = "usehandshake"; + private static final boolean USE_HANDSHAKE_DEFAULT = true; - private static final String BAUDRATE_KEY = "baudrate"; - private static final int BAUDRATE_DEFAULT = 0; + private static final String BAUDRATE_KEY = "baudrate"; + private static final int BAUDRATE_DEFAULT = 0; - private static final String PASSWORD_KEY = "pw"; - private static final byte[] PASSWORD_DEFAULT = null; + private static final String PASSWORD_KEY = "pw"; + private static final byte[] PASSWORD_DEFAULT = null; - private static final String FORCE_SINGLE_KEY = "forcesingle"; - private static final boolean FORCE_SINGLE_DEFAULT = false; + private static final String FORCE_SINGLE_KEY = "forcesingle"; + private static final boolean FORCE_SINGLE_DEFAULT = false; - private static final Charset US_ASCII = Charset.forName("US-ASCII"); + private static final Charset US_ASCII = Charset.forName("US-ASCII"); - private final Map settingsMap = new HashMap(); + private final Map settingsMap = new HashMap(); - public SettingsHelper(String settings) { - String[] settingsArray = settings.split(";"); - for (String arg : settingsArray) { - int p = arg.indexOf("="); - if (p != -1) { - settingsMap.put(arg.substring(0, p).toLowerCase().trim(), arg.substring(p + 1).trim()); - } - // ignore params with wrong formatting - // TODO Add logging for wrongly formatted setting - } - } + public SettingsHelper(String settings) { + String[] settingsArray = settings.split(";"); + for (String arg : settingsArray) { + int p = arg.indexOf("="); + if (p != -1) { + settingsMap.put(arg.substring(0, p).toLowerCase().trim(), arg.substring(p + 1).trim()); + } + // ignore params with wrong formatting + // TODO Add logging for wrongly formatted setting + } + } - public boolean sendDisconnect() { - if (settingsMap.containsKey(SEND_DISCONNECT_KEY)) { - return Boolean.parseBoolean(settingsMap.get(SEND_DISCONNECT_KEY).trim()); - } + public boolean sendDisconnect() { + if (settingsMap.containsKey(SEND_DISCONNECT_KEY)) { + return Boolean.parseBoolean(settingsMap.get(SEND_DISCONNECT_KEY).trim()); + } - return SEND_DISCONNECT_DEFAULT; - } + return SEND_DISCONNECT_DEFAULT; + } - public String getReferencing() { - if (settingsMap.containsKey(REFERENCING_KEY)) { - return settingsMap.get(REFERENCING_KEY).toUpperCase(); - } + public String getReferencing() { + if (settingsMap.containsKey(REFERENCING_KEY)) { + return settingsMap.get(REFERENCING_KEY).toUpperCase(); + } - return REFERENCING_DEFAULT; - } + return REFERENCING_DEFAULT; + } - public boolean useHandshake() { - if (settingsMap.containsKey(USE_HANDSHAKE_KEY)) { - return Boolean.parseBoolean(settingsMap.get(USE_HANDSHAKE_KEY).trim()); - } + public boolean useHandshake() { + if (settingsMap.containsKey(USE_HANDSHAKE_KEY)) { + return Boolean.parseBoolean(settingsMap.get(USE_HANDSHAKE_KEY).trim()); + } - return USE_HANDSHAKE_DEFAULT; - } + return USE_HANDSHAKE_DEFAULT; + } - public int getBaudrate() { - if (settingsMap.containsKey(BAUDRATE_KEY)) { - return Integer.parseInt(settingsMap.get(BAUDRATE_KEY).trim()); - } + public int getBaudrate() { + if (settingsMap.containsKey(BAUDRATE_KEY)) { + return Integer.parseInt(settingsMap.get(BAUDRATE_KEY).trim()); + } - return BAUDRATE_DEFAULT; - } + return BAUDRATE_DEFAULT; + } - public byte[] getPassword() { - if (settingsMap.containsKey(PASSWORD_KEY)) { - return settingsMap.get(PASSWORD_KEY).getBytes(US_ASCII); - } + public byte[] getPassword() { + if (settingsMap.containsKey(PASSWORD_KEY)) { + return settingsMap.get(PASSWORD_KEY).getBytes(US_ASCII); + } - return PASSWORD_DEFAULT; - } + return PASSWORD_DEFAULT; + } - public boolean forceSingle() { - if (settingsMap.containsKey(FORCE_SINGLE_KEY)) { - return Boolean.parseBoolean(settingsMap.get(FORCE_SINGLE_KEY).trim()); - } + public boolean forceSingle() { + if (settingsMap.containsKey(FORCE_SINGLE_KEY)) { + return Boolean.parseBoolean(settingsMap.get(FORCE_SINGLE_KEY).trim()); + } - return FORCE_SINGLE_DEFAULT; - } + return FORCE_SINGLE_DEFAULT; + } } diff --git a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/WriteHandle.java b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/WriteHandle.java index ff86d79e..d63aa0fe 100644 --- a/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/WriteHandle.java +++ b/projects/driver/dlms/src/main/java/org/openmuc/driver/dlms/WriteHandle.java @@ -22,173 +22,160 @@ import org.openmuc.framework.data.Flag; import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.jdlms.client.AccessResultCode; -import org.openmuc.jdlms.client.Data; -import org.openmuc.jdlms.client.GetRequest; -import org.openmuc.jdlms.client.GetResult; -import org.openmuc.jdlms.client.SetRequest; +import org.openmuc.jdlms.client.*; public class WriteHandle { - private final ChannelValueContainer container; - private GetResult getResult; - private AccessResultCode setResult; + private final ChannelValueContainer container; + private GetResult getResult; + private AccessResultCode setResult; - private int getIndex = -1; - private int setIndex = -1; - private Flag flag; + private int getIndex = -1; + private int setIndex = -1; + private Flag flag; - public WriteHandle(ChannelValueContainer container) { - this.container = container; - } + public WriteHandle(ChannelValueContainer container) { + this.container = container; + } - public GetRequest createGetRequest() { - GetRequest channelHandle = null; - if (container.getChannelHandle() == null) { - try { - channelHandle = ChannelAddress.parse(container.getChannelAddress()).createGetRequest(); - container.setChannelHandle(channelHandle); - } catch (IllegalArgumentException e) { - flag = Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID; - } - } - else { - channelHandle = (GetRequest) container.getChannelHandle(); - } - return channelHandle; - } + public GetRequest createGetRequest() { + GetRequest channelHandle = null; + if (container.getChannelHandle() == null) { + try { + channelHandle = ChannelAddress.parse(container.getChannelAddress()).createGetRequest(); + container.setChannelHandle(channelHandle); + } catch (IllegalArgumentException e) { + flag = Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID; + } + } else { + channelHandle = (GetRequest) container.getChannelHandle(); + } + return channelHandle; + } - public void setGetResult(GetResult result) { - getResult = result; - if (getResult == null) { - flag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - } - else { - if (!getResult.isSuccess()) { - flag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; - } - } - } + public void setGetResult(GetResult result) { + getResult = result; + if (getResult == null) { + flag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + } else { + if (!getResult.isSuccess()) { + flag = Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE; + } + } + } - public SetRequest createSetRequest() { - if (flag != null) { - return null; - } - SetRequest result = ((GetRequest) container.getChannelHandle()).toSetRequest(); - Data originData = getResult.getResultData(); - Data param = result.data(); + public SetRequest createSetRequest() { + if (flag != null) { + return null; + } + SetRequest result = ((GetRequest) container.getChannelHandle()).toSetRequest(); + Data originData = getResult.getResultData(); + Data param = result.data(); - switch (originData.getChoiceIndex()) { - case NULL_DATA: - param.setNull(); - break; - case ARRAY: - case STRUCTURE: - case COMPACT_ARRAY: - case DATE_TIME: - case DATE: - case TIME: - case DONT_CARE: - flag = Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION; - result = null; - break; - case BOOL: - param.setbool(container.getValue().asBoolean()); - break; - case BIT_STRING: - param.setBitString(container.getValue().asByteArray(), container.getValue().asByteArray().length * 8); - break; - case DOUBLE_LONG: - param.setInteger32(container.getValue().asInt()); - break; - case DOUBLE_LONG_UNSIGNED: - param.setUnsigned32(container.getValue().asLong()); - break; - case OCTET_STRING: - param.setOctetString(container.getValue().asByteArray()); - break; - case VISIBLE_STRING: - param.setVisibleString(container.getValue().asByteArray()); - break; - case BCD: - param.setBcd(container.getValue().asByte()); - break; - case INTEGER: - param.setInteger8(container.getValue().asByte()); - break; - case LONG_INTEGER: - param.setInteger16(container.getValue().asShort()); - break; - case UNSIGNED: - param.setUnsigned8(container.getValue().asShort()); - break; - case LONG_UNSIGNED: - param.setUnsigned16(container.getValue().asInt()); - break; - case LONG64: - param.setInteger64(container.getValue().asLong()); - break; - case LONG64_UNSIGNED: - param.setUnsigned64(container.getValue().asLong()); - break; - case ENUMERATE: - param.setEnumerate(container.getValue().asByte()); - break; - case FLOAT32: - param.setFloat32(container.getValue().asFloat()); - break; - case FLOAT64: - param.setFloat64(container.getValue().asDouble()); - break; - } - return result; - } + switch (originData.getChoiceIndex()) { + case NULL_DATA: + param.setNull(); + break; + case ARRAY: + case STRUCTURE: + case COMPACT_ARRAY: + case DATE_TIME: + case DATE: + case TIME: + case DONT_CARE: + flag = Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION; + result = null; + break; + case BOOL: + param.setbool(container.getValue().asBoolean()); + break; + case BIT_STRING: + param.setBitString(container.getValue().asByteArray(), container.getValue().asByteArray().length * 8); + break; + case DOUBLE_LONG: + param.setInteger32(container.getValue().asInt()); + break; + case DOUBLE_LONG_UNSIGNED: + param.setUnsigned32(container.getValue().asLong()); + break; + case OCTET_STRING: + param.setOctetString(container.getValue().asByteArray()); + break; + case VISIBLE_STRING: + param.setVisibleString(container.getValue().asByteArray()); + break; + case BCD: + param.setBcd(container.getValue().asByte()); + break; + case INTEGER: + param.setInteger8(container.getValue().asByte()); + break; + case LONG_INTEGER: + param.setInteger16(container.getValue().asShort()); + break; + case UNSIGNED: + param.setUnsigned8(container.getValue().asShort()); + break; + case LONG_UNSIGNED: + param.setUnsigned16(container.getValue().asInt()); + break; + case LONG64: + param.setInteger64(container.getValue().asLong()); + break; + case LONG64_UNSIGNED: + param.setUnsigned64(container.getValue().asLong()); + break; + case ENUMERATE: + param.setEnumerate(container.getValue().asByte()); + break; + case FLOAT32: + param.setFloat32(container.getValue().asFloat()); + break; + case FLOAT64: + param.setFloat64(container.getValue().asDouble()); + break; + } + return result; + } - public void setSetResult(AccessResultCode result) { - setResult = result; - } + public void setSetResult(AccessResultCode result) { + setResult = result; + } - public void writeFlag() { - if (setResult == null) { - container.setFlag(flag); - } - else { - if (setResult == AccessResultCode.SUCCESS) { - container.setFlag(Flag.VALID); - } - else if (setResult == AccessResultCode.HARDWARE_FAULT) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); - } - else if (setResult == AccessResultCode.TEMPORARY_FAILURE) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE); - } - else if (setResult == AccessResultCode.READ_WRITE_DENIED) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); - } - else if (setResult == AccessResultCode.OBJECT_UNDEFINED) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); - } - else if (setResult == AccessResultCode.OBJECT_UNAVAILABLE) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); - } - else { - container.setFlag(Flag.UNKNOWN_ERROR); - } - } - } + public void writeFlag() { + if (setResult == null) { + container.setFlag(flag); + } else { + if (setResult == AccessResultCode.SUCCESS) { + container.setFlag(Flag.VALID); + } else if (setResult == AccessResultCode.HARDWARE_FAULT) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); + } else if (setResult == AccessResultCode.TEMPORARY_FAILURE) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE); + } else if (setResult == AccessResultCode.READ_WRITE_DENIED) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); + } else if (setResult == AccessResultCode.OBJECT_UNDEFINED) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); + } else if (setResult == AccessResultCode.OBJECT_UNAVAILABLE) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); + } else { + container.setFlag(Flag.UNKNOWN_ERROR); + } + } + } - public void setReadIndex(int index) { - getIndex = index; - } + public void setReadIndex(int index) { + getIndex = index; + } - public int getReadIndex() { - return getIndex; - } + public int getReadIndex() { + return getIndex; + } - public void setWriteIndex(int index) { - setIndex = index; - } + public void setWriteIndex(int index) { + setIndex = index; + } - public int getWriteIndex() { - return setIndex; - } + public int getWriteIndex() { + return setIndex; + } } diff --git a/projects/driver/dlms/src/main/resources/OSGI-INF/components.xml b/projects/driver/dlms/src/main/resources/OSGI-INF/components.xml index 8fc15bb5..d135c129 100644 --- a/projects/driver/dlms/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/dlms/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/ehz/build.gradle b/projects/driver/ehz/build.gradle index 01a86437..71e3ad2d 100644 --- a/projects/driver/ehz/build.gradle +++ b/projects/driver/ehz/build.gradle @@ -3,25 +3,25 @@ configurations.create('embed') def jsmlversion = "1.0.17" dependencies { - compile project(':openmuc-core-spi') - compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') - - compile group: 'org.openmuc', name: 'jsml', version: jsmlversion - embed group: 'org.openmuc', name: 'jsml', version: jsmlversion + compile project(':openmuc-core-spi') + compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') + + compile group: 'org.openmuc', name: 'jsml', version: jsmlversion + embed group: 'org.openmuc', name: 'jsml', version: jsmlversion } jar { - manifest { - name = "OpenMUC Driver - eHZ" - instruction 'Bundle-ClassPath', '.,lib/jsml-' + jsmlversion + '.jar' - instruction 'Import-Package', '!org.openmuc.jsml*,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - eHZ" + instruction 'Bundle-ClassPath', '.,lib/jsml-' + jsmlversion + '.jar' + instruction 'Import-Package', '!org.openmuc.jsml*,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/EhzDriver.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/EhzDriver.java index 2c3f64d5..59de8eee 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/EhzDriver.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/EhzDriver.java @@ -22,16 +22,7 @@ package org.openmuc.framework.driver.ehz; import gnu.io.CommPortIdentifier; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.Connection; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; @@ -39,99 +30,100 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class EhzDriver implements DriverService { - - private static Logger logger = LoggerFactory.getLogger(EhzDriver.class); - - private static final String ADDR_IEC = "iec"; - private static final String ADDR_SML = "sml"; - - private final static DriverInfo info = new DriverInfo("ehz", // id - // description - "Driver for IEC 62056-21 and SML.", - // device address - "N.A.", - // parameters - "N.A.", - // channel address - "N.A.", - // device scan parameters - "N.A."); - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - - Enumeration ports = CommPortIdentifier.getPortIdentifiers(); - while (ports.hasMoreElements()) { - CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); - String serialPort = port.getName(); - logger.trace("searching for device at " + serialPort); - URI deviceAddress = null; - GeneralConnection connection = null; - if (deviceAddress == null) { - try { - connection = new IecConnection(serialPort, 2000); - if (connection.isWorking()) { - logger.info("found iec device at " + serialPort); - deviceAddress = new URI(ADDR_IEC + "://" + serialPort); - } - connection.close(); - } catch (Exception e) { - logger.trace(serialPort + " is no iec device"); - } - } - if (deviceAddress == null) { - try { - connection = new SmlConnection(serialPort); - if (connection.isWorking()) { - logger.info("found sml device at " + serialPort); - deviceAddress = new URI(ADDR_SML + "://" + serialPort); - } - connection.close(); - } catch (Exception e) { - logger.trace(serialPort + " is no sml device"); - } - } - if (deviceAddress != null) { - listener.deviceFound(new DeviceScanInfo(deviceAddress.toString(), "", "")); - } - else { - logger.info("no ehz device found at " + serialPort); - } - } - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - - } +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Enumeration; - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - logger.trace("trying to connect to " + deviceAddress); - try { - URI device = new URI(deviceAddress); +public class EhzDriver implements DriverService { - if (device.getScheme().equals(ADDR_IEC)) { - logger.trace("connecting to iec device"); - return new IecConnection(device.getPath(), GeneralConnection.timeout); - } - else if (device.getScheme().equals(ADDR_SML)) { - logger.trace("connecting to sml device"); - return new SmlConnection(device.getPath()); - } - throw new ConnectionException("unrecognized address scheme " + device.getScheme()); - } catch (URISyntaxException e) { - throw new ConnectionException(e); - } - } + private static Logger logger = LoggerFactory.getLogger(EhzDriver.class); + + private static final String ADDR_IEC = "iec"; + private static final String ADDR_SML = "sml"; + + private final static DriverInfo info = new DriverInfo("ehz", // id + // description + "Driver for IEC 62056-21 and SML.", + // device address + "N.A.", + // parameters + "N.A.", + // channel address + "N.A.", + // device scan parameters + "N.A."); + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + + Enumeration ports = CommPortIdentifier.getPortIdentifiers(); + while (ports.hasMoreElements()) { + CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); + String serialPort = port.getName(); + logger.trace("searching for device at " + serialPort); + URI deviceAddress = null; + GeneralConnection connection = null; + if (deviceAddress == null) { + try { + connection = new IecConnection(serialPort, 2000); + if (connection.isWorking()) { + logger.info("found iec device at " + serialPort); + deviceAddress = new URI(ADDR_IEC + "://" + serialPort); + } + connection.close(); + } catch (Exception e) { + logger.trace(serialPort + " is no iec device"); + } + } + if (deviceAddress == null) { + try { + connection = new SmlConnection(serialPort); + if (connection.isWorking()) { + logger.info("found sml device at " + serialPort); + deviceAddress = new URI(ADDR_SML + "://" + serialPort); + } + connection.close(); + } catch (Exception e) { + logger.trace(serialPort + " is no sml device"); + } + } + if (deviceAddress != null) { + listener.deviceFound(new DeviceScanInfo(deviceAddress.toString(), "", "")); + } else { + logger.info("no ehz device found at " + serialPort); + } + } + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + logger.trace("trying to connect to " + deviceAddress); + try { + URI device = new URI(deviceAddress); + + if (device.getScheme().equals(ADDR_IEC)) { + logger.trace("connecting to iec device"); + return new IecConnection(device.getPath(), GeneralConnection.timeout); + } else if (device.getScheme().equals(ADDR_SML)) { + logger.trace("connecting to sml device"); + return new SmlConnection(device.getPath()); + } + throw new ConnectionException("unrecognized address scheme " + device.getScheme()); + } catch (URISyntaxException e) { + throw new ConnectionException(e); + } + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/GeneralConnection.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/GeneralConnection.java index 2b6bd00c..dff01a36 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/GeneralConnection.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/GeneralConnection.java @@ -21,9 +21,6 @@ package org.openmuc.framework.driver.ehz; -import java.util.List; -import java.util.Map; - import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.data.DoubleValue; import org.openmuc.framework.data.Flag; @@ -36,72 +33,71 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.Map; + /** * @author Frederic Robra - * */ public abstract class GeneralConnection implements org.openmuc.framework.driver.spi.Connection { - protected static Logger logger = LoggerFactory.getLogger(GeneralConnection.class); - protected String name; - - protected final static int timeout = 10000; - - public abstract void close(); - - public abstract void read(List containers, int timeout) throws ConnectionException; - - public abstract List listChannels(int timeout); - - public abstract boolean isWorking(); - - protected void handleChannelRecordContainer(List containers, Map values, - long timestamp) { - for (ChannelRecordContainer container : containers) { - String address = container.getChannelAddress(); - if (values.containsKey(address)) { - Value value = new DoubleValue(values.get(address)); - Record record = new Record(value, timestamp, Flag.VALID); - container.setRecord(record); - } - } - } - - /* - * (non-Javadoc) - * - * @see - * org.openmuc.framework.driver.spi.DriverService#scanForChannels(org.openmuc.framework.driver.spi.DeviceConnection, - * int) - */ - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - return listChannels(20000); - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - read(containers, timeout); - return null; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void disconnect() { - close(); - } + protected static Logger logger = LoggerFactory.getLogger(GeneralConnection.class); + protected String name; + + protected final static int timeout = 10000; + + public abstract void close(); + + public abstract void read(List containers, int timeout) throws ConnectionException; + + public abstract List listChannels(int timeout); + + public abstract boolean isWorking(); + + protected void handleChannelRecordContainer(List containers, Map values, long timestamp) { + for (ChannelRecordContainer container : containers) { + String address = container.getChannelAddress(); + if (values.containsKey(address)) { + Value value = new DoubleValue(values.get(address)); + Record record = new Record(value, timestamp, Flag.VALID); + container.setRecord(record); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * org.openmuc.framework.driver.spi.DriverService#scanForChannels(org.openmuc.framework.driver.spi.DeviceConnection, + * int) + */ + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + return listChannels(20000); + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + read(containers, timeout); + return null; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void disconnect() { + close(); + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/IecConnection.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/IecConnection.java index 7a11c9f7..8a4e9777 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/IecConnection.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/IecConnection.java @@ -21,13 +21,6 @@ package org.openmuc.framework.driver.ehz; -import java.io.IOException; -import java.text.ParseException; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.driver.ehz.iec62056_21.DataSet; @@ -36,122 +29,128 @@ import org.openmuc.framework.driver.spi.ChannelRecordContainer; import org.openmuc.framework.driver.spi.ConnectionException; +import java.io.IOException; +import java.text.ParseException; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + /** * @author Frederic Robra - * */ public class IecConnection extends GeneralConnection { - private IecReceiver receiver; - - public IecConnection(String deviceAddress, int timeout) throws ConnectionException { - name = "IEC - " + deviceAddress + " - "; - try { - receiver = new IecReceiver(deviceAddress); - } catch (Exception e) { - throw new ConnectionException(name + "serial port not found"); - } - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#close() - */ - @Override - public void close() { - receiver.close(); - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#read(java.util.List, int) - */ - @Override - public void read(List containers, int timeout) throws ConnectionException { - logger.trace(name + "reading channels"); - try { - long timestamp = System.currentTimeMillis(); - - byte[] frame = receiver.receiveMessage(timeout); - ModeDMessage message = new ModeDMessage(frame); - message.parse(); - List dataSets = message.getDataSets(); - - Map values = new LinkedHashMap(); - for (String data : dataSets) { - DataSet dataSet = new DataSet(data); - String address = dataSet.getAddress(); - double value = dataSet.getVal(); - values.put(address, value); - logger.trace(name + address + " = " + value); - } - - handleChannelRecordContainer(containers, values, timestamp); - } catch (IOException e) { - e.printStackTrace(); - logger.error(name + "read failed"); - close(); - throw new ConnectionException(e); - } catch (ParseException e) { - logger.error(name + "parsing failed"); - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#listChannels(int) - */ - @Override - public List listChannels(int timeout) { - List channelInfos = new LinkedList(); - - logger.debug(name + "scanning channels"); - try { - byte[] frame = receiver.receiveMessage(timeout); - ModeDMessage message = new ModeDMessage(frame); - message.parse(); - List dataSets = message.getDataSets(); - - for (String data : dataSets) { - DataSet dataSet = new DataSet(data); - String channelAddress = dataSet.getAddress(); - String description = "Current value: " + dataSet.getVal() + dataSet.getUnit(); - ValueType valueType = ValueType.DOUBLE; - Integer valueTypeLength = null; - Boolean readable = true; - Boolean writable = false; - ChannelScanInfo channelInfo = new ChannelScanInfo(channelAddress, description, valueType, - valueTypeLength, readable, writable); - channelInfos.add(channelInfo); - } - - } catch (Exception e) { - e.printStackTrace(); - logger.warn(name + "read failed"); - } - return channelInfos; - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#isWorking() - */ - @Override - public boolean isWorking() { - try { - byte[] frame = receiver.receiveMessage(1000); - ModeDMessage message = new ModeDMessage(frame); - message.parse(); - return true; - } catch (Exception e) { - return false; - } - - } + private IecReceiver receiver; + + public IecConnection(String deviceAddress, int timeout) throws ConnectionException { + name = "IEC - " + deviceAddress + " - "; + try { + receiver = new IecReceiver(deviceAddress); + } catch (Exception e) { + throw new ConnectionException(name + "serial port not found"); + } + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#close() + */ + @Override + public void close() { + receiver.close(); + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#read(java.util.List, int) + */ + @Override + public void read(List containers, int timeout) throws ConnectionException { + logger.trace(name + "reading channels"); + try { + long timestamp = System.currentTimeMillis(); + + byte[] frame = receiver.receiveMessage(timeout); + ModeDMessage message = new ModeDMessage(frame); + message.parse(); + List dataSets = message.getDataSets(); + + Map values = new LinkedHashMap(); + for (String data : dataSets) { + DataSet dataSet = new DataSet(data); + String address = dataSet.getAddress(); + double value = dataSet.getVal(); + values.put(address, value); + logger.trace(name + address + " = " + value); + } + + handleChannelRecordContainer(containers, values, timestamp); + } catch (IOException e) { + e.printStackTrace(); + logger.error(name + "read failed"); + close(); + throw new ConnectionException(e); + } catch (ParseException e) { + logger.error(name + "parsing failed"); + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#listChannels(int) + */ + @Override + public List listChannels(int timeout) { + List channelInfos = new LinkedList(); + + logger.debug(name + "scanning channels"); + try { + byte[] frame = receiver.receiveMessage(timeout); + ModeDMessage message = new ModeDMessage(frame); + message.parse(); + List dataSets = message.getDataSets(); + + for (String data : dataSets) { + DataSet dataSet = new DataSet(data); + String channelAddress = dataSet.getAddress(); + String description = "Current value: " + dataSet.getVal() + dataSet.getUnit(); + ValueType valueType = ValueType.DOUBLE; + Integer valueTypeLength = null; + Boolean readable = true; + Boolean writable = false; + ChannelScanInfo channelInfo = new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength, readable, + writable); + channelInfos.add(channelInfo); + } + + } catch (Exception e) { + e.printStackTrace(); + logger.warn(name + "read failed"); + } + return channelInfos; + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#isWorking() + */ + @Override + public boolean isWorking() { + try { + byte[] frame = receiver.receiveMessage(1000); + ModeDMessage message = new ModeDMessage(frame); + message.parse(); + return true; + } catch (Exception e) { + return false; + } + + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/SmlConnection.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/SmlConnection.java index d9413707..2e01189f 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/SmlConnection.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/SmlConnection.java @@ -23,6 +23,12 @@ import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.data.ValueType; +import org.openmuc.framework.driver.spi.ChannelRecordContainer; +import org.openmuc.framework.driver.spi.ConnectionException; +import org.openmuc.jsml.structures.*; +import org.openmuc.jsml.tl.SML_SerialReceiver; import java.io.IOException; import java.util.LinkedHashMap; @@ -30,216 +36,187 @@ import java.util.List; import java.util.Map; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.jsml.structures.ASNObject; -import org.openmuc.jsml.structures.Integer16; -import org.openmuc.jsml.structures.Integer32; -import org.openmuc.jsml.structures.Integer64; -import org.openmuc.jsml.structures.Integer8; -import org.openmuc.jsml.structures.SML_File; -import org.openmuc.jsml.structures.SML_GetListRes; -import org.openmuc.jsml.structures.SML_ListEntry; -import org.openmuc.jsml.structures.SML_Message; -import org.openmuc.jsml.structures.SML_MessageBody; -import org.openmuc.jsml.structures.Unsigned16; -import org.openmuc.jsml.structures.Unsigned32; -import org.openmuc.jsml.structures.Unsigned64; -import org.openmuc.jsml.structures.Unsigned8; -import org.openmuc.jsml.tl.SML_SerialReceiver; - /** * @author Frederic Robra - * */ public class SmlConnection extends GeneralConnection { - private final SML_SerialReceiver receiver; - private String serverID; - - public SmlConnection(String deviceAddress) throws ConnectionException { - name = "SML - " + deviceAddress + " - "; - receiver = new SML_SerialReceiver(); - try { - receiver.setupComPort(deviceAddress); - } catch (IOException e) { - throw new ConnectionException(); - } catch (PortInUseException e) { - throw new ConnectionException("Port in use"); - } catch (UnsupportedCommOperationException e) { - throw new ConnectionException("Unsupported comm operation"); - } - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#close() - */ - @Override - public void close() { - try { - receiver.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#read(java.util.List, int) - */ - @Override - public void read(List containers, int timeout) throws ConnectionException { - logger.trace(name + "reading channels"); - try { - long timestamp = System.currentTimeMillis(); - SML_ListEntry[] list = getSML_ListEntries(); - - Map values = new LinkedHashMap(); - for (SML_ListEntry entry : list) { - String address = getAddress(entry.getObjName().getOctetString()); - double value = getValue(entry); - values.put(address, value); - logger.trace(name + address + " = " + value); - } - - handleChannelRecordContainer(containers, values, timestamp); - } catch (IOException e) { - e.printStackTrace(); - logger.error(name + "read failed"); - close(); - throw new ConnectionException(e); - } - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#listChannels(int) - */ - @Override - public List listChannels(int timeout) { - List channelInfos = new LinkedList(); - - logger.debug(name + "scanning channels"); - try { - SML_ListEntry[] list = getSML_ListEntries(); - for (SML_ListEntry entry : list) { - String channelAddress = getAddress(entry.getObjName().getOctetString()); - String description = "Current value: " + getValue(entry); // TODO entry.getUnit(); - ValueType valueType = ValueType.DOUBLE; - Integer valueTypeLength = null; - Boolean readable = true; - Boolean writable = false; - ChannelScanInfo channelInfo = new ChannelScanInfo(channelAddress, description, valueType, - valueTypeLength, readable, writable); - channelInfos.add(channelInfo); - } - } catch (IOException e) { - e.printStackTrace(); - logger.error(name + "read failed"); - } - return channelInfos; - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.ehz.Connection#isWorking() - */ - @Override - public boolean isWorking() { - try { - getSML_ListEntries(); - return true; - } catch (IOException e) { - return false; - } - } - - private SML_ListEntry[] getSML_ListEntries() throws IOException { - SML_File smlFile = receiver.getSMLFile(); - - List messages = smlFile.getMessages(); - - SML_ListEntry[] list = null; - - for (SML_Message message : messages) { - int tag = message.getMessageBody().getTag().getVal(); - - if (tag == SML_MessageBody.GetListResponse) { - SML_GetListRes resp = (SML_GetListRes) message.getMessageBody().getChoice(); - - if (serverID == null) { - serverID = ""; - for (Byte b : resp.getServerId().getOctetString()) { - serverID += Integer.toString((b & 0xff) + 0x100, 16).substring(1); - } - serverID = serverID.toUpperCase(); - } - - list = resp.getValList().getValListEntry(); - break; - } - } - return list; - } - - private String getAddress(byte[] data) { - StringBuilder address = new StringBuilder(data.length * 2); - for (byte b : data) { - address.append(String.format("%x", b)); - } - return address.toString(); - } - - // TODO return OpenMUC value - private double getValue(SML_ListEntry entry) { - double value = 0; - - ASNObject obj = entry.getValue().getChoice(); - if (obj.getClass().equals(Integer64.class)) { - Integer64 val = (Integer64) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Integer32.class)) { - Integer32 val = (Integer32) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Integer16.class)) { - Integer16 val = (Integer16) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Integer8.class)) { - Integer8 val = (Integer8) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Unsigned64.class)) { - Unsigned64 val = (Unsigned64) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Unsigned32.class)) { - Unsigned32 val = (Unsigned32) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Unsigned16.class)) { - Unsigned16 val = (Unsigned16) obj; - value = val.getVal(); - } - else if (obj.getClass().equals(Unsigned8.class)) { - Unsigned8 val = (Unsigned8) obj; - value = val.getVal(); - } - else { - return Double.NaN; - } - - byte scaler = entry.getScaler().getVal(); - return value * Math.pow(10, scaler); - } + private final SML_SerialReceiver receiver; + private String serverID; + + public SmlConnection(String deviceAddress) throws ConnectionException { + name = "SML - " + deviceAddress + " - "; + receiver = new SML_SerialReceiver(); + try { + receiver.setupComPort(deviceAddress); + } catch (IOException e) { + throw new ConnectionException(); + } catch (PortInUseException e) { + throw new ConnectionException("Port in use"); + } catch (UnsupportedCommOperationException e) { + throw new ConnectionException("Unsupported comm operation"); + } + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#close() + */ + @Override + public void close() { + try { + receiver.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#read(java.util.List, int) + */ + @Override + public void read(List containers, int timeout) throws ConnectionException { + logger.trace(name + "reading channels"); + try { + long timestamp = System.currentTimeMillis(); + SML_ListEntry[] list = getSML_ListEntries(); + + Map values = new LinkedHashMap(); + for (SML_ListEntry entry : list) { + String address = getAddress(entry.getObjName().getOctetString()); + double value = getValue(entry); + values.put(address, value); + logger.trace(name + address + " = " + value); + } + + handleChannelRecordContainer(containers, values, timestamp); + } catch (IOException e) { + e.printStackTrace(); + logger.error(name + "read failed"); + close(); + throw new ConnectionException(e); + } + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#listChannels(int) + */ + @Override + public List listChannels(int timeout) { + List channelInfos = new LinkedList(); + + logger.debug(name + "scanning channels"); + try { + SML_ListEntry[] list = getSML_ListEntries(); + for (SML_ListEntry entry : list) { + String channelAddress = getAddress(entry.getObjName().getOctetString()); + String description = "Current value: " + getValue(entry); // TODO entry.getUnit(); + ValueType valueType = ValueType.DOUBLE; + Integer valueTypeLength = null; + Boolean readable = true; + Boolean writable = false; + ChannelScanInfo channelInfo = new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength, readable, + writable); + channelInfos.add(channelInfo); + } + } catch (IOException e) { + e.printStackTrace(); + logger.error(name + "read failed"); + } + return channelInfos; + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.ehz.Connection#isWorking() + */ + @Override + public boolean isWorking() { + try { + getSML_ListEntries(); + return true; + } catch (IOException e) { + return false; + } + } + + private SML_ListEntry[] getSML_ListEntries() throws IOException { + SML_File smlFile = receiver.getSMLFile(); + + List messages = smlFile.getMessages(); + + SML_ListEntry[] list = null; + + for (SML_Message message : messages) { + int tag = message.getMessageBody().getTag().getVal(); + + if (tag == SML_MessageBody.GetListResponse) { + SML_GetListRes resp = (SML_GetListRes) message.getMessageBody().getChoice(); + + if (serverID == null) { + serverID = ""; + for (Byte b : resp.getServerId().getOctetString()) { + serverID += Integer.toString((b & 0xff) + 0x100, 16).substring(1); + } + serverID = serverID.toUpperCase(); + } + + list = resp.getValList().getValListEntry(); + break; + } + } + return list; + } + + private String getAddress(byte[] data) { + StringBuilder address = new StringBuilder(data.length * 2); + for (byte b : data) { + address.append(String.format("%x", b)); + } + return address.toString(); + } + + // TODO return OpenMUC value + private double getValue(SML_ListEntry entry) { + double value = 0; + + ASNObject obj = entry.getValue().getChoice(); + if (obj.getClass().equals(Integer64.class)) { + Integer64 val = (Integer64) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Integer32.class)) { + Integer32 val = (Integer32) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Integer16.class)) { + Integer16 val = (Integer16) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Integer8.class)) { + Integer8 val = (Integer8) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Unsigned64.class)) { + Unsigned64 val = (Unsigned64) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Unsigned32.class)) { + Unsigned32 val = (Unsigned32) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Unsigned16.class)) { + Unsigned16 val = (Unsigned16) obj; + value = val.getVal(); + } else if (obj.getClass().equals(Unsigned8.class)) { + Unsigned8 val = (Unsigned8) obj; + value = val.getVal(); + } else { + return Double.NaN; + } + + byte scaler = entry.getScaler().getVal(); + return value * Math.pow(10, scaler); + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/DataSet.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/DataSet.java index eaf56bee..8f331f88 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/DataSet.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/DataSet.java @@ -22,46 +22,45 @@ package org.openmuc.framework.driver.ehz.iec62056_21; public class DataSet { - private String address = null; - private String value = null; - private String unit = null; + private String address = null; + private String value = null; + private String unit = null; - public DataSet(String dataSet) { - int bracket = dataSet.indexOf('('); + public DataSet(String dataSet) { + int bracket = dataSet.indexOf('('); - address = dataSet.substring(0, bracket); + address = dataSet.substring(0, bracket); - dataSet = dataSet.substring(bracket); + dataSet = dataSet.substring(bracket); - int separator = dataSet.indexOf('*'); + int separator = dataSet.indexOf('*'); - if (separator == -1) { - value = dataSet.substring(1, dataSet.length() - 2); - } - else { - value = dataSet.substring(1, separator); - unit = dataSet.substring(separator + 1, dataSet.length() - 1); - } - } + if (separator == -1) { + value = dataSet.substring(1, dataSet.length() - 2); + } else { + value = dataSet.substring(1, separator); + unit = dataSet.substring(separator + 1, dataSet.length() - 1); + } + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public double getVal() { - try { - return Double.parseDouble(value); - } catch (NumberFormatException e) { - return Double.NaN; - } - } + public double getVal() { + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) { + return Double.NaN; + } + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public String getUnit() { - return unit; - } + public String getUnit() { + return unit; + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/IecReceiver.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/IecReceiver.java index 652f1e89..be693bd3 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/IecReceiver.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/IecReceiver.java @@ -25,142 +25,140 @@ import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.DataInputStream; import java.io.IOException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class IecReceiver { - private static Logger logger = LoggerFactory.getLogger(IecReceiver.class); - // public final static int PROTOCOL_NORMAL = 0; - // public final static int PROTOCOL_SECONDARY = 1; - // public final static int PROTOCOL_HDLC = 2; - // - // public final static int MODE_DATA_READOUT = 0; - // public final static int MODE_PROGRAMMING = 1; - // public final static int MODE_BINARY_HDLC = 2;, - - private CommPortIdentifier portId; - private SerialPort serialPort; - private final byte[] msgBuffer = new byte[10000]; - private final byte[] inputBuffer = new byte[2000]; - private DataInputStream inStream; - - private class Timeout extends Thread { - private final long time; - private boolean end; - - public Timeout(long msTimeout) { - time = msTimeout; - end = false; - } - - @Override - public void run() { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - } - end = true; - return; - } - - public boolean isEnd() { - return end; - } - } - - public IecReceiver(String iface) throws Exception { - try { - portId = CommPortIdentifier.getPortIdentifier(iface); - serialPort = (SerialPort) portId.open("ehz_connector", 2000); - - serialPort.setSerialPortParams(9600, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); - - inStream = new DataInputStream(serialPort.getInputStream()); - - if (inStream.available() > 0) { - inStream.read(inputBuffer); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } catch (PortInUseException e) { - throw new Exception("Port " + iface + " in use!"); - } catch (UnsupportedCommOperationException e) { - throw new Exception("Error setting communication parameters!"); - } catch (IOException e) { - throw new Exception("Cannot catch output stream!"); - } - - } - - public byte[] receiveMessage(long msTimeout) throws IOException { - Timeout time = new Timeout(msTimeout); - time.start(); - - int bufferIndex = 0; - boolean start = false; - boolean end = false; - inStream.skip(inStream.available()); // inStream to current state - - do { - if (inStream.available() > 0) { - int read = inStream.read(inputBuffer); - - for (int i = 0; i < read; i++) { - byte input = inputBuffer[i]; - if (input == '/' && !start) { - start = true; - bufferIndex = 0; - } - msgBuffer[bufferIndex] = input; - bufferIndex++; - if (input == '!' && start) { - end = true; - } - } - } - if (end && start) { - break; - } - - try { - Thread.sleep(50); - } catch (InterruptedException e) { - } - } while (!time.isEnd()); - - if (time.isEnd()) { - throw new IOException("Timeout"); - } - - byte[] frame = new byte[bufferIndex]; - - for (int i = 0; i < bufferIndex; i++) { - frame[i] = msgBuffer[i]; - } - - return frame; - } - - public void changeBaudrate(int baudrate) { - try { - logger.debug("Change baudrate to: " + baudrate); - serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, - SerialPort.PARITY_EVEN); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void close() { - serialPort.close(); - serialPort = null; - } + private static Logger logger = LoggerFactory.getLogger(IecReceiver.class); + // public final static int PROTOCOL_NORMAL = 0; + // public final static int PROTOCOL_SECONDARY = 1; + // public final static int PROTOCOL_HDLC = 2; + // + // public final static int MODE_DATA_READOUT = 0; + // public final static int MODE_PROGRAMMING = 1; + // public final static int MODE_BINARY_HDLC = 2;, + + private CommPortIdentifier portId; + private SerialPort serialPort; + private final byte[] msgBuffer = new byte[10000]; + private final byte[] inputBuffer = new byte[2000]; + private DataInputStream inStream; + + private class Timeout extends Thread { + private final long time; + private boolean end; + + public Timeout(long msTimeout) { + time = msTimeout; + end = false; + } + + @Override + public void run() { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + } + end = true; + return; + } + + public boolean isEnd() { + return end; + } + } + + public IecReceiver(String iface) throws Exception { + try { + portId = CommPortIdentifier.getPortIdentifier(iface); + serialPort = (SerialPort) portId.open("ehz_connector", 2000); + + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); + + inStream = new DataInputStream(serialPort.getInputStream()); + + if (inStream.available() > 0) { + inStream.read(inputBuffer); + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } catch (PortInUseException e) { + throw new Exception("Port " + iface + " in use!"); + } catch (UnsupportedCommOperationException e) { + throw new Exception("Error setting communication parameters!"); + } catch (IOException e) { + throw new Exception("Cannot catch output stream!"); + } + + } + + public byte[] receiveMessage(long msTimeout) throws IOException { + Timeout time = new Timeout(msTimeout); + time.start(); + + int bufferIndex = 0; + boolean start = false; + boolean end = false; + inStream.skip(inStream.available()); // inStream to current state + + do { + if (inStream.available() > 0) { + int read = inStream.read(inputBuffer); + + for (int i = 0; i < read; i++) { + byte input = inputBuffer[i]; + if (input == '/' && !start) { + start = true; + bufferIndex = 0; + } + msgBuffer[bufferIndex] = input; + bufferIndex++; + if (input == '!' && start) { + end = true; + } + } + } + if (end && start) { + break; + } + + try { + Thread.sleep(50); + } catch (InterruptedException e) { + } + } while (!time.isEnd()); + + if (time.isEnd()) { + throw new IOException("Timeout"); + } + + byte[] frame = new byte[bufferIndex]; + + for (int i = 0; i < bufferIndex; i++) { + frame[i] = msgBuffer[i]; + } + + return frame; + } + + public void changeBaudrate(int baudrate) { + try { + logger.debug("Change baudrate to: " + baudrate); + serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void close() { + serialPort.close(); + serialPort = null; + } } diff --git a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/ModeDMessage.java b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/ModeDMessage.java index ad9783ca..5742b9fb 100644 --- a/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/ModeDMessage.java +++ b/projects/driver/ehz/src/main/java/org/openmuc/framework/driver/ehz/iec62056_21/ModeDMessage.java @@ -27,90 +27,90 @@ public class ModeDMessage { - private final byte[] frame; + private final byte[] frame; - private String vendorID; - private String identifier; - private List dataSets; + private String vendorID; + private String identifier; + private List dataSets; - public List getDataSets() { - return dataSets; - } + public List getDataSets() { + return dataSets; + } - public ModeDMessage(byte[] frame) { - this.frame = frame; - } + public ModeDMessage(byte[] frame) { + this.frame = frame; + } - public String getVendorID() { - return vendorID; - } + public String getVendorID() { + return vendorID; + } - public String getIdentifier() { - return identifier; - } + public String getIdentifier() { + return identifier; + } - public void parse() throws ParseException { - int position = 0; - try { - /* Check for start sign */ - if (frame[0] != '/') { - throw new ParseException("Invalid character", 0); - } + public void parse() throws ParseException { + int position = 0; + try { + /* Check for start sign */ + if (frame[0] != '/') { + throw new ParseException("Invalid character", 0); + } /* Check for valid vendor ID (only upper case letters) */ - for (position = 1; position < 4; position++) { - if (!(frame[position] > 64 && frame[position] < 91)) { - throw new ParseException("Invalid character", position); - } - } + for (position = 1; position < 4; position++) { + if (!(frame[position] > 64 && frame[position] < 91)) { + throw new ParseException("Invalid character", position); + } + } - vendorID = new String(frame, 1, 3); + vendorID = new String(frame, 1, 3); /* Baud rate sign needs to be '0' .. '6' */ - if (frame[4] <= '0' || frame[4] >= '6') { - throw new ParseException("Invalid character", 4); - } + if (frame[4] <= '0' || frame[4] >= '6') { + throw new ParseException("Invalid character", 4); + } - position = 5; - int i = 0; + position = 5; + int i = 0; /* Search for CRLF to extract identifier */ - while (!((frame[position + i] == 0x0d) && (frame[position + i + 1] == 0x0a))) { - if (frame[position + i] == '!') { - throw new ParseException("Invalid end character", position + i); - } - i++; - } + while (!((frame[position + i] == 0x0d) && (frame[position + i + 1] == 0x0a))) { + if (frame[position + i] == '!') { + throw new ParseException("Invalid end character", position + i); + } + i++; + } - identifier = new String(frame, 5, i - 1); + identifier = new String(frame, 5, i - 1); - position += i; + position += i; /* Skip next CRLF */ - position += 4; + position += 4; /* Get data sets */ - dataSets = new ArrayList(); + dataSets = new ArrayList(); - while (frame[position] != '!') { + while (frame[position] != '!') { - i = 0; + i = 0; - while (frame[position + i] != 0x0d) { - i++; - } + while (frame[position + i] != 0x0d) { + i++; + } - String dataSet = new String(frame, position, i); + String dataSet = new String(frame, position, i); - dataSets.add(dataSet); + dataSets.add(dataSet); - position += (i + 2); + position += (i + 2); - } + } - } catch (IndexOutOfBoundsException e) { - throw new ParseException("Unexpected end of message", position); - } + } catch (IndexOutOfBoundsException e) { + throw new ParseException("Unexpected end of message", position); + } - } + } } diff --git a/projects/driver/ehz/src/main/resources/OSGI-INF/components.xml b/projects/driver/ehz/src/main/resources/OSGI-INF/components.xml index c654acc6..4bc65117 100644 --- a/projects/driver/ehz/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/ehz/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/iec61850/build.gradle b/projects/driver/iec61850/build.gradle index 2de94d68..81481a22 100644 --- a/projects/driver/iec61850/build.gradle +++ b/projects/driver/iec61850/build.gradle @@ -1,31 +1,30 @@ - configurations.create('embed') def openiec61850version = "1.1.1" def jasn1version = "1.4" dependencies { - compile project(':openmuc-core-spi') - compile group: 'org.openmuc', name: 'openiec61850', version: openiec61850version + compile project(':openmuc-core-spi') + compile group: 'org.openmuc', name: 'openiec61850', version: openiec61850version - embed group: 'org.openmuc', name: 'openiec61850', version: openiec61850version - embed group: 'org.openmuc', name: 'josistack', version: openiec61850version - embed group: 'org.openmuc', name: 'jositransport', version: openiec61850version - embed group: 'org.openmuc', name: 'jasn1', version: jasn1version + embed group: 'org.openmuc', name: 'openiec61850', version: openiec61850version + embed group: 'org.openmuc', name: 'josistack', version: openiec61850version + embed group: 'org.openmuc', name: 'jositransport', version: openiec61850version + embed group: 'org.openmuc', name: 'jasn1', version: jasn1version } jar { - manifest { - name = "OpenMUC Driver - IEC 61850" - instruction 'Bundle-ClassPath', '.,lib/openiec61850-' + openiec61850version + '.jar,lib/josistack-' + openiec61850version + '.jar,lib/jositransport-' + openiec61850version + '.jar,lib/jasn1-' + jasn1version + '.jar' - instruction 'Import-Package', '!org.openmuc.openiec61850.*,javax.net,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - IEC 61850" + instruction 'Bundle-ClassPath', '.,lib/openiec61850-' + openiec61850version + '.jar,lib/josistack-' + openiec61850version + '.jar,lib/jositransport-' + openiec61850version + '.jar,lib/jasn1-' + jasn1version + '.jar' + instruction 'Import-Package', '!org.openmuc.openiec61850.*,javax.net,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Connection.java b/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Connection.java index aa7cff52..cb52a266 100644 --- a/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Connection.java +++ b/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Connection.java @@ -20,690 +20,643 @@ */ package org.openmuc.framework.driver.iec61850; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.data.*; +import org.openmuc.framework.driver.spi.*; +import org.openmuc.openiec61850.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import org.openmuc.openiec61850.BasicDataAttribute; -import org.openmuc.openiec61850.BdaBitString; -import org.openmuc.openiec61850.BdaBoolean; -import org.openmuc.openiec61850.BdaEntryTime; -import org.openmuc.openiec61850.BdaFloat32; -import org.openmuc.openiec61850.BdaFloat64; -import org.openmuc.openiec61850.BdaInt16; -import org.openmuc.openiec61850.BdaInt16U; -import org.openmuc.openiec61850.BdaInt32; -import org.openmuc.openiec61850.BdaInt32U; -import org.openmuc.openiec61850.BdaInt64; -import org.openmuc.openiec61850.BdaInt8; -import org.openmuc.openiec61850.BdaInt8U; -import org.openmuc.openiec61850.BdaOctetString; -import org.openmuc.openiec61850.BdaTimestamp; -import org.openmuc.openiec61850.BdaUnicodeString; -import org.openmuc.openiec61850.BdaVisibleString; -import org.openmuc.openiec61850.ClientAssociation; -import org.openmuc.openiec61850.Fc; -import org.openmuc.openiec61850.FcModelNode; -import org.openmuc.openiec61850.ModelNode; -import org.openmuc.openiec61850.ServerModel; -import org.openmuc.openiec61850.ServiceError; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public final class Iec61850Connection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(Iec61850Connection.class); - - private final static String STRING_SEPARATOR = ","; - - private final ClientAssociation clientAssociation; - private final ServerModel serverModel; - - public Iec61850Connection(ClientAssociation clientAssociation, ServerModel serverModel) { - this.clientAssociation = clientAssociation; - this.serverModel = serverModel; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - List bdas = serverModel.getBasicDataAttributes(); - - List scanInfos = new ArrayList(bdas.size()); - - for (BasicDataAttribute bda : bdas) { - - String channelAddress = bda.getReference() + ":" + bda.getFc(); - - switch (bda.getBasicType()) { - - case CHECK: - case DOUBLE_BIT_POS: - case OPTFLDS: - case QUALITY: - case REASON_FOR_INCLUSION: - case TAP_COMMAND: - case TRIGGER_CONDITIONS: - case ENTRY_TIME: - case OCTET_STRING: - case VISIBLE_STRING: - case UNICODE_STRING: - bda.setDefault(); - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BYTE_ARRAY, ((BdaBitString) bda) - .getValue().length)); - break; - case TIMESTAMP: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.LONG, null)); - break; - case BOOLEAN: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BOOLEAN, null)); - break; - case FLOAT32: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.FLOAT, null)); - break; - case FLOAT64: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.DOUBLE, null)); - break; - case INT8: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BYTE, null)); - break; - case INT8U: - case INT16: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.SHORT, null)); - break; - case INT16U: - case INT32: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.INTEGER, null)); - break; - case INT32U: - case INT64: - scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.LONG, null)); - break; - default: - throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); - } - - } - - return scanInfos; - - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelRecordContainer container : containers) { - - if (container.getChannelHandle() == null) { - - String[] args = container.getChannelAddress().split(":", 3); - - if (args.length != 2) { - logger.debug("Wrong channel address syntax: {}", container.getChannelAddress()); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); - continue; - } - - ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); - - if (modelNode == null) { - logger.debug("No Basic Data Attribute for the channel address {} was found in the server model.", - container.getChannelAddress()); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); - continue; - } - - FcModelNode fcModelNode; - try { - fcModelNode = (FcModelNode) modelNode; - } catch (ClassCastException e) { - logger.debug( - "ModelNode with object reference {} was found in the server model but is not a Basic Data Attribute.", - container.getChannelAddress()); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); - continue; - } - - container.setChannelHandle(fcModelNode); - - } - } - - if (!samplingGroup.isEmpty()) { - - FcModelNode fcModelNode; - if (containerListHandle != null) { - fcModelNode = (FcModelNode) containerListHandle; - } - - else { - - String[] args = samplingGroup.split(":", 3); - - if (args.length != 2) { - logger.debug("Wrong sampling group syntax: {}", samplingGroup); - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); - } - return null; - } - - ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); - - if (modelNode == null) { - logger.debug( - "Error reading sampling group: no FCDO/DA or DataSet with object reference {} was not found in the server model.", - samplingGroup); - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); - } - return null; - } - - try { - fcModelNode = (FcModelNode) modelNode; - } catch (ClassCastException e) { - logger.debug( - "Error reading channel: ModelNode with sampling group reference {} was found in the server model but is not a FcModelNode.", - samplingGroup); - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); - } - return null; - } - - } - - try { - clientAssociation.getDataValues(fcModelNode); - } catch (ServiceError e) { - logger.debug("Error reading sampling group: service error calling getDataValues on {}: {}", - samplingGroup, e); - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE)); - } - return fcModelNode; - } catch (IOException e) { - throw new ConnectionException(e); - } - - long receiveTime = System.currentTimeMillis(); - - for (ChannelRecordContainer container : containers) { - if (container.getChannelHandle() != null) { - setRecord(container, (BasicDataAttribute) container.getChannelHandle(), receiveTime); - } - else { - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP)); - } - } - - return fcModelNode; - - } - // sampling group is empty - else { - - for (ChannelRecordContainer container : containers) { - - if (container.getChannelHandle() == null) { - continue; - } - FcModelNode fcModelNode = (FcModelNode) container.getChannelHandle(); - try { - clientAssociation.getDataValues(fcModelNode); - } catch (ServiceError e) { - logger.debug("Error reading channel: service error calling getDataValues on {}: {}", - container.getChannelAddress(), e); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); - continue; - } catch (IOException e) { - throw new ConnectionException(e); - } - - if (fcModelNode instanceof BasicDataAttribute) { - long receiveTime = System.currentTimeMillis(); - setRecord(container, (BasicDataAttribute) fcModelNode, receiveTime); - } - else { - StringBuilder sb = new StringBuilder(""); - for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { - sb.append(bda2String(bda) + STRING_SEPARATOR); - } - sb.delete(sb.length() - 1, sb.length());// remove last separator - long receiveTime = System.currentTimeMillis(); - setRecord(container, sb.toString(), receiveTime); - } - } - return null; - } - - } - - private String bda2String(BasicDataAttribute bda) { - String result; - switch (bda.getBasicType()) { - case CHECK: - case DOUBLE_BIT_POS: - case OPTFLDS: - case QUALITY: - case REASON_FOR_INCLUSION: - case TAP_COMMAND: - case TRIGGER_CONDITIONS: - case ENTRY_TIME: - case OCTET_STRING: - case VISIBLE_STRING: - case UNICODE_STRING: - result = new String(((BdaBitString) bda).getValue()); - break; - case TIMESTAMP: - Date date = ((BdaTimestamp) bda).getDate(); - result = date == null ? "" : ("" + date.getTime()); - break; - case BOOLEAN: - result = String.valueOf(((BdaBoolean) bda).getValue()); - break; - case FLOAT32: - result = String.valueOf(((BdaFloat32) bda).getFloat()); - break; - case FLOAT64: - result = String.valueOf(((BdaFloat64) bda).getDouble()); - break; - case INT8: - result = String.valueOf(((BdaInt8) bda).getValue()); - break; - case INT8U: - result = String.valueOf(((BdaInt8U) bda).getValue()); - break; - case INT16: - result = String.valueOf(((BdaInt16) bda).getValue()); - break; - case INT16U: - result = String.valueOf(((BdaInt16U) bda).getValue()); - break; - case INT32: - result = String.valueOf(((BdaInt32) bda).getValue()); - break; - case INT32U: - result = String.valueOf(((BdaInt32U) bda).getValue()); - break; - case INT64: - result = String.valueOf(((BdaInt64) bda).getValue()); - break; - default: - throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); - } - return result; - } - - private void setRecord(ChannelRecordContainer container, String stringValue, long receiveTime) { - container.setRecord(new Record(new ByteArrayValue(stringValue.getBytes(), true), receiveTime)); - } - - private void setRecord(ChannelRecordContainer container, BasicDataAttribute bda, long receiveTime) { - switch (bda.getBasicType()) { - case CHECK: - case DOUBLE_BIT_POS: - case OPTFLDS: - case QUALITY: - case REASON_FOR_INCLUSION: - case TAP_COMMAND: - case TRIGGER_CONDITIONS: - container.setRecord(new Record(new ByteArrayValue(((BdaBitString) bda).getValue(), true), receiveTime)); - break; - case ENTRY_TIME: - container.setRecord(new Record(new ByteArrayValue(((BdaEntryTime) bda).getValue(), true), receiveTime)); - break; - case OCTET_STRING: - container.setRecord(new Record(new ByteArrayValue(((BdaOctetString) bda).getValue(), true), receiveTime)); - break; - case VISIBLE_STRING: - container.setRecord(new Record(new StringValue(((BdaVisibleString) bda).getStringValue()), receiveTime)); - break; - case UNICODE_STRING: - container.setRecord(new Record(new ByteArrayValue(((BdaUnicodeString) bda).getValue(), true), receiveTime)); - break; - case TIMESTAMP: - Date date = ((BdaTimestamp) bda).getDate(); - if (date == null) { - container.setRecord(new Record(new LongValue(-1l), receiveTime)); - } - else { - container.setRecord(new Record(new LongValue(date.getTime()), receiveTime)); - } - break; - case BOOLEAN: - container.setRecord(new Record(new BooleanValue(((BdaBoolean) bda).getValue()), receiveTime)); - break; - case FLOAT32: - container.setRecord(new Record(new FloatValue(((BdaFloat32) bda).getFloat()), receiveTime)); - break; - case FLOAT64: - container.setRecord(new Record(new DoubleValue(((BdaFloat64) bda).getDouble()), receiveTime)); - break; - case INT8: - container.setRecord(new Record(new DoubleValue(((BdaInt8) bda).getValue()), receiveTime)); - break; - case INT8U: - container.setRecord(new Record(new DoubleValue(((BdaInt8U) bda).getValue()), receiveTime)); - break; - case INT16: - container.setRecord(new Record(new DoubleValue(((BdaInt16) bda).getValue()), receiveTime)); - break; - case INT16U: - container.setRecord(new Record(new DoubleValue(((BdaInt16U) bda).getValue()), receiveTime)); - break; - case INT32: - container.setRecord(new Record(new DoubleValue(((BdaInt32) bda).getValue()), receiveTime)); - break; - case INT32U: - container.setRecord(new Record(new DoubleValue(((BdaInt32U) bda).getValue()), receiveTime)); - break; - case INT64: - container.setRecord(new Record(new DoubleValue(((BdaInt64) bda).getValue()), receiveTime)); - break; - default: - throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); - } - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - - List modelNodesToBeWritten = new ArrayList(containers.size()); - for (ChannelValueContainer container : containers) { - - if (container.getChannelHandle() != null) { - modelNodesToBeWritten.add((FcModelNode) container.getChannelHandle()); - setFcModelNode(container, (FcModelNode) container.getChannelHandle()); - } - else { - - String[] args = container.getChannelAddress().split(":", 3); - - if (args.length != 2) { - logger.debug("Wrong channel address syntax: {}", container.getChannelAddress()); - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); - continue; - } - - ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); - - if (modelNode == null) { - logger.debug("No Basic Data Attribute for the channel address {} was found in the server model.", - container.getChannelAddress()); - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); - continue; - } - - FcModelNode fcModelNode; - try { - fcModelNode = (FcModelNode) modelNode; - - } catch (ClassCastException e) { - logger.debug( - "ModelNode with object reference {} was found in the server model but is not a Basic Data Attribute.", - container.getChannelAddress()); - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); - continue; - } - container.setChannelHandle(fcModelNode); - modelNodesToBeWritten.add(fcModelNode); - setFcModelNode(container, fcModelNode); - - } - } - - // TODO - // first check all datasets if the are some that contain only requested channels - // then check all remaining model nodes - - List fcNodesToBeRequested = new ArrayList(); - - while (modelNodesToBeWritten.size() > 0) { - fillRequestedNodes(fcNodesToBeRequested, modelNodesToBeWritten, serverModel); - } - - for (FcModelNode fcModelNode : fcNodesToBeRequested) { - try { - clientAssociation.setDataValues(fcModelNode); - } catch (ServiceError e) { - logger.debug("Error writing to channel: service error calling setDataValues on {}: {}", - fcModelNode.getReference(), e); - for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { - for (ChannelValueContainer valueContainer : containers) { - if (valueContainer.getChannelHandle() == bda) { - valueContainer.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); - } - } - } - return null; - } catch (IOException e) { - throw new ConnectionException(e); - } - for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { - for (ChannelValueContainer valueContainer : containers) { - if (valueContainer.getChannelHandle() == bda) { - valueContainer.setFlag(Flag.VALID); - } - } - } - } - - return null; - - } - - void fillRequestedNodes(List fcNodesToBeRequested, List remainingFcModelNodes, - ServerModel serverModel) { - - FcModelNode currentFcModelNode = remainingFcModelNodes.get(0); - - if (!checkParent(currentFcModelNode, fcNodesToBeRequested, remainingFcModelNodes, serverModel)) { - remainingFcModelNodes.remove(currentFcModelNode); - fcNodesToBeRequested.add(currentFcModelNode); - } - - } - - boolean checkParent(ModelNode modelNode, List fcNodesToBeRequested, - List remainingModelNodes, ServerModel serverModel) { - - if (!(modelNode instanceof FcModelNode)) { - return false; - } - - FcModelNode fcModelNode = (FcModelNode) modelNode; - - ModelNode parentNode = serverModel; - for (int i = 0; i < fcModelNode.getReference().size() - 1; i++) { - parentNode = parentNode.getChild(fcModelNode.getReference().get(i), fcModelNode.getFc()); - } - - List basicDataAttributes = parentNode.getBasicDataAttributes(); - for (BasicDataAttribute bda : basicDataAttributes) { - if (!remainingModelNodes.contains(bda)) { - return false; - } - } - - if (!checkParent(parentNode, fcNodesToBeRequested, remainingModelNodes, serverModel)) { - for (BasicDataAttribute bda : basicDataAttributes) { - remainingModelNodes.remove(bda); - } - fcNodesToBeRequested.add((FcModelNode) parentNode); - } - - return true; - } - - private void setFcModelNode(ChannelValueContainer container, FcModelNode fcModelNode) { - if (fcModelNode instanceof BasicDataAttribute) { - setBda(container, (BasicDataAttribute) fcModelNode); - } - else { - List bdas = fcModelNode.getBasicDataAttributes(); - String valueString = container.getValue().toString(); - String[] bdaValues = valueString.split(STRING_SEPARATOR); - if (bdaValues.length != bdas.size()) { - throw new IllegalStateException("attempt to write array " + valueString + " into fcModelNode " - + fcModelNode.getName() + " failed as the dimensions don't fit."); - } - for (int i = 0; i < bdaValues.length; i++) { - setBda(bdaValues[i], bdas.get(i)); - } - } - } - - private void setBda(String bdaValueString, BasicDataAttribute bda) { - switch (bda.getBasicType()) { - case CHECK: - case DOUBLE_BIT_POS: - case OPTFLDS: - case QUALITY: - case REASON_FOR_INCLUSION: - case TAP_COMMAND: - case TRIGGER_CONDITIONS: - ((BdaBitString) bda).setValue(bdaValueString.getBytes()); - break; - case ENTRY_TIME: - ((BdaEntryTime) bda).setValue(bdaValueString.getBytes()); - break; - case OCTET_STRING: - ((BdaOctetString) bda).setValue(bdaValueString.getBytes()); - break; - case VISIBLE_STRING: - ((BdaVisibleString) bda).setValue(bdaValueString); - break; - case UNICODE_STRING: - ((BdaUnicodeString) bda).setValue(bdaValueString.getBytes()); - break; - case TIMESTAMP: - ((BdaTimestamp) bda).setDate(new Date(Long.parseLong(bdaValueString))); - break; - case BOOLEAN: - ((BdaBoolean) bda).setValue(Boolean.parseBoolean(bdaValueString)); - break; - case FLOAT32: - ((BdaFloat32) bda).setFloat(Float.parseFloat(bdaValueString)); - break; - case FLOAT64: - ((BdaFloat64) bda).setDouble(Double.parseDouble(bdaValueString)); - break; - case INT8: - ((BdaInt8) bda).setValue(Byte.parseByte(bdaValueString)); - break; - case INT8U: - ((BdaInt8U) bda).setValue(Short.parseShort(bdaValueString)); - break; - case INT16: - ((BdaInt16) bda).setValue(Short.parseShort(bdaValueString)); - break; - case INT16U: - ((BdaInt16U) bda).setValue(Integer.parseInt(bdaValueString)); - break; - case INT32: - ((BdaInt32) bda).setValue(Integer.parseInt(bdaValueString)); - break; - case INT32U: - ((BdaInt32U) bda).setValue(Long.parseLong(bdaValueString)); - break; - case INT64: - ((BdaInt64) bda).setValue(Long.parseLong(bdaValueString)); - break; - default: - throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); - } - } - - private void setBda(ChannelValueContainer container, BasicDataAttribute bda) { - switch (bda.getBasicType()) { - case CHECK: - case DOUBLE_BIT_POS: - case OPTFLDS: - case QUALITY: - case REASON_FOR_INCLUSION: - case TAP_COMMAND: - case TRIGGER_CONDITIONS: - ((BdaBitString) bda).setValue(container.getValue().asByteArray()); - break; - case ENTRY_TIME: - ((BdaEntryTime) bda).setValue(container.getValue().asByteArray()); - break; - case OCTET_STRING: - ((BdaOctetString) bda).setValue(container.getValue().asByteArray()); - break; - case VISIBLE_STRING: - ((BdaVisibleString) bda).setValue(container.getValue().asString()); - break; - case UNICODE_STRING: - ((BdaUnicodeString) bda).setValue(container.getValue().asByteArray()); - break; - case TIMESTAMP: - ((BdaTimestamp) bda).setDate(new Date(container.getValue().asLong())); - break; - case BOOLEAN: - ((BdaBoolean) bda).setValue(container.getValue().asBoolean()); - break; - case FLOAT32: - ((BdaFloat32) bda).setFloat(container.getValue().asFloat()); - break; - case FLOAT64: - ((BdaFloat64) bda).setDouble(container.getValue().asDouble()); - break; - case INT8: - ((BdaInt8) bda).setValue(container.getValue().asByte()); - break; - case INT8U: - ((BdaInt8U) bda).setValue(container.getValue().asShort()); - break; - case INT16: - ((BdaInt16) bda).setValue(container.getValue().asShort()); - break; - case INT16U: - ((BdaInt16U) bda).setValue(container.getValue().asInt()); - break; - case INT32: - ((BdaInt32) bda).setValue(container.getValue().asInt()); - break; - case INT32U: - ((BdaInt32U) bda).setValue(container.getValue().asLong()); - break; - case INT64: - ((BdaInt64) bda).setValue(container.getValue().asLong()); - break; - default: - throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); - } - } - - @Override - public void disconnect() { - clientAssociation.close(); - } + private final static Logger logger = LoggerFactory.getLogger(Iec61850Connection.class); + + private final static String STRING_SEPARATOR = ","; + + private final ClientAssociation clientAssociation; + private final ServerModel serverModel; + + public Iec61850Connection(ClientAssociation clientAssociation, ServerModel serverModel) { + this.clientAssociation = clientAssociation; + this.serverModel = serverModel; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + List bdas = serverModel.getBasicDataAttributes(); + + List scanInfos = new ArrayList(bdas.size()); + + for (BasicDataAttribute bda : bdas) { + + String channelAddress = bda.getReference() + ":" + bda.getFc(); + + switch (bda.getBasicType()) { + + case CHECK: + case DOUBLE_BIT_POS: + case OPTFLDS: + case QUALITY: + case REASON_FOR_INCLUSION: + case TAP_COMMAND: + case TRIGGER_CONDITIONS: + case ENTRY_TIME: + case OCTET_STRING: + case VISIBLE_STRING: + case UNICODE_STRING: + bda.setDefault(); + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BYTE_ARRAY, ((BdaBitString) bda).getValue().length)); + break; + case TIMESTAMP: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.LONG, null)); + break; + case BOOLEAN: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BOOLEAN, null)); + break; + case FLOAT32: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.FLOAT, null)); + break; + case FLOAT64: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.DOUBLE, null)); + break; + case INT8: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.BYTE, null)); + break; + case INT8U: + case INT16: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.SHORT, null)); + break; + case INT16U: + case INT32: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.INTEGER, null)); + break; + case INT32U: + case INT64: + scanInfos.add(new ChannelScanInfo(channelAddress, "", ValueType.LONG, null)); + break; + default: + throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); + } + + } + + return scanInfos; + + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + for (ChannelRecordContainer container : containers) { + + if (container.getChannelHandle() == null) { + + String[] args = container.getChannelAddress().split(":", 3); + + if (args.length != 2) { + logger.debug("Wrong channel address syntax: {}", container.getChannelAddress()); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); + continue; + } + + ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); + + if (modelNode == null) { + logger.debug("No Basic Data Attribute for the channel address {} was found in the server model.", + container.getChannelAddress()); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); + continue; + } + + FcModelNode fcModelNode; + try { + fcModelNode = (FcModelNode) modelNode; + } catch (ClassCastException e) { + logger.debug("ModelNode with object reference {} was found in the server model but is not a Basic Data Attribute.", + container.getChannelAddress()); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); + continue; + } + + container.setChannelHandle(fcModelNode); + + } + } + + if (!samplingGroup.isEmpty()) { + + FcModelNode fcModelNode; + if (containerListHandle != null) { + fcModelNode = (FcModelNode) containerListHandle; + } else { + + String[] args = samplingGroup.split(":", 3); + + if (args.length != 2) { + logger.debug("Wrong sampling group syntax: {}", samplingGroup); + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); + } + return null; + } + + ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); + + if (modelNode == null) { + logger.debug( + "Error reading sampling group: no FCDO/DA or DataSet with object reference {} was not found in the server " + + "model.", + samplingGroup); + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); + } + return null; + } + + try { + fcModelNode = (FcModelNode) modelNode; + } catch (ClassCastException e) { + logger.debug( + "Error reading channel: ModelNode with sampling group reference {} was found in the server model but is not a" + + " FcModelNode.", + samplingGroup); + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_FOUND)); + } + return null; + } + + } + + try { + clientAssociation.getDataValues(fcModelNode); + } catch (ServiceError e) { + logger.debug("Error reading sampling group: service error calling getDataValues on {}: {}", samplingGroup, e); + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_SAMPLING_GROUP_NOT_ACCESSIBLE)); + } + return fcModelNode; + } catch (IOException e) { + throw new ConnectionException(e); + } + + long receiveTime = System.currentTimeMillis(); + + for (ChannelRecordContainer container : containers) { + if (container.getChannelHandle() != null) { + setRecord(container, (BasicDataAttribute) container.getChannelHandle(), receiveTime); + } else { + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_PART_OF_SAMPLING_GROUP)); + } + } + + return fcModelNode; + + } + // sampling group is empty + else { + + for (ChannelRecordContainer container : containers) { + + if (container.getChannelHandle() == null) { + continue; + } + FcModelNode fcModelNode = (FcModelNode) container.getChannelHandle(); + try { + clientAssociation.getDataValues(fcModelNode); + } catch (ServiceError e) { + logger.debug("Error reading channel: service error calling getDataValues on {}: {}", container.getChannelAddress(), e); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); + continue; + } catch (IOException e) { + throw new ConnectionException(e); + } + + if (fcModelNode instanceof BasicDataAttribute) { + long receiveTime = System.currentTimeMillis(); + setRecord(container, (BasicDataAttribute) fcModelNode, receiveTime); + } else { + StringBuilder sb = new StringBuilder(""); + for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { + sb.append(bda2String(bda) + STRING_SEPARATOR); + } + sb.delete(sb.length() - 1, sb.length());// remove last separator + long receiveTime = System.currentTimeMillis(); + setRecord(container, sb.toString(), receiveTime); + } + } + return null; + } + + } + + private String bda2String(BasicDataAttribute bda) { + String result; + switch (bda.getBasicType()) { + case CHECK: + case DOUBLE_BIT_POS: + case OPTFLDS: + case QUALITY: + case REASON_FOR_INCLUSION: + case TAP_COMMAND: + case TRIGGER_CONDITIONS: + case ENTRY_TIME: + case OCTET_STRING: + case VISIBLE_STRING: + case UNICODE_STRING: + result = new String(((BdaBitString) bda).getValue()); + break; + case TIMESTAMP: + Date date = ((BdaTimestamp) bda).getDate(); + result = date == null ? "" : ("" + date.getTime()); + break; + case BOOLEAN: + result = String.valueOf(((BdaBoolean) bda).getValue()); + break; + case FLOAT32: + result = String.valueOf(((BdaFloat32) bda).getFloat()); + break; + case FLOAT64: + result = String.valueOf(((BdaFloat64) bda).getDouble()); + break; + case INT8: + result = String.valueOf(((BdaInt8) bda).getValue()); + break; + case INT8U: + result = String.valueOf(((BdaInt8U) bda).getValue()); + break; + case INT16: + result = String.valueOf(((BdaInt16) bda).getValue()); + break; + case INT16U: + result = String.valueOf(((BdaInt16U) bda).getValue()); + break; + case INT32: + result = String.valueOf(((BdaInt32) bda).getValue()); + break; + case INT32U: + result = String.valueOf(((BdaInt32U) bda).getValue()); + break; + case INT64: + result = String.valueOf(((BdaInt64) bda).getValue()); + break; + default: + throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); + } + return result; + } + + private void setRecord(ChannelRecordContainer container, String stringValue, long receiveTime) { + container.setRecord(new Record(new ByteArrayValue(stringValue.getBytes(), true), receiveTime)); + } + + private void setRecord(ChannelRecordContainer container, BasicDataAttribute bda, long receiveTime) { + switch (bda.getBasicType()) { + case CHECK: + case DOUBLE_BIT_POS: + case OPTFLDS: + case QUALITY: + case REASON_FOR_INCLUSION: + case TAP_COMMAND: + case TRIGGER_CONDITIONS: + container.setRecord(new Record(new ByteArrayValue(((BdaBitString) bda).getValue(), true), receiveTime)); + break; + case ENTRY_TIME: + container.setRecord(new Record(new ByteArrayValue(((BdaEntryTime) bda).getValue(), true), receiveTime)); + break; + case OCTET_STRING: + container.setRecord(new Record(new ByteArrayValue(((BdaOctetString) bda).getValue(), true), receiveTime)); + break; + case VISIBLE_STRING: + container.setRecord(new Record(new StringValue(((BdaVisibleString) bda).getStringValue()), receiveTime)); + break; + case UNICODE_STRING: + container.setRecord(new Record(new ByteArrayValue(((BdaUnicodeString) bda).getValue(), true), receiveTime)); + break; + case TIMESTAMP: + Date date = ((BdaTimestamp) bda).getDate(); + if (date == null) { + container.setRecord(new Record(new LongValue(-1l), receiveTime)); + } else { + container.setRecord(new Record(new LongValue(date.getTime()), receiveTime)); + } + break; + case BOOLEAN: + container.setRecord(new Record(new BooleanValue(((BdaBoolean) bda).getValue()), receiveTime)); + break; + case FLOAT32: + container.setRecord(new Record(new FloatValue(((BdaFloat32) bda).getFloat()), receiveTime)); + break; + case FLOAT64: + container.setRecord(new Record(new DoubleValue(((BdaFloat64) bda).getDouble()), receiveTime)); + break; + case INT8: + container.setRecord(new Record(new DoubleValue(((BdaInt8) bda).getValue()), receiveTime)); + break; + case INT8U: + container.setRecord(new Record(new DoubleValue(((BdaInt8U) bda).getValue()), receiveTime)); + break; + case INT16: + container.setRecord(new Record(new DoubleValue(((BdaInt16) bda).getValue()), receiveTime)); + break; + case INT16U: + container.setRecord(new Record(new DoubleValue(((BdaInt16U) bda).getValue()), receiveTime)); + break; + case INT32: + container.setRecord(new Record(new DoubleValue(((BdaInt32) bda).getValue()), receiveTime)); + break; + case INT32U: + container.setRecord(new Record(new DoubleValue(((BdaInt32U) bda).getValue()), receiveTime)); + break; + case INT64: + container.setRecord(new Record(new DoubleValue(((BdaInt64) bda).getValue()), receiveTime)); + break; + default: + throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); + } + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + + List modelNodesToBeWritten = new ArrayList(containers.size()); + for (ChannelValueContainer container : containers) { + + if (container.getChannelHandle() != null) { + modelNodesToBeWritten.add((FcModelNode) container.getChannelHandle()); + setFcModelNode(container, (FcModelNode) container.getChannelHandle()); + } else { + + String[] args = container.getChannelAddress().split(":", 3); + + if (args.length != 2) { + logger.debug("Wrong channel address syntax: {}", container.getChannelAddress()); + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); + continue; + } + + ModelNode modelNode = serverModel.findModelNode(args[0], Fc.fromString(args[1])); + + if (modelNode == null) { + logger.debug("No Basic Data Attribute for the channel address {} was found in the server model.", + container.getChannelAddress()); + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); + continue; + } + + FcModelNode fcModelNode; + try { + fcModelNode = (FcModelNode) modelNode; + + } catch (ClassCastException e) { + logger.debug("ModelNode with object reference {} was found in the server model but is not a Basic Data Attribute.", + container.getChannelAddress()); + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND); + continue; + } + container.setChannelHandle(fcModelNode); + modelNodesToBeWritten.add(fcModelNode); + setFcModelNode(container, fcModelNode); + + } + } + + // TODO + // first check all datasets if the are some that contain only requested channels + // then check all remaining model nodes + + List fcNodesToBeRequested = new ArrayList(); + + while (modelNodesToBeWritten.size() > 0) { + fillRequestedNodes(fcNodesToBeRequested, modelNodesToBeWritten, serverModel); + } + + for (FcModelNode fcModelNode : fcNodesToBeRequested) { + try { + clientAssociation.setDataValues(fcModelNode); + } catch (ServiceError e) { + logger.debug("Error writing to channel: service error calling setDataValues on {}: {}", fcModelNode.getReference(), e); + for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { + for (ChannelValueContainer valueContainer : containers) { + if (valueContainer.getChannelHandle() == bda) { + valueContainer.setFlag(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE); + } + } + } + return null; + } catch (IOException e) { + throw new ConnectionException(e); + } + for (BasicDataAttribute bda : fcModelNode.getBasicDataAttributes()) { + for (ChannelValueContainer valueContainer : containers) { + if (valueContainer.getChannelHandle() == bda) { + valueContainer.setFlag(Flag.VALID); + } + } + } + } + + return null; + + } + + void fillRequestedNodes(List fcNodesToBeRequested, List remainingFcModelNodes, ServerModel serverModel) { + + FcModelNode currentFcModelNode = remainingFcModelNodes.get(0); + + if (!checkParent(currentFcModelNode, fcNodesToBeRequested, remainingFcModelNodes, serverModel)) { + remainingFcModelNodes.remove(currentFcModelNode); + fcNodesToBeRequested.add(currentFcModelNode); + } + + } + + boolean checkParent(ModelNode modelNode, List fcNodesToBeRequested, List remainingModelNodes, ServerModel + serverModel) { + + if (!(modelNode instanceof FcModelNode)) { + return false; + } + + FcModelNode fcModelNode = (FcModelNode) modelNode; + + ModelNode parentNode = serverModel; + for (int i = 0; i < fcModelNode.getReference().size() - 1; i++) { + parentNode = parentNode.getChild(fcModelNode.getReference().get(i), fcModelNode.getFc()); + } + + List basicDataAttributes = parentNode.getBasicDataAttributes(); + for (BasicDataAttribute bda : basicDataAttributes) { + if (!remainingModelNodes.contains(bda)) { + return false; + } + } + + if (!checkParent(parentNode, fcNodesToBeRequested, remainingModelNodes, serverModel)) { + for (BasicDataAttribute bda : basicDataAttributes) { + remainingModelNodes.remove(bda); + } + fcNodesToBeRequested.add((FcModelNode) parentNode); + } + + return true; + } + + private void setFcModelNode(ChannelValueContainer container, FcModelNode fcModelNode) { + if (fcModelNode instanceof BasicDataAttribute) { + setBda(container, (BasicDataAttribute) fcModelNode); + } else { + List bdas = fcModelNode.getBasicDataAttributes(); + String valueString = container.getValue().toString(); + String[] bdaValues = valueString.split(STRING_SEPARATOR); + if (bdaValues.length != bdas.size()) { + throw new IllegalStateException("attempt to write array " + valueString + " into fcModelNode " + fcModelNode + .getName() + " failed as the dimensions don't fit."); + } + for (int i = 0; i < bdaValues.length; i++) { + setBda(bdaValues[i], bdas.get(i)); + } + } + } + + private void setBda(String bdaValueString, BasicDataAttribute bda) { + switch (bda.getBasicType()) { + case CHECK: + case DOUBLE_BIT_POS: + case OPTFLDS: + case QUALITY: + case REASON_FOR_INCLUSION: + case TAP_COMMAND: + case TRIGGER_CONDITIONS: + ((BdaBitString) bda).setValue(bdaValueString.getBytes()); + break; + case ENTRY_TIME: + ((BdaEntryTime) bda).setValue(bdaValueString.getBytes()); + break; + case OCTET_STRING: + ((BdaOctetString) bda).setValue(bdaValueString.getBytes()); + break; + case VISIBLE_STRING: + ((BdaVisibleString) bda).setValue(bdaValueString); + break; + case UNICODE_STRING: + ((BdaUnicodeString) bda).setValue(bdaValueString.getBytes()); + break; + case TIMESTAMP: + ((BdaTimestamp) bda).setDate(new Date(Long.parseLong(bdaValueString))); + break; + case BOOLEAN: + ((BdaBoolean) bda).setValue(Boolean.parseBoolean(bdaValueString)); + break; + case FLOAT32: + ((BdaFloat32) bda).setFloat(Float.parseFloat(bdaValueString)); + break; + case FLOAT64: + ((BdaFloat64) bda).setDouble(Double.parseDouble(bdaValueString)); + break; + case INT8: + ((BdaInt8) bda).setValue(Byte.parseByte(bdaValueString)); + break; + case INT8U: + ((BdaInt8U) bda).setValue(Short.parseShort(bdaValueString)); + break; + case INT16: + ((BdaInt16) bda).setValue(Short.parseShort(bdaValueString)); + break; + case INT16U: + ((BdaInt16U) bda).setValue(Integer.parseInt(bdaValueString)); + break; + case INT32: + ((BdaInt32) bda).setValue(Integer.parseInt(bdaValueString)); + break; + case INT32U: + ((BdaInt32U) bda).setValue(Long.parseLong(bdaValueString)); + break; + case INT64: + ((BdaInt64) bda).setValue(Long.parseLong(bdaValueString)); + break; + default: + throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); + } + } + + private void setBda(ChannelValueContainer container, BasicDataAttribute bda) { + switch (bda.getBasicType()) { + case CHECK: + case DOUBLE_BIT_POS: + case OPTFLDS: + case QUALITY: + case REASON_FOR_INCLUSION: + case TAP_COMMAND: + case TRIGGER_CONDITIONS: + ((BdaBitString) bda).setValue(container.getValue().asByteArray()); + break; + case ENTRY_TIME: + ((BdaEntryTime) bda).setValue(container.getValue().asByteArray()); + break; + case OCTET_STRING: + ((BdaOctetString) bda).setValue(container.getValue().asByteArray()); + break; + case VISIBLE_STRING: + ((BdaVisibleString) bda).setValue(container.getValue().asString()); + break; + case UNICODE_STRING: + ((BdaUnicodeString) bda).setValue(container.getValue().asByteArray()); + break; + case TIMESTAMP: + ((BdaTimestamp) bda).setDate(new Date(container.getValue().asLong())); + break; + case BOOLEAN: + ((BdaBoolean) bda).setValue(container.getValue().asBoolean()); + break; + case FLOAT32: + ((BdaFloat32) bda).setFloat(container.getValue().asFloat()); + break; + case FLOAT64: + ((BdaFloat64) bda).setDouble(container.getValue().asDouble()); + break; + case INT8: + ((BdaInt8) bda).setValue(container.getValue().asByte()); + break; + case INT8U: + ((BdaInt8U) bda).setValue(container.getValue().asShort()); + break; + case INT16: + ((BdaInt16) bda).setValue(container.getValue().asShort()); + break; + case INT16U: + ((BdaInt16U) bda).setValue(container.getValue().asInt()); + break; + case INT32: + ((BdaInt32) bda).setValue(container.getValue().asInt()); + break; + case INT32U: + ((BdaInt32U) bda).setValue(container.getValue().asLong()); + break; + case INT64: + ((BdaInt64) bda).setValue(container.getValue().asLong()); + break; + default: + throw new IllegalStateException("unknown BasicType received: " + bda.getBasicType()); + } + } + + @Override + public void disconnect() { + clientAssociation.close(); + } } diff --git a/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Driver.java b/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Driver.java index 112aa7c2..2aa84ab7 100644 --- a/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Driver.java +++ b/projects/driver/iec61850/src/main/java/org/openmuc/framework/driver/iec61850/Iec61850Driver.java @@ -21,10 +21,6 @@ package org.openmuc.framework.driver.iec61850; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.DriverInfo; import org.openmuc.framework.config.ScanException; @@ -40,139 +36,136 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + public final class Iec61850Driver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(Iec61850Driver.class); - - private final static DriverInfo info = new DriverInfo("iec61850", // id - // description - "This driver can be used to access IEC 61850 MMS devices", - // device address - "Synopsis: [:]\nThe default port is 102.", - // parameters - "Synopsis: [-a ] [-lt ] [-rt ]", - // channel address - "Synopsis: :", - // device scan parameters - "N.A."); - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - - String[] deviceAddresses = deviceAddress.split(":"); - - if (deviceAddresses.length < 1 || deviceAddresses.length > 2) { - throw new ArgumentSyntaxException("Invalid device address syntax."); - } - - String remoteHost = deviceAddresses[0]; - InetAddress address; - try { - address = InetAddress.getByName(remoteHost); - } catch (UnknownHostException e) { - throw new ConnectionException("Unknown host: " + remoteHost, e); - } - - int remotePort = 102; - if (deviceAddresses.length == 2) { - try { - remotePort = Integer.parseInt(deviceAddresses[1]); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException("The specified port is not an integer"); - } - } - - ClientSap clientSap = new ClientSap(); - - String authentication = null; - - if (!settings.isEmpty()) { - String[] args = settings.split("\\s+", 0); - if (args.length > 6) { - throw new ArgumentSyntaxException( - "Less than one or more than four arguments in the settings are not allowed."); - } - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-a")) { - i++; - if (i == args.length) { - throw new ArgumentSyntaxException( - "No authentication parameter was specified after the -a parameter"); - } - authentication = args[i]; - } - else if (args[i].equals("-lt")) { - - if (i == (args.length - 1) || args[i + 1].startsWith("-")) { - clientSap.setTSelLocal(new byte[0]); - } - else { - i++; - byte[] tSelLocal = new byte[args[i].length()]; - for (int j = 0; j < args[i].length(); j++) { - tSelLocal[j] = (byte) args[i].charAt(j); - } - clientSap.setTSelLocal(tSelLocal); - } - } - else if (args[i].equals("-rt")) { - - if (i == (args.length - 1) || args[i + 1].startsWith("-")) { - clientSap.setTSelRemote(new byte[0]); - } - else { - i++; - byte[] tSelRemote = new byte[args[i].length()]; - for (int j = 0; j < args[i].length(); j++) { - tSelRemote[j] = (byte) args[i].charAt(j); - } - clientSap.setTSelRemote(tSelRemote); - } - } - else { - throw new ArgumentSyntaxException("Unexpected argument: " + args[i]); - } - } - } - - ClientAssociation clientAssociation; - try { - clientAssociation = clientSap.associate(address, remotePort, authentication, null); - } catch (IOException e) { - throw new ConnectionException(e); - } - - ServerModel serverModel; - try { - serverModel = clientAssociation.retrieveModel(); - } catch (ServiceError e) { - clientAssociation.close(); - throw new ConnectionException("Service error retrieving server model" + e.getMessage(), e); - } catch (IOException e) { - clientAssociation.close(); - throw new ConnectionException("IOException retrieving server model: " + e.getMessage(), e); - } - - return new Iec61850Connection(clientAssociation, serverModel); - } + private final static Logger logger = LoggerFactory.getLogger(Iec61850Driver.class); + + private final static DriverInfo info = new DriverInfo("iec61850", // id + // description + "This driver can be used to access IEC 61850 MMS devices", + // device address + "Synopsis: [:]\nThe default port is 102.", + // parameters + "Synopsis: [-a ] [-lt ] [-rt " + + "]", + // channel address + "Synopsis: :", + // device scan parameters + "N.A."); + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + + String[] deviceAddresses = deviceAddress.split(":"); + + if (deviceAddresses.length < 1 || deviceAddresses.length > 2) { + throw new ArgumentSyntaxException("Invalid device address syntax."); + } + + String remoteHost = deviceAddresses[0]; + InetAddress address; + try { + address = InetAddress.getByName(remoteHost); + } catch (UnknownHostException e) { + throw new ConnectionException("Unknown host: " + remoteHost, e); + } + + int remotePort = 102; + if (deviceAddresses.length == 2) { + try { + remotePort = Integer.parseInt(deviceAddresses[1]); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException("The specified port is not an integer"); + } + } + + ClientSap clientSap = new ClientSap(); + + String authentication = null; + + if (!settings.isEmpty()) { + String[] args = settings.split("\\s+", 0); + if (args.length > 6) { + throw new ArgumentSyntaxException("Less than one or more than four arguments in the settings are not allowed."); + } + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-a")) { + i++; + if (i == args.length) { + throw new ArgumentSyntaxException("No authentication parameter was specified after the -a parameter"); + } + authentication = args[i]; + } else if (args[i].equals("-lt")) { + + if (i == (args.length - 1) || args[i + 1].startsWith("-")) { + clientSap.setTSelLocal(new byte[0]); + } else { + i++; + byte[] tSelLocal = new byte[args[i].length()]; + for (int j = 0; j < args[i].length(); j++) { + tSelLocal[j] = (byte) args[i].charAt(j); + } + clientSap.setTSelLocal(tSelLocal); + } + } else if (args[i].equals("-rt")) { + + if (i == (args.length - 1) || args[i + 1].startsWith("-")) { + clientSap.setTSelRemote(new byte[0]); + } else { + i++; + byte[] tSelRemote = new byte[args[i].length()]; + for (int j = 0; j < args[i].length(); j++) { + tSelRemote[j] = (byte) args[i].charAt(j); + } + clientSap.setTSelRemote(tSelRemote); + } + } else { + throw new ArgumentSyntaxException("Unexpected argument: " + args[i]); + } + } + } + + ClientAssociation clientAssociation; + try { + clientAssociation = clientSap.associate(address, remotePort, authentication, null); + } catch (IOException e) { + throw new ConnectionException(e); + } + + ServerModel serverModel; + try { + serverModel = clientAssociation.retrieveModel(); + } catch (ServiceError e) { + clientAssociation.close(); + throw new ConnectionException("Service error retrieving server model" + e.getMessage(), e); + } catch (IOException e) { + clientAssociation.close(); + throw new ConnectionException("IOException retrieving server model: " + e.getMessage(), e); + } + + return new Iec61850Connection(clientAssociation, serverModel); + } } diff --git a/projects/driver/iec61850/src/main/resources/OSGI-INF/components.xml b/projects/driver/iec61850/src/main/resources/OSGI-INF/components.xml index 6179bc9c..0c210465 100644 --- a/projects/driver/iec61850/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/iec61850/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/iec62056p21/build.gradle b/projects/driver/iec62056p21/build.gradle index bbaf744b..457b978a 100644 --- a/projects/driver/iec62056p21/build.gradle +++ b/projects/driver/iec62056p21/build.gradle @@ -1,28 +1,27 @@ - configurations.create('embed') def j62056version = "1.2" dependencies { - compile project(':openmuc-core-spi') - compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') - - compile group: 'org.openmuc', name: 'j62056', version: j62056version - embed group: 'org.openmuc', name: 'j62056', version: j62056version + compile project(':openmuc-core-spi') + compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') + + compile group: 'org.openmuc', name: 'j62056', version: j62056version + embed group: 'org.openmuc', name: 'j62056', version: j62056version } jar { - manifest { - name = "OpenMUC Driver - IEC 62056-21 Mode C" - instruction 'Bundle-ClassPath', '.,lib/j62056-' + j62056version + '.jar' - instruction 'Import-Package', '!org.openmuc.j62056*,gnu.io,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - IEC 62056-21 Mode C" + instruction 'Bundle-ClassPath', '.,lib/j62056-' + j62056version + '.jar' + instruction 'Import-Package', '!org.openmuc.j62056*,gnu.io,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Connection.java b/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Connection.java index a011e4bc..fe15e44d 100644 --- a/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Connection.java +++ b/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Connection.java @@ -20,126 +20,114 @@ */ package org.openmuc.framework.driver.iec62056p21; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.config.ScanException; +import org.openmuc.framework.data.*; +import org.openmuc.framework.driver.spi.*; +import org.openmuc.j62056.DataSet; + import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeoutException; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import org.openmuc.j62056.DataSet; - public class Iec62056Connection implements Connection { - private final org.openmuc.j62056.Connection connection; - - public Iec62056Connection(org.openmuc.j62056.Connection connection) { - this.connection = connection; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, ScanException, - ConnectionException { - - List dataSets; - try { - dataSets = connection.read(); - } catch (IOException e1) { - e1.printStackTrace(); - throw new ScanException(e1); - } catch (TimeoutException e) { - e.printStackTrace(); - throw new ScanException(e); - } - - if (dataSets == null) { - throw new ScanException("Read timeout."); - } - - List scanInfos = new ArrayList(dataSets.size()); - - for (DataSet dataSet : dataSets) { - try { - Double.parseDouble(dataSet.getValue()); - scanInfos.add(new ChannelScanInfo(dataSet.getId(), "", ValueType.DOUBLE, null)); - } catch (NumberFormatException e) { - scanInfos.add(new ChannelScanInfo(dataSet.getId(), "", ValueType.STRING, dataSet.getValue().length())); - } - - } - - return scanInfos; - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - List dataSets; - try { - dataSets = connection.read(); - } catch (IOException e) { - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_READ_FAILURE)); - } - return null; - } catch (TimeoutException e) { - e.printStackTrace(); - throw new ConnectionException("Read timed out: " + e.getMessage()); - } - - if (dataSets == null) { - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.TIMEOUT)); - } - return null; - } - - long time = System.currentTimeMillis(); - for (ChannelRecordContainer container : containers) { - for (DataSet dataSet : dataSets) { - if (dataSet.getId().equals(container.getChannelAddress())) { - String value = dataSet.getValue(); - if (value != null) { - try { - container.setRecord(new Record(new DoubleValue(Double.parseDouble(dataSet.getValue())), - time)); - } catch (NumberFormatException e) { - container.setRecord(new Record(new StringValue(dataSet.getValue()), time)); - } - } - break; - } - } - } - - return null; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void disconnect() { - connection.close(); - } + private final org.openmuc.j62056.Connection connection; + + public Iec62056Connection(org.openmuc.j62056.Connection connection) { + this.connection = connection; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ScanException, ConnectionException { + + List dataSets; + try { + dataSets = connection.read(); + } catch (IOException e1) { + e1.printStackTrace(); + throw new ScanException(e1); + } catch (TimeoutException e) { + e.printStackTrace(); + throw new ScanException(e); + } + + if (dataSets == null) { + throw new ScanException("Read timeout."); + } + + List scanInfos = new ArrayList(dataSets.size()); + + for (DataSet dataSet : dataSets) { + try { + Double.parseDouble(dataSet.getValue()); + scanInfos.add(new ChannelScanInfo(dataSet.getId(), "", ValueType.DOUBLE, null)); + } catch (NumberFormatException e) { + scanInfos.add(new ChannelScanInfo(dataSet.getId(), "", ValueType.STRING, dataSet.getValue().length())); + } + + } + + return scanInfos; + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + List dataSets; + try { + dataSets = connection.read(); + } catch (IOException e) { + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_READ_FAILURE)); + } + return null; + } catch (TimeoutException e) { + e.printStackTrace(); + throw new ConnectionException("Read timed out: " + e.getMessage()); + } + + if (dataSets == null) { + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.TIMEOUT)); + } + return null; + } + + long time = System.currentTimeMillis(); + for (ChannelRecordContainer container : containers) { + for (DataSet dataSet : dataSets) { + if (dataSet.getId().equals(container.getChannelAddress())) { + String value = dataSet.getValue(); + if (value != null) { + try { + container.setRecord(new Record(new DoubleValue(Double.parseDouble(dataSet.getValue())), time)); + } catch (NumberFormatException e) { + container.setRecord(new Record(new StringValue(dataSet.getValue()), time)); + } + } + break; + } + } + } + + return null; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void disconnect() { + connection.close(); + } } diff --git a/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Driver.java b/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Driver.java index f6c144c7..fbf5d8d2 100644 --- a/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Driver.java +++ b/projects/driver/iec62056p21/src/main/java/org/openmuc/framework/driver/iec62056p21/Iec62056Driver.java @@ -20,179 +20,169 @@ */ package org.openmuc.framework.driver.iec62056p21; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; import org.openmuc.framework.driver.spi.DriverService; import org.openmuc.j62056.Connection; import org.openmuc.j62056.DataSet; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeoutException; + public final class Iec62056Driver implements DriverService { - private final static DriverInfo info = new DriverInfo("iec62056p21", // id - // description - "This driver can read meters using IEC 62056-21 Mode C.", - // device address - "Synopsis: \nExamples: /dev/ttyS0 (Unix), COM1 (Windows)", - // parameters - "N.A.", - // channel address - "Synopsis: ", - // device scan parameters - "Synopsis: [-e] [-d ]\nExamples for : /dev/ttyS0 (Unix), COM1 (Windows)\n-e = enable handling of echos caused by optical tranceivers\n-d = delay of baud rate change in ms. Default is 0. USB to serial converters often require a delay of up to 250ms."); - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - - String[] args = settings.split("\\s+", 0); - if (args.length < 1 || args.length > 4) { - throw new ArgumentSyntaxException( - "Less than one or more than four arguments in the settings are not allowed."); - } - - String serialPortName = ""; - boolean echoHandling = false; - int baudRateChangeDelay = 0; - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-e")) { - echoHandling = true; - } - else if (args[i].equals("-d")) { - i++; - if (i == args.length) { - throw new ArgumentSyntaxException("No baudRateChangeDelay was specified after the -d parameter"); - } - try { - baudRateChangeDelay = Integer.parseInt(args[i]); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException("Specified baudRateChangeDelay is not an integer."); - } - } - else { - serialPortName = args[i]; - } - } - - if (serialPortName.isEmpty()) { - throw new ArgumentSyntaxException("The has to be specified in the settings"); - } - - Connection connection = new Connection(serialPortName, echoHandling, baudRateChangeDelay); - try { - connection.open(); - } catch (IOException e) { - throw new ScanException(e); - } - - try { - List dataSets = connection.read(); - String deviceSettings; - if (echoHandling) { - if (baudRateChangeDelay > 0) { - deviceSettings = "-e -d " + baudRateChangeDelay; - } - else { - deviceSettings = "-e"; - } - } - else { - if (baudRateChangeDelay > 0) { - deviceSettings = "-d " + baudRateChangeDelay; - } - else { - deviceSettings = ""; - } - } - - listener.deviceFound(new DeviceScanInfo(serialPortName, deviceSettings, dataSets.get(0).getId() - .replaceAll("\\p{Cntrl}", ""))); - - } catch (IOException e) { - e.printStackTrace(); - throw new ScanException(e); - } catch (TimeoutException e) { - e.printStackTrace(); - throw new ScanException(e); - } finally { - connection.close(); - } - - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public org.openmuc.framework.driver.spi.Connection connect(String deviceAddress, String settings) - throws ArgumentSyntaxException, ConnectionException { - - boolean echoHandling = false; - int baudRateChangeDelay = 0; - - if (!settings.equals("")) { - - String[] args = settings.split("\\s+"); - if (args.length > 2) { - throw new ArgumentSyntaxException("More than two arguments in the settings are not allowed."); - } - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-e")) { - echoHandling = true; - } - else if (args[i].equals("-d")) { - i++; - if (i == args.length) { - throw new ArgumentSyntaxException("No baudRateChangeDelay was specified after the -d parameter"); - } - try { - baudRateChangeDelay = Integer.parseInt(args[i]); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException("Specified baudRateChangeDelay is not an integer."); - } - } - else { - throw new ArgumentSyntaxException("Found unknown argument in settings: " + args[i]); - } - } - } - - Connection connection = new Connection(deviceAddress, echoHandling, baudRateChangeDelay); - try { - connection.open(); - } catch (IOException e) { - throw new ConnectionException("Unable to open local serial port: " + deviceAddress, e); - } - - try { - connection.read(); - } catch (IOException e) { - connection.close(); - throw new ConnectionException("IOException trying to read meter: " + deviceAddress + ": " + e.getMessage(), - e); - } catch (TimeoutException e) { - e.printStackTrace(); - throw new ConnectionException("Read timed out: " + e.getMessage()); - } - return new Iec62056Connection(connection); - - } + private final static DriverInfo info = new DriverInfo("iec62056p21", // id + // description + "This driver can read meters using IEC 62056-21 Mode C.", + // device address + "Synopsis: \nExamples: /dev/ttyS0 (Unix), COM1 (Windows)", + // parameters + "N.A.", + // channel address + "Synopsis: ", + // device scan parameters + "Synopsis: [-e] [-d ]\nExamples for " + + ": /dev/ttyS0 (Unix), COM1 (Windows)\n-e = enable handling" + + " of echos caused by optical tranceivers\n-d =" + + " delay of baud rate change in ms. Default is 0. USB to serial " + + "converters often require a delay of up to 250ms."); + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + + String[] args = settings.split("\\s+", 0); + if (args.length < 1 || args.length > 4) { + throw new ArgumentSyntaxException("Less than one or more than four arguments in the settings are not allowed."); + } + + String serialPortName = ""; + boolean echoHandling = false; + int baudRateChangeDelay = 0; + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-e")) { + echoHandling = true; + } else if (args[i].equals("-d")) { + i++; + if (i == args.length) { + throw new ArgumentSyntaxException("No baudRateChangeDelay was specified after the -d parameter"); + } + try { + baudRateChangeDelay = Integer.parseInt(args[i]); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException("Specified baudRateChangeDelay is not an integer."); + } + } else { + serialPortName = args[i]; + } + } + + if (serialPortName.isEmpty()) { + throw new ArgumentSyntaxException("The has to be specified in the settings"); + } + + Connection connection = new Connection(serialPortName, echoHandling, baudRateChangeDelay); + try { + connection.open(); + } catch (IOException e) { + throw new ScanException(e); + } + + try { + List dataSets = connection.read(); + String deviceSettings; + if (echoHandling) { + if (baudRateChangeDelay > 0) { + deviceSettings = "-e -d " + baudRateChangeDelay; + } else { + deviceSettings = "-e"; + } + } else { + if (baudRateChangeDelay > 0) { + deviceSettings = "-d " + baudRateChangeDelay; + } else { + deviceSettings = ""; + } + } + + listener.deviceFound(new DeviceScanInfo(serialPortName, deviceSettings, dataSets.get(0).getId().replaceAll("\\p{Cntrl}", ""))); + + } catch (IOException e) { + e.printStackTrace(); + throw new ScanException(e); + } catch (TimeoutException e) { + e.printStackTrace(); + throw new ScanException(e); + } finally { + connection.close(); + } + + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public org.openmuc.framework.driver.spi.Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, + ConnectionException { + + boolean echoHandling = false; + int baudRateChangeDelay = 0; + + if (!settings.equals("")) { + + String[] args = settings.split("\\s+"); + if (args.length > 2) { + throw new ArgumentSyntaxException("More than two arguments in the settings are not allowed."); + } + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-e")) { + echoHandling = true; + } else if (args[i].equals("-d")) { + i++; + if (i == args.length) { + throw new ArgumentSyntaxException("No baudRateChangeDelay was specified after the -d parameter"); + } + try { + baudRateChangeDelay = Integer.parseInt(args[i]); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException("Specified baudRateChangeDelay is not an integer."); + } + } else { + throw new ArgumentSyntaxException("Found unknown argument in settings: " + args[i]); + } + } + } + + Connection connection = new Connection(deviceAddress, echoHandling, baudRateChangeDelay); + try { + connection.open(); + } catch (IOException e) { + throw new ConnectionException("Unable to open local serial port: " + deviceAddress, e); + } + + try { + connection.read(); + } catch (IOException e) { + connection.close(); + throw new ConnectionException("IOException trying to read meter: " + deviceAddress + ": " + e.getMessage(), e); + } catch (TimeoutException e) { + e.printStackTrace(); + throw new ConnectionException("Read timed out: " + e.getMessage()); + } + return new Iec62056Connection(connection); + + } } diff --git a/projects/driver/iec62056p21/src/main/resources/OSGI-INF/components.xml b/projects/driver/iec62056p21/src/main/resources/OSGI-INF/components.xml index edb9d2d7..e268dffb 100644 --- a/projects/driver/iec62056p21/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/iec62056p21/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/iec62056p21/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java b/projects/driver/iec62056p21/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java index e05a8c72..3fc20c68 100644 --- a/projects/driver/iec62056p21/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java +++ b/projects/driver/iec62056p21/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java @@ -22,29 +22,29 @@ public class MBusObjectLocatorTest { - // @Test - // public void mbusStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); - // - // byte[] difs = locator.getDifs(); - // - // Assert.assertEquals(1, difs.length); - // Assert.assertEquals((byte) 4, difs[0]); - // - // byte[] vifs = locator.getVifs(); - // - // Assert.assertEquals(2, vifs.length); - // Assert.assertEquals((byte) 0x94, vifs[0]); - // Assert.assertEquals((byte) 0x3a, vifs[1]); - // - // } - // - // @Test - // public void obisStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); - // } + // @Test + // public void mbusStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); + // + // byte[] difs = locator.getDifs(); + // + // Assert.assertEquals(1, difs.length); + // Assert.assertEquals((byte) 4, difs[0]); + // + // byte[] vifs = locator.getVifs(); + // + // Assert.assertEquals(2, vifs.length); + // Assert.assertEquals((byte) 0x94, vifs[0]); + // Assert.assertEquals((byte) 0x3a, vifs[1]); + // + // } + // + // @Test + // public void obisStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); + // } } diff --git a/projects/driver/knx/build.gradle b/projects/driver/knx/build.gradle index 05bd7769..0b4f7fda 100644 --- a/projects/driver/knx/build.gradle +++ b/projects/driver/knx/build.gradle @@ -1,27 +1,26 @@ - configurations.create('embed') def calimerovers = '2.0.0-SNAPSHOT' dependencies { - compile project(':openmuc-core-spi') - compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') - compile group: 'calimero', name: 'calimero-core', version: calimerovers - embed group: 'calimero', name: 'calimero-core', version: calimerovers + compile project(':openmuc-core-spi') + compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') + compile group: 'calimero', name: 'calimero-core', version: calimerovers + embed group: 'calimero', name: 'calimero-core', version: calimerovers } jar { - manifest { - name = "OpenMUC Driver - KNX" - instruction 'Bundle-ClassPath', '.,lib/calimero-core-' + calimerovers + '.jar' - instruction 'Import-Package', '!tuwien.auto.calimero*,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - KNX" + instruction 'Bundle-ClassPath', '.,lib/calimero-core-' + calimerovers + '.jar' + instruction 'Import-Package', '!tuwien.auto.calimero*,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxConnection.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxConnection.java index bc4f6af6..e05aef20 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxConnection.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxConnection.java @@ -20,27 +20,14 @@ */ package org.openmuc.framework.driver.knx; -import java.net.InetSocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.driver.knx.value.KnxValue; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; +import org.openmuc.framework.driver.spi.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import tuwien.auto.calimero.DataUnitBuilder; import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.IndividualAddress; @@ -59,317 +46,314 @@ import tuwien.auto.calimero.process.ProcessCommunicatorImpl; import tuwien.auto.calimero.serial.rc1180.SNorDoA; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + public class KnxConnection implements Connection { - private static Logger logger = LoggerFactory.getLogger(KnxConnection.class); - private static final int DEFAULT_PORT = 3671; - private static final int DEFAULT_TIMEOUT = 2; - - private KNXNetworkLink knxNetworkLink; - private ProcessCommunicator processCommunicator; - private KnxProcessListener processListener; - private int responseTimeout; - private String name; - - public KnxConnection(String deviceAddress, String settings, int timeout) throws ArgumentSyntaxException, - ConnectionException { - - URI deviceURI = null; - URI interfaceURI = null; - try { - String[] deviceAddressSubStrings = deviceAddress.split("\\s+"); - if (deviceAddressSubStrings.length == 2) { - interfaceURI = new URI(deviceAddressSubStrings[0]); - deviceURI = new URI(deviceAddressSubStrings[1]); - } - else { - deviceURI = new URI(deviceAddress); - } - } catch (URISyntaxException e) { - logger.error("wrong format of interface address"); - throw new ArgumentSyntaxException(); - } - - IndividualAddress address = new IndividualAddress(0); - byte[] serialNumber = new byte[6]; - if (settings != null) { - String[] settingsArray = settings.split(";"); - for (String arg : settingsArray) { - int p = arg.indexOf("="); - if (p != -1) { - String key = arg.substring(0, p).toLowerCase().trim(); - String value = arg.substring(p + 1).trim(); - if (key.equals("address")) { - try { - address = new IndividualAddress(value); - logger.debug("setting individual address to " + address); - } catch (KNXFormatException e) { - logger.warn("wrong format of individual address in settings"); - } - } - else if (key.equals("serialnumber")) { - if (value.length() == 12) { - value = value.toLowerCase(); - for (int i = 0; i < 6; i++) { - String hexValue = value.substring(i * 2, (i * 2) + 2); - serialNumber[i] = (byte) Integer.parseInt(hexValue, 16); - } - logger.debug("setting serial number to " + DataUnitBuilder.toHex(serialNumber, ":")); - } - } - } - } - } - - if (deviceURI.getScheme().toLowerCase().equals(KnxDriver.ADDRESS_SCHEME_KNXIP) && interfaceURI != null) { - name = interfaceURI.getHost() + " - " + deviceURI.getHost(); - logger.debug("connecting over KNX/IP from " + name.replace("-", "to")); - connectNetIP(interfaceURI, deviceURI, address); - } - else if (deviceURI.getScheme().toLowerCase().equals(KnxDriver.ADDRESS_SCHEME_RC1180)) { - name = deviceURI.getPath(); - logger.debug("connecting over KNX RF (RC1180) to " + name); - connectRC1180(deviceURI, address, serialNumber); - } - else { - logger.error("wrong format of address"); - throw new ArgumentSyntaxException(); - } - - try { - processCommunicator = new ProcessCommunicatorImpl(knxNetworkLink); - processListener = new KnxProcessListener(); - processCommunicator.addProcessListener(processListener); - setResponseTimeout(timeout); - } catch (KNXLinkClosedException e) { - e.printStackTrace(); - throw new ConnectionException(e); - } - } - - private void connectNetIP(URI localUri, URI remoteUri, IndividualAddress address) throws ConnectionException { - - try { - String localIP = localUri.getHost(); - int localPort = localUri.getPort() < 0 ? DEFAULT_PORT : localUri.getPort(); - - String remoteIP = remoteUri.getHost(); - int remotePort = remoteUri.getPort() < 0 ? DEFAULT_PORT : remoteUri.getPort(); - - int serviceMode = KNXNetworkLinkIP.TUNNELING; - InetSocketAddress localSocket = new InetSocketAddress(localIP, localPort); - InetSocketAddress remoteSocket = new InetSocketAddress(remoteIP, remotePort); - boolean useNAT = true; - KNXMediumSettings settings = new TPSettings(address, true); - - knxNetworkLink = new KNXNetworkLinkIP(serviceMode, localSocket, remoteSocket, useNAT, settings); - } catch (KNXException e) { - logger.error("Connection failed: " + e.getMessage()); - throw new ConnectionException(e); - } catch (InterruptedException e) { - e.printStackTrace(); - throw new ConnectionException(e); - } - - } - - private void connectRC1180(URI device, IndividualAddress address, byte[] serialNumber) throws ConnectionException { - try { - RFSettings settings = new RFSettings(address, null, serialNumber, false); - // knxNetworkLink = new KNXNetworkLinkRC1180(device.getPath(), settings); - knxNetworkLink = new KNXNetworkLinkRC1180(device.getPath(), settings, true); - } catch (KNXException e) { - logger.error("Connection failed: " + e.getMessage()); - throw new ConnectionException(e); - } - } - - public List listKnownChannels() { - List informations = new ArrayList(); - Map values = processListener.getCachedValues(); - Set keys = values.keySet(); - Map addressInfo = null; - if (knxNetworkLink instanceof KNXNetworkLinkRC1180) { - addressInfo = ((KNXNetworkLinkRC1180) knxNetworkLink).getSendInformation(); - } - - for (GroupAddress groupAddress : keys) { - byte[] asdu = values.get(groupAddress); - StringBuilder channelAddress = new StringBuilder(); - channelAddress.append(groupAddress.toString()).append(":1.001"); - if (addressInfo != null) { - if (addressInfo.containsKey(groupAddress)) { - SNorDoA address = addressInfo.get(groupAddress); - channelAddress.append(':').append(address.isDomainAddress() ? '1' : '0'); - channelAddress.append(':').append(DataUnitBuilder.toHex(address.get(), null)); - } - } - - StringBuilder description = new StringBuilder(); - description.append("Datapoint length: ").append(asdu.length); - description.append("; Last datapoint ASDU: ").append(DataUnitBuilder.toHex(asdu, ":")); - informations.add(new ChannelScanInfo(channelAddress.toString(), description.toString(), null, null)); - } - return informations; - } - - public Record read(KnxGroupDP groupDP, int timeout) throws ConnectionException, KNXException { - Record record = null; - setResponseTimeout(timeout); - - try { - groupDP.getKnxValue().setDPTValue(processCommunicator.read(groupDP)); - - record = new Record(groupDP.getKnxValue().getOpenMucValue(), System.currentTimeMillis()); - } catch (InterruptedException e) { - e.printStackTrace(); - throw new ConnectionException("Read failed for group address " + groupDP.getMainAddress()); - } - - return record; - } - - public boolean write(KnxGroupDP groupDP, int timeout) { - setResponseTimeout(timeout); - - if (groupDP.getAddress() != null && knxNetworkLink instanceof KNXNetworkLinkRC1180) { - ((KNXNetworkLinkRC1180) knxNetworkLink).addSendInformation(groupDP.getMainAddress(), groupDP.getAddress()); - } - - try { - KnxValue value = groupDP.getKnxValue(); - processCommunicator.write(groupDP, value.getDPTValue()); - return true; - } catch (KNXException e) { - logger.warn("write failed"); - return false; - } - } - - private void setResponseTimeout(int timeout) { - if (responseTimeout != timeout) { - responseTimeout = timeout; - int timeoutSec = (timeout / 1000); - if (timeoutSec > 0) { - processCommunicator.setResponseTimeout(timeoutSec); - } - else { - processCommunicator.setResponseTimeout(DEFAULT_TIMEOUT); - } - } - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - return listKnownChannels(); - } - - @Override - public void disconnect() { - logger.debug("disconnecting from " + name); - processCommunicator.detach(); - knxNetworkLink.close(); - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelRecordContainer container : containers) { - try { - - KnxGroupDP groupDP = null; - if (container.getChannelHandle() == null) { - groupDP = createKnxGroupDP(container.getChannelAddress()); - logger.debug("New datapoint: " + groupDP); - container.setChannelHandle(groupDP); - } - else { - groupDP = (KnxGroupDP) container.getChannelHandle(); - } - - Record record = read(groupDP, KnxDriver.timeout); - container.setRecord(record); - } catch (KNXTimeoutException e1) { - logger.debug(e1.getMessage()); - container.setRecord(new Record(null, System.currentTimeMillis(), Flag.TIMEOUT)); - } catch (KNXException e) { - e.printStackTrace(); - } - - } - - return null; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - for (ChannelRecordContainer container : containers) { - if (container.getChannelHandle() == null) { - try { - container.setChannelHandle(createKnxGroupDP(container.getChannelAddress())); - } catch (KNXException e) { - e.printStackTrace(); - } - } - } - logger.info("Start listening for " + containers.size() + " channels"); - processListener.registerOpenMucListener(containers, listener); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelValueContainer container : containers) { - try { - KnxGroupDP groupDP = null; - if (container.getChannelHandle() == null) { - groupDP = createKnxGroupDP(container.getChannelAddress()); - logger.debug("New datapoint: " + groupDP); - container.setChannelHandle(groupDP); - } - else { - groupDP = (KnxGroupDP) container.getChannelHandle(); - } - - groupDP.getKnxValue().setOpenMucValue(container.getValue()); - boolean state = write(groupDP, KnxDriver.timeout); - if (state) { - container.setFlag(Flag.VALID); - } - else { - container.setFlag(Flag.UNKNOWN_ERROR); - } - } catch (KNXException e) { - logger.warn(e.getMessage()); - } - } - - return null; - } - - private static KnxGroupDP createKnxGroupDP(String channelAddress) throws KNXException { - String[] address = channelAddress.split(":"); - GroupAddress main = new GroupAddress(address[0]); - String dptID = address[1]; - KnxGroupDP dp = new KnxGroupDP(main, channelAddress, dptID); - if (address.length == 4) { - boolean AET = address[2].equals("1"); - String value = address[3]; - if (value.length() == 12) { - byte[] SNorDoA = new byte[6]; - value = value.toLowerCase(); - for (int i = 0; i < 6; i++) { - String hexValue = value.substring(i * 2, (i * 2) + 2); - SNorDoA[i] = (byte) Integer.parseInt(hexValue, 16); - } - dp.setAddress(AET, SNorDoA); - } - } - return dp; - } + private static Logger logger = LoggerFactory.getLogger(KnxConnection.class); + private static final int DEFAULT_PORT = 3671; + private static final int DEFAULT_TIMEOUT = 2; + + private KNXNetworkLink knxNetworkLink; + private ProcessCommunicator processCommunicator; + private KnxProcessListener processListener; + private int responseTimeout; + private String name; + + public KnxConnection(String deviceAddress, String settings, int timeout) throws ArgumentSyntaxException, ConnectionException { + + URI deviceURI = null; + URI interfaceURI = null; + try { + String[] deviceAddressSubStrings = deviceAddress.split("\\s+"); + if (deviceAddressSubStrings.length == 2) { + interfaceURI = new URI(deviceAddressSubStrings[0]); + deviceURI = new URI(deviceAddressSubStrings[1]); + } else { + deviceURI = new URI(deviceAddress); + } + } catch (URISyntaxException e) { + logger.error("wrong format of interface address"); + throw new ArgumentSyntaxException(); + } + + IndividualAddress address = new IndividualAddress(0); + byte[] serialNumber = new byte[6]; + if (settings != null) { + String[] settingsArray = settings.split(";"); + for (String arg : settingsArray) { + int p = arg.indexOf("="); + if (p != -1) { + String key = arg.substring(0, p).toLowerCase().trim(); + String value = arg.substring(p + 1).trim(); + if (key.equals("address")) { + try { + address = new IndividualAddress(value); + logger.debug("setting individual address to " + address); + } catch (KNXFormatException e) { + logger.warn("wrong format of individual address in settings"); + } + } else if (key.equals("serialnumber")) { + if (value.length() == 12) { + value = value.toLowerCase(); + for (int i = 0; i < 6; i++) { + String hexValue = value.substring(i * 2, (i * 2) + 2); + serialNumber[i] = (byte) Integer.parseInt(hexValue, 16); + } + logger.debug("setting serial number to " + DataUnitBuilder.toHex(serialNumber, ":")); + } + } + } + } + } + + if (deviceURI.getScheme().toLowerCase().equals(KnxDriver.ADDRESS_SCHEME_KNXIP) && interfaceURI != null) { + name = interfaceURI.getHost() + " - " + deviceURI.getHost(); + logger.debug("connecting over KNX/IP from " + name.replace("-", "to")); + connectNetIP(interfaceURI, deviceURI, address); + } else if (deviceURI.getScheme().toLowerCase().equals(KnxDriver.ADDRESS_SCHEME_RC1180)) { + name = deviceURI.getPath(); + logger.debug("connecting over KNX RF (RC1180) to " + name); + connectRC1180(deviceURI, address, serialNumber); + } else { + logger.error("wrong format of address"); + throw new ArgumentSyntaxException(); + } + + try { + processCommunicator = new ProcessCommunicatorImpl(knxNetworkLink); + processListener = new KnxProcessListener(); + processCommunicator.addProcessListener(processListener); + setResponseTimeout(timeout); + } catch (KNXLinkClosedException e) { + e.printStackTrace(); + throw new ConnectionException(e); + } + } + + private void connectNetIP(URI localUri, URI remoteUri, IndividualAddress address) throws ConnectionException { + + try { + String localIP = localUri.getHost(); + int localPort = localUri.getPort() < 0 ? DEFAULT_PORT : localUri.getPort(); + + String remoteIP = remoteUri.getHost(); + int remotePort = remoteUri.getPort() < 0 ? DEFAULT_PORT : remoteUri.getPort(); + + int serviceMode = KNXNetworkLinkIP.TUNNELING; + InetSocketAddress localSocket = new InetSocketAddress(localIP, localPort); + InetSocketAddress remoteSocket = new InetSocketAddress(remoteIP, remotePort); + boolean useNAT = true; + KNXMediumSettings settings = new TPSettings(address, true); + + knxNetworkLink = new KNXNetworkLinkIP(serviceMode, localSocket, remoteSocket, useNAT, settings); + } catch (KNXException e) { + logger.error("Connection failed: " + e.getMessage()); + throw new ConnectionException(e); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new ConnectionException(e); + } + + } + + private void connectRC1180(URI device, IndividualAddress address, byte[] serialNumber) throws ConnectionException { + try { + RFSettings settings = new RFSettings(address, null, serialNumber, false); + // knxNetworkLink = new KNXNetworkLinkRC1180(device.getPath(), settings); + knxNetworkLink = new KNXNetworkLinkRC1180(device.getPath(), settings, true); + } catch (KNXException e) { + logger.error("Connection failed: " + e.getMessage()); + throw new ConnectionException(e); + } + } + + public List listKnownChannels() { + List informations = new ArrayList(); + Map values = processListener.getCachedValues(); + Set keys = values.keySet(); + Map addressInfo = null; + if (knxNetworkLink instanceof KNXNetworkLinkRC1180) { + addressInfo = ((KNXNetworkLinkRC1180) knxNetworkLink).getSendInformation(); + } + + for (GroupAddress groupAddress : keys) { + byte[] asdu = values.get(groupAddress); + StringBuilder channelAddress = new StringBuilder(); + channelAddress.append(groupAddress.toString()).append(":1.001"); + if (addressInfo != null) { + if (addressInfo.containsKey(groupAddress)) { + SNorDoA address = addressInfo.get(groupAddress); + channelAddress.append(':').append(address.isDomainAddress() ? '1' : '0'); + channelAddress.append(':').append(DataUnitBuilder.toHex(address.get(), null)); + } + } + + StringBuilder description = new StringBuilder(); + description.append("Datapoint length: ").append(asdu.length); + description.append("; Last datapoint ASDU: ").append(DataUnitBuilder.toHex(asdu, ":")); + informations.add(new ChannelScanInfo(channelAddress.toString(), description.toString(), null, null)); + } + return informations; + } + + public Record read(KnxGroupDP groupDP, int timeout) throws ConnectionException, KNXException { + Record record = null; + setResponseTimeout(timeout); + + try { + groupDP.getKnxValue().setDPTValue(processCommunicator.read(groupDP)); + + record = new Record(groupDP.getKnxValue().getOpenMucValue(), System.currentTimeMillis()); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new ConnectionException("Read failed for group address " + groupDP.getMainAddress()); + } + + return record; + } + + public boolean write(KnxGroupDP groupDP, int timeout) { + setResponseTimeout(timeout); + + if (groupDP.getAddress() != null && knxNetworkLink instanceof KNXNetworkLinkRC1180) { + ((KNXNetworkLinkRC1180) knxNetworkLink).addSendInformation(groupDP.getMainAddress(), groupDP.getAddress()); + } + + try { + KnxValue value = groupDP.getKnxValue(); + processCommunicator.write(groupDP, value.getDPTValue()); + return true; + } catch (KNXException e) { + logger.warn("write failed"); + return false; + } + } + + private void setResponseTimeout(int timeout) { + if (responseTimeout != timeout) { + responseTimeout = timeout; + int timeoutSec = (timeout / 1000); + if (timeoutSec > 0) { + processCommunicator.setResponseTimeout(timeoutSec); + } else { + processCommunicator.setResponseTimeout(DEFAULT_TIMEOUT); + } + } + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + return listKnownChannels(); + } + + @Override + public void disconnect() { + logger.debug("disconnecting from " + name); + processCommunicator.detach(); + knxNetworkLink.close(); + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + for (ChannelRecordContainer container : containers) { + try { + + KnxGroupDP groupDP = null; + if (container.getChannelHandle() == null) { + groupDP = createKnxGroupDP(container.getChannelAddress()); + logger.debug("New datapoint: " + groupDP); + container.setChannelHandle(groupDP); + } else { + groupDP = (KnxGroupDP) container.getChannelHandle(); + } + + Record record = read(groupDP, KnxDriver.timeout); + container.setRecord(record); + } catch (KNXTimeoutException e1) { + logger.debug(e1.getMessage()); + container.setRecord(new Record(null, System.currentTimeMillis(), Flag.TIMEOUT)); + } catch (KNXException e) { + e.printStackTrace(); + } + + } + + return null; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException, ConnectionException { + for (ChannelRecordContainer container : containers) { + if (container.getChannelHandle() == null) { + try { + container.setChannelHandle(createKnxGroupDP(container.getChannelAddress())); + } catch (KNXException e) { + e.printStackTrace(); + } + } + } + logger.info("Start listening for " + containers.size() + " channels"); + processListener.registerOpenMucListener(containers, listener); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + + for (ChannelValueContainer container : containers) { + try { + KnxGroupDP groupDP = null; + if (container.getChannelHandle() == null) { + groupDP = createKnxGroupDP(container.getChannelAddress()); + logger.debug("New datapoint: " + groupDP); + container.setChannelHandle(groupDP); + } else { + groupDP = (KnxGroupDP) container.getChannelHandle(); + } + + groupDP.getKnxValue().setOpenMucValue(container.getValue()); + boolean state = write(groupDP, KnxDriver.timeout); + if (state) { + container.setFlag(Flag.VALID); + } else { + container.setFlag(Flag.UNKNOWN_ERROR); + } + } catch (KNXException e) { + logger.warn(e.getMessage()); + } + } + + return null; + } + + private static KnxGroupDP createKnxGroupDP(String channelAddress) throws KNXException { + String[] address = channelAddress.split(":"); + GroupAddress main = new GroupAddress(address[0]); + String dptID = address[1]; + KnxGroupDP dp = new KnxGroupDP(main, channelAddress, dptID); + if (address.length == 4) { + boolean AET = address[2].equals("1"); + String value = address[3]; + if (value.length() == 12) { + byte[] SNorDoA = new byte[6]; + value = value.toLowerCase(); + for (int i = 0; i < 6; i++) { + String hexValue = value.substring(i * 2, (i * 2) + 2); + SNorDoA[i] = (byte) Integer.parseInt(hexValue, 16); + } + dp.setAddress(AET, SNorDoA); + } + } + return dp; + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxDriver.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxDriver.java index 4f8194a1..aac8f012 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxDriver.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxDriver.java @@ -21,15 +21,7 @@ package org.openmuc.framework.driver.knx; import gnu.io.CommPortIdentifier; - -import java.io.IOException; -import java.util.Enumeration; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.Connection; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; @@ -37,82 +29,81 @@ import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import tuwien.auto.calimero.log.LogManager; +import java.io.IOException; +import java.util.Enumeration; + public class KnxDriver implements DriverService { - public static final String ADDRESS_SCHEME_KNXIP = "knxip"; - public static final String ADDRESS_SCHEME_RC1180 = "knxrc1180"; - private static Logger logger = LoggerFactory.getLogger(KnxDriver.class); - - final static int timeout = 10000; - - private final static DriverInfo info = new DriverInfo("knx", "Driver to read and write KNX groupaddresses", "?", - "?", "?", "?"); - - protected void activate(ComponentContext context) { - if (logger.isDebugEnabled()) { - LogManager.getManager().addWriter("", new KnxLogWriter()); // Add calimero logger - } - } - - protected void deactivate(ComponentContext context) { - logger.debug("Deactivated KNX Driver"); - } - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - - String[] args = settings.split("\\s+"); - - if (args.length > 0) { - boolean natAware = false; - boolean mcastResponse = false; - if (args.length > 1) { - logger.debug("Applying settings: " + args[1]); - natAware = args[1].contains("nat"); - mcastResponse = args[1].contains("mcast"); - } - KnxIpDiscover discover; - try { - discover = new KnxIpDiscover(args[0], natAware, mcastResponse); - discover.startSearch(0, listener); - } catch (IOException e) { - throw new ScanException(e); - } - } - else { - try { - Enumeration ports = CommPortIdentifier.getPortIdentifiers(); - while (ports.hasMoreElements()) { - CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); - String name = port.getName(); - String description = "settings could be: address=1.1.1;serialNumber=0123456789AB"; - listener.deviceFound(new DeviceScanInfo(ADDRESS_SCHEME_RC1180 + "://" + name, "", description)); - } - } catch (Exception e) { - logger.warn("serial communication failed"); - } - } - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - return new KnxConnection(deviceAddress, settings, timeout); - } + public static final String ADDRESS_SCHEME_KNXIP = "knxip"; + public static final String ADDRESS_SCHEME_RC1180 = "knxrc1180"; + private static Logger logger = LoggerFactory.getLogger(KnxDriver.class); + + final static int timeout = 10000; + + private final static DriverInfo info = new DriverInfo("knx", "Driver to read and write KNX groupaddresses", "?", "?", "?", "?"); + + protected void activate(ComponentContext context) { + if (logger.isDebugEnabled()) { + LogManager.getManager().addWriter("", new KnxLogWriter()); // Add calimero logger + } + } + + protected void deactivate(ComponentContext context) { + logger.debug("Deactivated KNX Driver"); + } + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + + String[] args = settings.split("\\s+"); + + if (args.length > 0) { + boolean natAware = false; + boolean mcastResponse = false; + if (args.length > 1) { + logger.debug("Applying settings: " + args[1]); + natAware = args[1].contains("nat"); + mcastResponse = args[1].contains("mcast"); + } + KnxIpDiscover discover; + try { + discover = new KnxIpDiscover(args[0], natAware, mcastResponse); + discover.startSearch(0, listener); + } catch (IOException e) { + throw new ScanException(e); + } + } else { + try { + Enumeration ports = CommPortIdentifier.getPortIdentifiers(); + while (ports.hasMoreElements()) { + CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); + String name = port.getName(); + String description = "settings could be: address=1.1.1;serialNumber=0123456789AB"; + listener.deviceFound(new DeviceScanInfo(ADDRESS_SCHEME_RC1180 + "://" + name, "", description)); + } + } catch (Exception e) { + logger.warn("serial communication failed"); + } + } + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + return new KnxConnection(deviceAddress, settings, timeout); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxGroupDP.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxGroupDP.java index 7eb93419..117c214f 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxGroupDP.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxGroupDP.java @@ -21,7 +21,6 @@ package org.openmuc.framework.driver.knx; import org.openmuc.framework.driver.knx.value.KnxValue; - import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.datapoint.CommandDP; import tuwien.auto.calimero.exception.KNXException; @@ -29,36 +28,34 @@ /** * @author frobra - * */ public class KnxGroupDP extends CommandDP { - private final KnxValue value; - private SNorDoA address; - - /** - * @throws KNXException - * - */ - public KnxGroupDP(GroupAddress main, String name, String dptID) throws KNXException { - super(main, name, Integer.parseInt(dptID.split("\\.")[0]), dptID); - value = KnxValue.createKnxValue(dptID); - address = null; - } - - /** - * @return the value - */ - public KnxValue getKnxValue() { - return value; - } - - public void setAddress(boolean AET, byte[] SNorDoA) { - address = new SNorDoA(AET, SNorDoA); - } - - public SNorDoA getAddress() { - return address; - } + private final KnxValue value; + private SNorDoA address; + + /** + * @throws KNXException + */ + public KnxGroupDP(GroupAddress main, String name, String dptID) throws KNXException { + super(main, name, Integer.parseInt(dptID.split("\\.")[0]), dptID); + value = KnxValue.createKnxValue(dptID); + address = null; + } + + /** + * @return the value + */ + public KnxValue getKnxValue() { + return value; + } + + public void setAddress(boolean AET, byte[] SNorDoA) { + address = new SNorDoA(AET, SNorDoA); + } + + public SNorDoA getAddress() { + return address; + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxIpDiscover.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxIpDiscover.java index 321ed0eb..0c3d139a 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxIpDiscover.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxIpDiscover.java @@ -20,80 +20,77 @@ */ package org.openmuc.framework.driver.knx; -import java.io.IOException; -import java.net.InetAddress; - import org.openmuc.framework.config.DeviceScanInfo; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import tuwien.auto.calimero.knxnetip.Discoverer; import tuwien.auto.calimero.knxnetip.servicetype.SearchResponse; +import java.io.IOException; +import java.net.InetAddress; + /** * @author frobra - * */ public class KnxIpDiscover { - private static Logger logger = LoggerFactory.getLogger(KnxIpDiscover.class); - private static int DEFALUT_TIMEOUT = 5; + private static Logger logger = LoggerFactory.getLogger(KnxIpDiscover.class); + private static int DEFALUT_TIMEOUT = 5; - private Discoverer discoverer; - private SearchResponse[] searchResponses; + private Discoverer discoverer; + private SearchResponse[] searchResponses; - public KnxIpDiscover(String interfaceAddress, boolean natAware, boolean mcastResponse) throws IOException { - try { - // System.setProperty("java.net.preferIPv4Stack", "true"); - InetAddress localHost = InetAddress.getByName(interfaceAddress); - discoverer = new Discoverer(localHost, 0, natAware, mcastResponse); - } catch (Exception e) { - logger.warn("can not create discoverer: " + e.getMessage()); - throw new IOException(e); - } - } + public KnxIpDiscover(String interfaceAddress, boolean natAware, boolean mcastResponse) throws IOException { + try { + // System.setProperty("java.net.preferIPv4Stack", "true"); + InetAddress localHost = InetAddress.getByName(interfaceAddress); + discoverer = new Discoverer(localHost, 0, natAware, mcastResponse); + } catch (Exception e) { + logger.warn("can not create discoverer: " + e.getMessage()); + throw new IOException(e); + } + } - public void startSearch(int timeout, DriverDeviceScanListener listener) throws IOException { - timeout = timeout / 1000; - if (timeout < 1) { - timeout = DEFALUT_TIMEOUT; - } - try { - logger.debug("Starting search (timeout: " + timeout + "s)"); - discoverer.startSearch(timeout, true); - searchResponses = discoverer.getSearchResponses(); - } catch (Exception e) { - logger.warn("A network I/O error occurred"); - e.printStackTrace(); - throw new IOException(e); - } - if (searchResponses != null) { - notifyListener(listener); - } - } + public void startSearch(int timeout, DriverDeviceScanListener listener) throws IOException { + timeout = timeout / 1000; + if (timeout < 1) { + timeout = DEFALUT_TIMEOUT; + } + try { + logger.debug("Starting search (timeout: " + timeout + "s)"); + discoverer.startSearch(timeout, true); + searchResponses = discoverer.getSearchResponses(); + } catch (Exception e) { + logger.warn("A network I/O error occurred"); + e.printStackTrace(); + throw new IOException(e); + } + if (searchResponses != null) { + notifyListener(listener); + } + } - private void notifyListener(DriverDeviceScanListener listener) { + private void notifyListener(DriverDeviceScanListener listener) { - for (SearchResponse response : searchResponses) { - StringBuilder deviceAddress = new StringBuilder(); - deviceAddress.append(KnxDriver.ADDRESS_SCHEME_KNXIP).append("://"); - String ipAddress = response.getControlEndpoint().getAddress().getHostAddress(); - if (ipAddress.contains(":")) { // if it is an ipv6 address - deviceAddress.append("[").append(ipAddress).append("]"); - } - else { - deviceAddress.append(ipAddress); - } - deviceAddress.append(":").append(response.getControlEndpoint().getPort()); + for (SearchResponse response : searchResponses) { + StringBuilder deviceAddress = new StringBuilder(); + deviceAddress.append(KnxDriver.ADDRESS_SCHEME_KNXIP).append("://"); + String ipAddress = response.getControlEndpoint().getAddress().getHostAddress(); + if (ipAddress.contains(":")) { // if it is an ipv6 address + deviceAddress.append("[").append(ipAddress).append("]"); + } else { + deviceAddress.append(ipAddress); + } + deviceAddress.append(":").append(response.getControlEndpoint().getPort()); - String name = response.getDevice().getSerialNumberString(); - String description = response.getDevice().toString(); + String name = response.getDevice().getSerialNumberString(); + String description = response.getDevice().toString(); - logger.debug("Found " + deviceAddress + " - " + name + " - " + description); + logger.debug("Found " + deviceAddress + " - " + name + " - " + description); - listener.deviceFound(new DeviceScanInfo(deviceAddress.toString(), "", description)); - } + listener.deviceFound(new DeviceScanInfo(deviceAddress.toString(), "", description)); + } - } + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxLogWriter.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxLogWriter.java index f683f624..3d0f4d21 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxLogWriter.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxLogWriter.java @@ -22,79 +22,72 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import tuwien.auto.calimero.log.LogLevel; import tuwien.auto.calimero.log.LogWriter; /** * @author frobra - * */ public class KnxLogWriter extends LogWriter { - private static Logger logger = LoggerFactory.getLogger(KnxLogWriter.class); + private static Logger logger = LoggerFactory.getLogger(KnxLogWriter.class); - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.log.LogWriter#write(java.lang.String, tuwien.auto.calimero.log.LogLevel, - * java.lang.String) - */ - @Override - public void write(String logService, LogLevel level, String msg) { - write(logService, level, msg, null); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.log.LogWriter#write(java.lang.String, tuwien.auto.calimero.log.LogLevel, + * java.lang.String) + */ + @Override + public void write(String logService, LogLevel level, String msg) { + write(logService, level, msg, null); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.log.LogWriter#write(java.lang.String, tuwien.auto.calimero.log.LogLevel, - * java.lang.String, java.lang.Throwable) - */ - @Override - public void write(String logService, LogLevel level, String msg, Throwable t) { - String logMsg = logService + " - " + msg; - // Logger logger = LoggerFactory.getLogger(logService); - if (level.equals(LogLevel.TRACE)) { - logger.trace(logMsg); - } - else if (level.equals(LogLevel.INFO)) { - logger.debug(logMsg); - } - else if (level.equals(LogLevel.WARN)) { - logger.info(logMsg); - } - else if (level.equals(LogLevel.ERROR)) { - logger.warn(logMsg); - } - else if (level.equals(LogLevel.FATAL)) { - logger.error(logMsg); - } - else { - logger.debug(level.toString().toUpperCase() + " " + logMsg); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.log.LogWriter#write(java.lang.String, tuwien.auto.calimero.log.LogLevel, + * java.lang.String, java.lang.Throwable) + */ + @Override + public void write(String logService, LogLevel level, String msg, Throwable t) { + String logMsg = logService + " - " + msg; + // Logger logger = LoggerFactory.getLogger(logService); + if (level.equals(LogLevel.TRACE)) { + logger.trace(logMsg); + } else if (level.equals(LogLevel.INFO)) { + logger.debug(logMsg); + } else if (level.equals(LogLevel.WARN)) { + logger.info(logMsg); + } else if (level.equals(LogLevel.ERROR)) { + logger.warn(logMsg); + } else if (level.equals(LogLevel.FATAL)) { + logger.error(logMsg); + } else { + logger.debug(level.toString().toUpperCase() + " " + logMsg); + } - if (logger.isTraceEnabled() && t != null) { - t.printStackTrace(); - } - } + if (logger.isTraceEnabled() && t != null) { + t.printStackTrace(); + } + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.log.LogWriter#flush() - */ - @Override - public void flush() { - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.log.LogWriter#flush() + */ + @Override + public void flush() { + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.log.LogWriter#close() - */ - @Override - public void close() { - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.log.LogWriter#close() + */ + @Override + public void close() { + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxProcessListener.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxProcessListener.java index 51f534aa..18d86e8c 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxProcessListener.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/KnxProcessListener.java @@ -20,11 +20,6 @@ */ package org.openmuc.framework.driver.knx; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.driver.knx.value.KnxValue; @@ -32,87 +27,89 @@ import org.openmuc.framework.driver.spi.RecordsReceivedListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import tuwien.auto.calimero.DetachEvent; import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.process.ProcessEvent; import tuwien.auto.calimero.process.ProcessListener; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + /** * @author frobra - * */ public class KnxProcessListener implements ProcessListener { - private static Logger logger = LoggerFactory.getLogger(KnxProcessListener.class); - - private List containers; - private RecordsReceivedListener listener; - private final Map cachedValues; - - public KnxProcessListener() { - cachedValues = new LinkedHashMap(); - - containers = null; - listener = null; - } - - public synchronized void registerOpenMucListener(List containers, - RecordsReceivedListener listener) { - this.containers = containers; - this.listener = listener; - } - - public synchronized void unregisterOpenMucListener() { - containers = null; - listener = null; - } - - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.process.ProcessListener#groupWrite(tuwien.auto.calimero.process.ProcessEvent) - */ - @Override - public void groupWrite(ProcessEvent e) { - if (listener != null) { - long timestamp = System.currentTimeMillis(); - for (ChannelRecordContainer container : containers) { - KnxGroupDP groupDP = (KnxGroupDP) container.getChannelHandle(); - if (groupDP.getMainAddress().equals(e.getDestination())) { - KnxValue value = groupDP.getKnxValue(); - value.setData(e.getASDU()); - logger.debug("Group write: " + e.getDestination()); - - Record record = new Record(value.getOpenMucValue(), timestamp, Flag.VALID); - - listener.newRecords(createNewRecords(container, record)); - break; - } - } - } - cachedValues.put(e.getDestination(), e.getASDU()); - } - - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.process.ProcessListener#detached(tuwien.auto.calimero.DetachEvent) - */ - @Override - public void detached(DetachEvent e) { - - } - - public Map getCachedValues() { - return cachedValues; - } - - private static List createNewRecords(ChannelRecordContainer container, Record record) { - List recordContainers = new ArrayList(); - container.setRecord(record); - recordContainers.add(container); - return recordContainers; - } + private static Logger logger = LoggerFactory.getLogger(KnxProcessListener.class); + + private List containers; + private RecordsReceivedListener listener; + private final Map cachedValues; + + public KnxProcessListener() { + cachedValues = new LinkedHashMap(); + + containers = null; + listener = null; + } + + public synchronized void registerOpenMucListener(List containers, RecordsReceivedListener listener) { + this.containers = containers; + this.listener = listener; + } + + public synchronized void unregisterOpenMucListener() { + containers = null; + listener = null; + } + + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.process.ProcessListener#groupWrite(tuwien.auto.calimero.process.ProcessEvent) + */ + @Override + public void groupWrite(ProcessEvent e) { + if (listener != null) { + long timestamp = System.currentTimeMillis(); + for (ChannelRecordContainer container : containers) { + KnxGroupDP groupDP = (KnxGroupDP) container.getChannelHandle(); + if (groupDP.getMainAddress().equals(e.getDestination())) { + KnxValue value = groupDP.getKnxValue(); + value.setData(e.getASDU()); + logger.debug("Group write: " + e.getDestination()); + + Record record = new Record(value.getOpenMucValue(), timestamp, Flag.VALID); + + listener.newRecords(createNewRecords(container, record)); + break; + } + } + } + cachedValues.put(e.getDestination(), e.getASDU()); + } + + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.process.ProcessListener#detached(tuwien.auto.calimero.DetachEvent) + */ + @Override + public void detached(DetachEvent e) { + + } + + public Map getCachedValues() { + return cachedValues; + } + + private static List createNewRecords(ChannelRecordContainer container, Record record) { + List recordContainers = new ArrayList(); + container.setRecord(record); + recordContainers.add(container); + return recordContainers; + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue.java index e2b48078..820971f1 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue.java @@ -21,68 +21,66 @@ package org.openmuc.framework.driver.knx.value; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator; import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public abstract class KnxValue { - protected DPTXlator dptXlator; + protected DPTXlator dptXlator; - public static KnxValue createKnxValue(String dptID) throws KNXException { - int mainNumber = new Integer(dptID.split("\\.")[0]); + public static KnxValue createKnxValue(String dptID) throws KNXException { + int mainNumber = new Integer(dptID.split("\\.")[0]); - switch (mainNumber) { - case 1: - return new KnxValueBoolean(dptID); - case 2: - return new KnxValue1BitControlled(dptID); - case 3: - return new KnxValue3BitControlled(dptID); - case 5: - return new KnxValue8BitUnsigned(dptID); - case 7: - return new KnxValue2ByteUnsigned(dptID); - case 9: - return new KnxValue2ByteFloat(dptID); - case 10: - return new KnxValueTime(dptID); - case 11: - return new KnxValueDate(dptID); - case 12: - return new KnxValue4ByteUnsigned(dptID); - case 13: - return new KnxValue4ByteSigned(dptID); - case 14: - return new KnxValue4ByteFloat(dptID); - case 16: - return new KnxValueString(dptID); - case 19: - return new KnxValueDateTime(dptID); - default: - throw new KNXException("unknown datapoint"); - } + switch (mainNumber) { + case 1: + return new KnxValueBoolean(dptID); + case 2: + return new KnxValue1BitControlled(dptID); + case 3: + return new KnxValue3BitControlled(dptID); + case 5: + return new KnxValue8BitUnsigned(dptID); + case 7: + return new KnxValue2ByteUnsigned(dptID); + case 9: + return new KnxValue2ByteFloat(dptID); + case 10: + return new KnxValueTime(dptID); + case 11: + return new KnxValueDate(dptID); + case 12: + return new KnxValue4ByteUnsigned(dptID); + case 13: + return new KnxValue4ByteSigned(dptID); + case 14: + return new KnxValue4ByteFloat(dptID); + case 16: + return new KnxValueString(dptID); + case 19: + return new KnxValueDateTime(dptID); + default: + throw new KNXException("unknown datapoint"); + } - } + } - public String getDPTValue() { - return dptXlator.getValue(); - } + public String getDPTValue() { + return dptXlator.getValue(); + } - public void setDPTValue(String value) throws KNXFormatException { - dptXlator.setValue(value); - } + public void setDPTValue(String value) throws KNXFormatException { + dptXlator.setValue(value); + } - public void setData(byte[] data) { - dptXlator.setData(data); - } + public void setData(byte[] data) { + dptXlator.setData(data); + } - public abstract void setOpenMucValue(Value value) throws KNXFormatException; + public abstract void setOpenMucValue(Value value) throws KNXFormatException; - public abstract Value getOpenMucValue(); + public abstract Value getOpenMucValue(); } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue1BitControlled.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue1BitControlled.java index 96df752e..7c4d6ade 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue1BitControlled.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue1BitControlled.java @@ -22,39 +22,37 @@ import org.openmuc.framework.data.ByteValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author Frederic Robra - * */ public class KnxValue1BitControlled extends KnxValue { - public KnxValue1BitControlled(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator1BitControlled(dptID); - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator1BitControlled) dptXlator).setData(value.asByteArray()); - - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new ByteValue(((DPTXlator1BitControlled) dptXlator).getData()[0]); - } + public KnxValue1BitControlled(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator1BitControlled(dptID); + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator1BitControlled) dptXlator).setData(value.asByteArray()); + + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new ByteValue(((DPTXlator1BitControlled) dptXlator).getData()[0]); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteFloat.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteFloat.java index 7e8cd3a7..ff67fa64 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteFloat.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteFloat.java @@ -22,43 +22,41 @@ import org.openmuc.framework.data.FloatValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue2ByteFloat extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValue2ByteFloat(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator2ByteFloat(dptID); - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator2ByteFloat) dptXlator).setValue(value.asFloat()); - - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new FloatValue(((DPTXlator2ByteFloat) dptXlator).getValueFloat()); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValue2ByteFloat(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator2ByteFloat(dptID); + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator2ByteFloat) dptXlator).setValue(value.asFloat()); + + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new FloatValue(((DPTXlator2ByteFloat) dptXlator).getValueFloat()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteUnsigned.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteUnsigned.java index 0610aa8b..f10305ee 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteUnsigned.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue2ByteUnsigned.java @@ -22,42 +22,40 @@ import org.openmuc.framework.data.IntValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue2ByteUnsigned extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValue2ByteUnsigned(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator2ByteUnsigned(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValue2ByteUnsigned(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator2ByteUnsigned(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator2ByteUnsigned) dptXlator).setValue(value.asInt()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator2ByteUnsigned) dptXlator).setValue(value.asInt()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new IntValue(((DPTXlator2ByteUnsigned) dptXlator).getValueUnsigned()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new IntValue(((DPTXlator2ByteUnsigned) dptXlator).getValueUnsigned()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue3BitControlled.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue3BitControlled.java index ea3bc35d..2846f279 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue3BitControlled.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue3BitControlled.java @@ -22,42 +22,40 @@ import org.openmuc.framework.data.ByteValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue3BitControlled extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValue3BitControlled(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator3BitControlled(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValue3BitControlled(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator3BitControlled(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator3BitControlled) dptXlator).setValue(value.asByte()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator3BitControlled) dptXlator).setValue(value.asByte()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new ByteValue(((DPTXlator3BitControlled) dptXlator).getData()[0]); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new ByteValue(((DPTXlator3BitControlled) dptXlator).getData()[0]); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteFloat.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteFloat.java index 3cf37962..1d099581 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteFloat.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteFloat.java @@ -22,43 +22,41 @@ import org.openmuc.framework.data.FloatValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue4ByteFloat extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValue4ByteFloat(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator4ByteFloat(dptID); - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator4ByteFloat) dptXlator).setValue(value.asFloat()); - - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new FloatValue(((DPTXlator4ByteFloat) dptXlator).getValueFloat()); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValue4ByteFloat(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator4ByteFloat(dptID); + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator4ByteFloat) dptXlator).setValue(value.asFloat()); + + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new FloatValue(((DPTXlator4ByteFloat) dptXlator).getValueFloat()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteSigned.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteSigned.java index 2c3fffc6..150bbf5e 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteSigned.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteSigned.java @@ -22,38 +22,36 @@ import org.openmuc.framework.data.IntValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator4ByteSigned; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author Frederic Robra - * */ public class KnxValue4ByteSigned extends KnxValue { - public KnxValue4ByteSigned(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator4ByteSigned(dptID); - } + public KnxValue4ByteSigned(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator4ByteSigned(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator4ByteSigned) dptXlator).setValue(value.asInt()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator4ByteSigned) dptXlator).setValue(value.asInt()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new IntValue(((DPTXlator4ByteSigned) dptXlator).getValueSigned()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new IntValue(((DPTXlator4ByteSigned) dptXlator).getValueSigned()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteUnsigned.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteUnsigned.java index d7e86c8c..8a6c7946 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteUnsigned.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue4ByteUnsigned.java @@ -22,39 +22,37 @@ import org.openmuc.framework.data.LongValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator4ByteUnsigned; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue4ByteUnsigned extends KnxValue { - public KnxValue4ByteUnsigned(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator4ByteUnsigned(dptID); - - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlator4ByteUnsigned) dptXlator).setValue(value.asLong()); - } - - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new LongValue(((DPTXlator4ByteUnsigned) dptXlator).getValueUnsigned()); - } + public KnxValue4ByteUnsigned(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator4ByteUnsigned(dptID); + + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlator4ByteUnsigned) dptXlator).setValue(value.asLong()); + } + + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new LongValue(((DPTXlator4ByteUnsigned) dptXlator).getValueUnsigned()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue8BitUnsigned.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue8BitUnsigned.java index c3e501a2..51d75185 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue8BitUnsigned.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValue8BitUnsigned.java @@ -22,37 +22,35 @@ import org.openmuc.framework.data.ShortValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValue8BitUnsigned extends KnxValue { - public KnxValue8BitUnsigned(String dptID) throws KNXFormatException { - dptXlator = new DPTXlator8BitUnsigned(dptID); - } + public KnxValue8BitUnsigned(String dptID) throws KNXFormatException { + dptXlator = new DPTXlator8BitUnsigned(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) { - ((DPTXlator8BitUnsigned) dptXlator).setValueUnscaled(value.asShort()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) { + ((DPTXlator8BitUnsigned) dptXlator).setValueUnscaled(value.asShort()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new ShortValue(((DPTXlator8BitUnsigned) dptXlator).getValueUnsigned()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new ShortValue(((DPTXlator8BitUnsigned) dptXlator).getValueUnsigned()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueBoolean.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueBoolean.java index c252406c..3c565d1c 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueBoolean.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueBoolean.java @@ -22,39 +22,37 @@ import org.openmuc.framework.data.BooleanValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean; import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValueBoolean extends KnxValue { - public KnxValueBoolean(String dptID) throws KNXException { - dptXlator = new DPTXlatorBoolean(dptID); - } + public KnxValueBoolean(String dptID) throws KNXException { + dptXlator = new DPTXlatorBoolean(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlatorBoolean) dptXlator).setValue(value.asBoolean()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlatorBoolean) dptXlator).setValue(value.asBoolean()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new BooleanValue(((DPTXlatorBoolean) dptXlator).getValueBoolean()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new BooleanValue(((DPTXlatorBoolean) dptXlator).getValueBoolean()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDate.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDate.java index fa8fd170..c194d481 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDate.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDate.java @@ -22,46 +22,44 @@ import org.openmuc.framework.data.LongValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlatorDate; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValueDate extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValueDate(String dptID) throws KNXFormatException { - dptXlator = new DPTXlatorDate(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValueDate(String dptID) throws KNXFormatException { + dptXlator = new DPTXlatorDate(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlatorDate) dptXlator).setValue(value.asLong()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlatorDate) dptXlator).setValue(value.asLong()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - try { - return new LongValue(((DPTXlatorDate) dptXlator).getValueMilliseconds()); - } catch (Exception e) { - return new LongValue(0); - } - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + try { + return new LongValue(((DPTXlatorDate) dptXlator).getValueMilliseconds()); + } catch (Exception e) { + return new LongValue(0); + } + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDateTime.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDateTime.java index db9d90e5..1d35ce06 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDateTime.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueDateTime.java @@ -22,47 +22,45 @@ import org.openmuc.framework.data.LongValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValueDateTime extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValueDateTime(String dptID) throws KNXFormatException { - dptXlator = new DPTXlatorDateTime(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValueDateTime(String dptID) throws KNXFormatException { + dptXlator = new DPTXlatorDateTime(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlatorDateTime) dptXlator).setValue(value.asLong()); + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlatorDateTime) dptXlator).setValue(value.asLong()); - } + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - try { - return new LongValue(((DPTXlatorDateTime) dptXlator).getValueMilliseconds()); - } catch (Exception e) { - return new LongValue(0); - } - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + try { + return new LongValue(((DPTXlatorDateTime) dptXlator).getValueMilliseconds()); + } catch (Exception e) { + return new LongValue(0); + } + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueString.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueString.java index e61fe043..3ff6466d 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueString.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueString.java @@ -22,43 +22,41 @@ import org.openmuc.framework.data.ByteArrayValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlatorString; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValueString extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValueString(String dptID) throws KNXFormatException { - dptXlator = new DPTXlatorString(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValueString(String dptID) throws KNXFormatException { + dptXlator = new DPTXlatorString(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlatorString) dptXlator).setValue(new String(value.asByteArray())); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlatorString) dptXlator).setValue(new String(value.asByteArray())); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - // TODO Auto-generated method stub - return new ByteArrayValue(((DPTXlatorString) dptXlator).getValue().getBytes()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + // TODO Auto-generated method stub + return new ByteArrayValue(((DPTXlatorString) dptXlator).getValue().getBytes()); + } } diff --git a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueTime.java b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueTime.java index bd77f8fb..df3ab9d2 100644 --- a/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueTime.java +++ b/projects/driver/knx/src/main/java/org/openmuc/framework/driver/knx/value/KnxValueTime.java @@ -22,42 +22,40 @@ import org.openmuc.framework.data.LongValue; import org.openmuc.framework.data.Value; - import tuwien.auto.calimero.dptxlator.DPTXlatorTime; import tuwien.auto.calimero.exception.KNXFormatException; /** * @author frobra - * */ public class KnxValueTime extends KnxValue { - /** - * @param dptID - * @throws KNXFormatException - */ - public KnxValueTime(String dptID) throws KNXFormatException { - dptXlator = new DPTXlatorTime(dptID); - } + /** + * @param dptID + * @throws KNXFormatException + */ + public KnxValueTime(String dptID) throws KNXFormatException { + dptXlator = new DPTXlatorTime(dptID); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) - */ - @Override - public void setOpenMucValue(Value value) throws KNXFormatException { - ((DPTXlatorTime) dptXlator).setValue(value.asLong()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#setOpenMucValue(org.openmuc.framework.data.Value) + */ + @Override + public void setOpenMucValue(Value value) throws KNXFormatException { + ((DPTXlatorTime) dptXlator).setValue(value.asLong()); + } - /* - * (non-Javadoc) - * - * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() - */ - @Override - public Value getOpenMucValue() { - return new LongValue(((DPTXlatorTime) dptXlator).getValueMilliseconds()); - } + /* + * (non-Javadoc) + * + * @see org.openmuc.framework.driver.knx.value.KnxValue#getOpenMucValue() + */ + @Override + public Value getOpenMucValue() { + return new LongValue(((DPTXlatorTime) dptXlator).getValueMilliseconds()); + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkRC1180.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkRC1180.java index 1cf019ad..97d983ed 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkRC1180.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkRC1180.java @@ -20,14 +20,7 @@ */ package tuwien.auto.calimero.link; -import java.util.Arrays; -import java.util.Map; - -import tuwien.auto.calimero.CloseEvent; -import tuwien.auto.calimero.DataUnitBuilder; -import tuwien.auto.calimero.FrameEvent; -import tuwien.auto.calimero.KNXAddress; -import tuwien.auto.calimero.Priority; +import tuwien.auto.calimero.*; import tuwien.auto.calimero.cemi.CEMILData; import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXIllegalArgumentException; @@ -39,268 +32,258 @@ import tuwien.auto.calimero.serial.rc1180.RC1180Connection; import tuwien.auto.calimero.serial.rc1180.SNorDoA; +import java.util.Arrays; +import java.util.Map; + /** * Implementation of the KNX network link, for KNX RF, based on the RC1180 chip, using a {@link RC1180Connection}. - * + * * @author Frederic Robra - * */ public class KNXNetworkLinkRC1180 implements KNXNetworkLink { - private static final class LinkNotifier extends EventNotifier { + private static final class LinkNotifier extends EventNotifier { - LinkNotifier(Object source, LogService logger) { - super(source, logger); - } + LinkNotifier(Object source, LogService logger) { + super(source, logger); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.EventNotifier#frameReceived(tuwien.auto.calimero.FrameEvent) - */ - @Override - public void frameReceived(FrameEvent e) { - logger.trace(e.getFrame().toString()); - addEvent(new Indication(new FrameEvent(source, e.getFrame()))); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.EventNotifier#frameReceived(tuwien.auto.calimero.FrameEvent) + */ + @Override + public void frameReceived(FrameEvent e) { + logger.trace(e.getFrame().toString()); + addEvent(new Indication(new FrameEvent(source, e.getFrame()))); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.EventNotifier#connectionClosed(tuwien.auto.calimero.CloseEvent) - */ - @Override - public void connectionClosed(CloseEvent e) { - ((KNXNetworkLinkRC1180) source).close(); - super.connectionClosed(e); - logger.info("link closed"); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.EventNotifier#connectionClosed(tuwien.auto.calimero.CloseEvent) + */ + @Override + public void connectionClosed(CloseEvent e) { + ((KNXNetworkLinkRC1180) source).close(); + super.connectionClosed(e); + logger.info("link closed"); + } - } + } - private String name; - private RC1180Connection connection; - private LogService logger; - private EventNotifier notifier; - private RFSettings settings; - private int hopCount = 6; - private boolean spoofing; + private String name; + private RC1180Connection connection; + private LogService logger; + private EventNotifier notifier; + private RFSettings settings; + private int hopCount = 6; + private boolean spoofing; - /** - * Creates a new network link for KNX RF. Opens a connection to a RC1180 chip, like the CALAO USB-KNX-RF-KNX1 - * - * @param portID - * identifier of the serial device (e.g. /dev/ttyUSB0) - * @param settings - * medium settings defining device and medium specifics needed for communication - * @throws KNXException - */ - public KNXNetworkLinkRC1180(String portID, KNXMediumSettings settings) throws KNXException { - init(portID, settings); - } + /** + * Creates a new network link for KNX RF. Opens a connection to a RC1180 chip, like the CALAO USB-KNX-RF-KNX1 + * + * @param portID identifier of the serial device (e.g. /dev/ttyUSB0) + * @param settings medium settings defining device and medium specifics needed for communication + * @throws KNXException + */ + public KNXNetworkLinkRC1180(String portID, KNXMediumSettings settings) throws KNXException { + init(portID, settings); + } - /** - * Creates a new network link for KNX RF. Opens a connection to a RC1180 chip, like the CALAO USB-KNX-RF-KNX1 - *

    - * If spoofing is enabled, every message modifies the serial number or domain address in the non-volatile memory of - * the chip - * - * @param portID - * identifier of the serial device (e.g. /dev/ttyUSB0) - * @param settings - * medium settings defining device and medium specifics needed for communication - * @param spoofing - * enable for spoofing the serial number or domain address per send request - * @throws KNXException - */ - public KNXNetworkLinkRC1180(String portID, KNXMediumSettings settings, boolean spoofing) throws KNXException { - this.spoofing = spoofing; - init(portID, settings); - } + /** + * Creates a new network link for KNX RF. Opens a connection to a RC1180 chip, like the CALAO USB-KNX-RF-KNX1 + *

    + * If spoofing is enabled, every message modifies the serial number or domain address in the non-volatile memory of + * the chip + * + * @param portID identifier of the serial device (e.g. /dev/ttyUSB0) + * @param settings medium settings defining device and medium specifics needed for communication + * @param spoofing enable for spoofing the serial number or domain address per send request + * @throws KNXException + */ + public KNXNetworkLinkRC1180(String portID, KNXMediumSettings settings, boolean spoofing) throws KNXException { + this.spoofing = spoofing; + init(portID, settings); + } - private void init(String portID, KNXMediumSettings settings) throws KNXException { - name = "link " + portID; - logger = LogManager.getManager().getLogService(name); - connection = new RC1180Connection(portID); - notifier = new LinkNotifier(this, logger); - connection.addConnectionListener(notifier); - setKNXMedium(settings); - } + private void init(String portID, KNXMediumSettings settings) throws KNXException { + name = "link " + portID; + logger = LogManager.getManager().getLogService(name); + connection = new RC1180Connection(portID); + notifier = new LinkNotifier(this, logger); + connection.addConnectionListener(notifier); + setKNXMedium(settings); + } - public void addSendInformation(KNXAddress dst, SNorDoA address) { - if (spoofing) { - connection.putInAddressContainer(dst, address); - } - } + public void addSendInformation(KNXAddress dst, SNorDoA address) { + if (spoofing) { + connection.putInAddressContainer(dst, address); + } + } - public Map getSendInformation() { - return connection.getAddressContainer(); - } + public Map getSendInformation() { + return connection.getAddressContainer(); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#setKNXMedium(tuwien.auto.calimero.link.medium.KNXMediumSettings) - */ - @Override - public void setKNXMedium(KNXMediumSettings settings) { - if (settings == null) { - throw new KNXIllegalArgumentException("medium settings are mandatory"); - } - else if (settings instanceof RFSettings) { - byte[] serialNumber = null; - byte[] domainAddress = null; - if (!Arrays.equals(((RFSettings) settings).getSerialNumber(), new byte[6])) { - serialNumber = ((RFSettings) settings).getSerialNumber(); - connection.setSerialNumber(serialNumber); - } - else { - serialNumber = connection.getSerialNumber(); - } - if (!Arrays.equals(((RFSettings) settings).getDomainAddress(), new byte[6])) { - domainAddress = ((RFSettings) settings).getDomainAddress(); - connection.setDomainAddress(domainAddress); - } - else { - domainAddress = connection.getDomainAddress(); - } - RFSettings acquiredSettings = new RFSettings(settings.getDeviceAddress(), domainAddress, serialNumber, - ((RFSettings) settings).isUnidirectional()); + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#setKNXMedium(tuwien.auto.calimero.link.medium.KNXMediumSettings) + */ + @Override + public void setKNXMedium(KNXMediumSettings settings) { + if (settings == null) { + throw new KNXIllegalArgumentException("medium settings are mandatory"); + } else if (settings instanceof RFSettings) { + byte[] serialNumber = null; + byte[] domainAddress = null; + if (!Arrays.equals(((RFSettings) settings).getSerialNumber(), new byte[6])) { + serialNumber = ((RFSettings) settings).getSerialNumber(); + connection.setSerialNumber(serialNumber); + } else { + serialNumber = connection.getSerialNumber(); + } + if (!Arrays.equals(((RFSettings) settings).getDomainAddress(), new byte[6])) { + domainAddress = ((RFSettings) settings).getDomainAddress(); + connection.setDomainAddress(domainAddress); + } else { + domainAddress = connection.getDomainAddress(); + } + RFSettings acquiredSettings = new RFSettings(settings.getDeviceAddress(), domainAddress, serialNumber, + ((RFSettings) settings).isUnidirectional()); - logger.trace("serial number: " + DataUnitBuilder.toHex(serialNumber, ":") + "; domain address: " - + DataUnitBuilder.toHex(domainAddress, ":")); - this.settings = acquiredSettings; - } - else { - throw new KNXIllegalArgumentException("medium differs"); - } - } + logger.trace("serial number: " + DataUnitBuilder.toHex(serialNumber, ":") + "; domain address: " + DataUnitBuilder + .toHex(domainAddress, ":")); + this.settings = acquiredSettings; + } else { + throw new KNXIllegalArgumentException("medium differs"); + } + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#getKNXMedium() - */ - @Override - public KNXMediumSettings getKNXMedium() { - return settings; - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#getKNXMedium() + */ + @Override + public KNXMediumSettings getKNXMedium() { + return settings; + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#addLinkListener(tuwien.auto.calimero.link.NetworkLinkListener) - */ - @Override - public void addLinkListener(NetworkLinkListener l) { - notifier.addListener(l); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#addLinkListener(tuwien.auto.calimero.link.NetworkLinkListener) + */ + @Override + public void addLinkListener(NetworkLinkListener l) { + notifier.addListener(l); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#removeLinkListener(tuwien.auto.calimero.link.NetworkLinkListener) - */ - @Override - public void removeLinkListener(NetworkLinkListener l) { - notifier.removeListener(l); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#removeLinkListener(tuwien.auto.calimero.link.NetworkLinkListener) + */ + @Override + public void removeLinkListener(NetworkLinkListener l) { + notifier.removeListener(l); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#setHopCount(int) - */ - @Override - public void setHopCount(int count) { - if (count < 0 || count > 7) { - throw new KNXIllegalArgumentException("hop count out of range [0..7]"); - } - hopCount = count; - logger.info("hop count set to " + count); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#setHopCount(int) + */ + @Override + public void setHopCount(int count) { + if (count < 0 || count > 7) { + throw new KNXIllegalArgumentException("hop count out of range [0..7]"); + } + hopCount = count; + logger.info("hop count set to " + count); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#getHopCount() - */ - @Override - public int getHopCount() { - return hopCount; - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#getHopCount() + */ + @Override + public int getHopCount() { + return hopCount; + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#sendRequest(tuwien.auto.calimero.KNXAddress, - * tuwien.auto.calimero.Priority, byte[]) - */ - @Override - public void sendRequest(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { - sendRequest(dst, hopCount, nsdu, false); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#sendRequest(tuwien.auto.calimero.KNXAddress, + * tuwien.auto.calimero.Priority, byte[]) + */ + @Override + public void sendRequest(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { + sendRequest(dst, hopCount, nsdu, false); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#sendRequestWait(tuwien.auto.calimero.KNXAddress, - * tuwien.auto.calimero.Priority, byte[]) - */ - @Override - public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, - KNXLinkClosedException { - sendRequest(dst, hopCount, nsdu, true); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#sendRequestWait(tuwien.auto.calimero.KNXAddress, + * tuwien.auto.calimero.Priority, byte[]) + */ + @Override + public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { + sendRequest(dst, hopCount, nsdu, true); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#send(tuwien.auto.calimero.cemi.CEMILData, boolean) - */ - @Override - public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException { - sendRequest(msg.getDestination(), msg.getHopCount(), msg.getPayload(), waitForCon); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#send(tuwien.auto.calimero.cemi.CEMILData, boolean) + */ + @Override + public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException { + sendRequest(msg.getDestination(), msg.getHopCount(), msg.getPayload(), waitForCon); + } - private void sendRequest(KNXAddress dst, int hopCount, byte[] nsdu, boolean waitForCon) throws KNXTimeoutException, - KNXLinkClosedException { - if (spoofing) { - connection.sendSpoofingRequest(settings.getDeviceAddress(), dst, hopCount, nsdu, waitForCon); - } - else { - connection.sendRequest(settings.getDeviceAddress(), dst, hopCount, nsdu, waitForCon); - } - } + private void sendRequest(KNXAddress dst, int hopCount, byte[] nsdu, boolean waitForCon) throws KNXTimeoutException, KNXLinkClosedException { + if (spoofing) { + connection.sendSpoofingRequest(settings.getDeviceAddress(), dst, hopCount, nsdu, waitForCon); + } else { + connection.sendRequest(settings.getDeviceAddress(), dst, hopCount, nsdu, waitForCon); + } + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#getName() - */ - @Override - public String getName() { - return name; - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#getName() + */ + @Override + public String getName() { + return name; + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#isOpen() - */ - @Override - public boolean isOpen() { - return connection.isOpen(); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#isOpen() + */ + @Override + public boolean isOpen() { + return connection.isOpen(); + } - /* - * (non-Javadoc) - * - * @see tuwien.auto.calimero.link.KNXNetworkLink#close() - */ - @Override - public void close() { - connection.close(); - } + /* + * (non-Javadoc) + * + * @see tuwien.auto.calimero.link.KNXNetworkLink#close() + */ + @Override + public void close() { + connection.close(); + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/Configure.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/Configure.java index 2b0182cf..95ac1602 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/Configure.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/Configure.java @@ -20,390 +20,380 @@ */ package tuwien.auto.calimero.serial.rc1180; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.Semaphore; - import tuwien.auto.calimero.DataUnitBuilder; import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXIllegalArgumentException; import tuwien.auto.calimero.exception.KNXTimeoutException; import tuwien.auto.calimero.log.LogService; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + /** * Used to configure the RC1180 chip - * + * * @author Frederic Robra - * */ class Configure { - private static final byte CONFIG_MODE_ENTER = 0x00; - private static final byte CONFIG_MODE_EXIT = 0x58; - private static final byte CONFIG_MODE_GT_PROMPT = 0x3E; - - private static final byte RF_POWER = 0x01; - private static final byte RF_POWER_ARG_DEFAULT = 0x05; - - private static final byte KNX_MODE = 0x03; - private static final byte KNX_MODE_ARG_DEFAULT = 0x00; - - private static final byte SLEEP_MODE = 0x04; - private static final byte SLEEP_MODE_ARG_DEFAULT = 0x00; - - private static final byte RSSI_MODE = 0x05; - private static final byte RSSI_MODE_ARG_DEFAULT = 0x00; - - private static final byte PREAMBLE_LENGTH = 0x0A; - // private static final byte PREAMBLE_LENGTH_ARG_DEFAULT = 0x00; - private static final byte PREAMBLE_LENGTH_ARG_LONG = 0x01; - - private static final byte BATTERY_THRESHOLD = 0x0B; - private static final byte BATTERY_THRESHOLD_ARG_DEFAULT = 85; - // private static final byte BATTERY_THRESHOLD_ARG_DISABLE = 0x00; - - private static final byte TIMEOUT = 0x10; - private static final byte TIMEOUT_ARG_DEFAULT = 0x7C; - - private static final byte NETWORK_ROLE = 0x12; - private static final byte NETWORK_ROLE_ARG_DEFAULT = 0x00; - - private static final byte DATA_INTERFACE = 0x36; - // private static final byte DATA_INTERFACE_ARG_DEFAULT = 0x00; - private static final byte DATA_INTERFACE_ARG_ADDSTARTSTOPBYTE = 0x04; - // private static final byte DATA_INTERFACE_ARG_TXCOMPLETE = 0x10; - - private static final byte SERIAL_NUMBER_0 = 0x1B; - private static final byte SERIAL_NUMBER_1 = 0x1C; - private static final byte SERIAL_NUMBER_2 = 0x1D; - private static final byte SERIAL_NUMBER_3 = 0x1E; - private static final byte SERIAL_NUMBER_4 = 0x1F; - private static final byte SERIAL_NUMBER_5 = 0x20; - - private static final byte DOMAIN_ADDRESS_0 = 0x21; - private static final byte DOMAIN_ADDRESS_1 = 0x22; - private static final byte DOMAIN_ADDRESS_2 = 0x23; - private static final byte DOMAIN_ADDRESS_3 = 0x24; - private static final byte DOMAIN_ADDRESS_4 = 0x25; - private static final byte DOMAIN_ADDRESS_5 = 0x26; - - private static final byte CONFIG_MODE_TEST_MODE_0 = 0x30; - private static final byte CONFIG_MODE_MEMORY_CONFIGURATION = 0x4D; - private static final byte CONFIG_MODE_MEMORY_CONFIGURATION_EXIT = (byte) 0xFF; - - private final DataOutputStream os; - private final DataInputStream is; - private final LogService logger; - private final Semaphore io; - - /** - * Used to configure the RC1180 chip - * - * @param is - * UART TDX pin - * @param os - * UART RDX pin - * @param io - * semaphore used to lock the input and output stream - * @param logger - */ - public Configure(DataInputStream is, DataOutputStream os, Semaphore io, LogService logger) { - this.is = is; - this.os = os; - this.io = io; - this.logger = logger; - } - - /** - * Sets the specific settings - * - * @throws KNXException - */ - public void set() throws KNXException { - try { - io.acquireUninterruptibly(); - logger.trace("enter configuration mode for RC1180-KNX1"); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - - byte[] memory = readMemory(); - - configure(memory, RF_POWER, RF_POWER_ARG_DEFAULT, "Default RF output power"); - configure(memory, KNX_MODE, KNX_MODE_ARG_DEFAULT, "Set mode to S2"); - configure(memory, SLEEP_MODE, SLEEP_MODE_ARG_DEFAULT, "Disable sleep mode"); - configure(memory, RSSI_MODE, RSSI_MODE_ARG_DEFAULT, "Do not append RSSI to received data"); - configure(memory, PREAMBLE_LENGTH, PREAMBLE_LENGTH_ARG_LONG, "Long preamble (KNX Ready)"); - configure(memory, BATTERY_THRESHOLD, BATTERY_THRESHOLD_ARG_DEFAULT, - "Threshold battery voltage (2.5V) for alarm"); - configure(memory, TIMEOUT, TIMEOUT_ARG_DEFAULT, "Modem clears buffer after 2s"); - configure(memory, NETWORK_ROLE, NETWORK_ROLE_ARG_DEFAULT, "Transmitter/Receiver"); - configure(memory, DATA_INTERFACE, (DATA_INTERFACE_ARG_ADDSTARTSTOPBYTE), - "Add start (68h) and stop (16h) byte"); - - logger.trace("exit configuration mode"); - sendByte(CONFIG_MODE_EXIT); - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - } - - /** - * Performs a factory reset of the RC1180 chip - * - * @throws KNXException - */ - public void factoryReset() throws KNXException { - try { - io.acquireUninterruptibly(); - logger.info("factory reset..."); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); - - int[] memory = new int[] { 0x0B, 0x05, 0x02, 0x00, 0x00, 0x00, 0x64, 0x00, 0x05, 0x3C, 0x00, 0x55, 0x00, - 0x00, 0x80, 0x80, 0x7C, 0x00, 0x00, 0x01, 0x00, 0x00, 0x17, 0x00, 0x00, 0xFF, 0x00, 0x12, 0x34, - 0x56, 0x78, 0x90, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x04, 0xFF, 0x08, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x05, 0x08, 0x00, 0x01, 0x05, 0x00, 0x00, 0x01, 0x2B, 0x00, 0x00, 0x44, 0x06, - 0x02, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; - - for (int i = 0x00; i < 0x60; i++) { - sendConfig(i, memory[i]); - } - for (int i = 0x78; i <= 0xFF; i++) { - sendConfig(i, memory[i]); - } - - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); - sendByte(CONFIG_MODE_EXIT); - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - } - - /** - * @return the serial number saved on the chip - * @throws KNXException - */ - public byte[] getSerialNumber() throws KNXException { - byte[] serialNumber = new byte[6]; - try { - io.acquireUninterruptibly(); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - byte[] memory = readMemory(); - sendByte(CONFIG_MODE_EXIT); - serialNumber[0] = memory[SERIAL_NUMBER_0]; - serialNumber[1] = memory[SERIAL_NUMBER_1]; - serialNumber[2] = memory[SERIAL_NUMBER_2]; - serialNumber[3] = memory[SERIAL_NUMBER_3]; - serialNumber[4] = memory[SERIAL_NUMBER_4]; - serialNumber[5] = memory[SERIAL_NUMBER_5]; - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - return serialNumber; - } - - /** - * @return the domain address saved on the chip - * @throws KNXException - */ - public byte[] getDomainAddress() throws KNXException { - byte[] domainAddress = new byte[6]; - try { - io.acquireUninterruptibly(); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - byte[] memory = readMemory(); - sendByte(CONFIG_MODE_EXIT); - domainAddress[0] = memory[DOMAIN_ADDRESS_0]; - domainAddress[1] = memory[DOMAIN_ADDRESS_1]; - domainAddress[2] = memory[DOMAIN_ADDRESS_2]; - domainAddress[3] = memory[DOMAIN_ADDRESS_3]; - domainAddress[4] = memory[DOMAIN_ADDRESS_4]; - domainAddress[5] = memory[DOMAIN_ADDRESS_5]; - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - return domainAddress; - } - - /** - * Writes the serial number to the chip. A write will only be performed if the address on the chip differs - * - * @param serialNumber - * byte array containing the serial number - * @throws KNXException - */ - public void setSerialNumber(final byte[] serialNumber) throws KNXException { - if (serialNumber.length != 6) { - throw new KNXIllegalArgumentException("wrong length of serial number"); - } - byte[] oldSerialNumber = getSerialNumber(); - if (!Arrays.equals(oldSerialNumber, serialNumber)) { - try { - io.acquireUninterruptibly(); - logger.info("setting serial number to " + DataUnitBuilder.toHex(serialNumber, ":")); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); - - sendConfig(SERIAL_NUMBER_0, serialNumber[0]); - sendConfig(SERIAL_NUMBER_1, serialNumber[1]); - sendConfig(SERIAL_NUMBER_2, serialNumber[2]); - sendConfig(SERIAL_NUMBER_3, serialNumber[3]); - sendConfig(SERIAL_NUMBER_4, serialNumber[4]); - sendConfig(SERIAL_NUMBER_5, serialNumber[5]); - - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); - sendByte(CONFIG_MODE_EXIT); - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - } - } - - /** - * Writes the domain address to the chip. A write will only be performed if the address on the chip differs - * - * @param domainAddress - * byte array containing the domain address - * @throws KNXException - */ - public void setDomainAddress(final byte[] domainAddress) throws KNXException { - if (domainAddress.length != 6) { - throw new KNXIllegalArgumentException("wrong length of domain address"); - } - byte[] oldDomainAddress = getDomainAddress(); - if (!Arrays.equals(oldDomainAddress, domainAddress)) { - try { - io.acquireUninterruptibly(); - logger.info("setting domain addres to " + DataUnitBuilder.toHex(domainAddress, ":")); - sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); - - sendConfig(DOMAIN_ADDRESS_0, domainAddress[0]); - sendConfig(DOMAIN_ADDRESS_1, domainAddress[1]); - sendConfig(DOMAIN_ADDRESS_2, domainAddress[2]); - sendConfig(DOMAIN_ADDRESS_3, domainAddress[3]); - sendConfig(DOMAIN_ADDRESS_4, domainAddress[4]); - sendConfig(DOMAIN_ADDRESS_5, domainAddress[5]); - - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); - sendByte(CONFIG_MODE_EXIT); - } catch (KNXException e) { - throw e; - } finally { - io.release(); - } - } - } - - private void configure(byte[] memory, byte parameter, byte argument, String description) throws KNXException { - if (memory[parameter] != argument) { - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); - logger.info(description); - sendConfig(parameter, argument); - sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); - } - } - - private byte[] readMemory() throws KNXException { - int length = 257; // length = 0xff + end_prompt ('>') - byte[] memory = new byte[length]; - sendByte(CONFIG_MODE_TEST_MODE_0); - int available; - int read = 0; - int timeout = 1000; - do { - try { - available = is.available(); - is.read(memory, read, available); - read += available; - } catch (IOException e) { - logger.error(e.getMessage()); - throw new KNXException(e.getMessage(), e); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - timeout -= 100; - if (timeout == 0) { - throw new KNXTimeoutException("memory read failed"); - } - } while (read < length); - - return memory; - } - - private void sendByte(int send) { - try { - os.writeByte(send); - os.flush(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - private void sendConfig(int command, int argument) throws KNXException { - // sendAndWaitForResponse(command, CONFIG_MODE_GT_PROMPT); - // sendAndWaitForResponse(argument, CONFIG_MODE_GT_PROMPT); - sendByte(command); - sendByte(argument); - } - - private void sendAndWaitForResponse(int send, byte response) throws KNXException { - sendByte(send); - int timeout = 1000; - boolean wait = true; - int available; - do { - try { - available = is.available(); - if (available > 0) { - byte[] buffer = new byte[available]; - is.read(buffer); - for (byte b : buffer) { - if (b == response) { - wait = false; - break; - } - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - timeout -= 100; - if (timeout == 0) { - throw new KNXTimeoutException("configuring failed"); - } - } - } catch (IOException e) { - logger.error(e.getMessage()); - throw new KNXException(e.getMessage(), e); - } - - } while (wait); - - } + private static final byte CONFIG_MODE_ENTER = 0x00; + private static final byte CONFIG_MODE_EXIT = 0x58; + private static final byte CONFIG_MODE_GT_PROMPT = 0x3E; + + private static final byte RF_POWER = 0x01; + private static final byte RF_POWER_ARG_DEFAULT = 0x05; + + private static final byte KNX_MODE = 0x03; + private static final byte KNX_MODE_ARG_DEFAULT = 0x00; + + private static final byte SLEEP_MODE = 0x04; + private static final byte SLEEP_MODE_ARG_DEFAULT = 0x00; + + private static final byte RSSI_MODE = 0x05; + private static final byte RSSI_MODE_ARG_DEFAULT = 0x00; + + private static final byte PREAMBLE_LENGTH = 0x0A; + // private static final byte PREAMBLE_LENGTH_ARG_DEFAULT = 0x00; + private static final byte PREAMBLE_LENGTH_ARG_LONG = 0x01; + + private static final byte BATTERY_THRESHOLD = 0x0B; + private static final byte BATTERY_THRESHOLD_ARG_DEFAULT = 85; + // private static final byte BATTERY_THRESHOLD_ARG_DISABLE = 0x00; + + private static final byte TIMEOUT = 0x10; + private static final byte TIMEOUT_ARG_DEFAULT = 0x7C; + + private static final byte NETWORK_ROLE = 0x12; + private static final byte NETWORK_ROLE_ARG_DEFAULT = 0x00; + + private static final byte DATA_INTERFACE = 0x36; + // private static final byte DATA_INTERFACE_ARG_DEFAULT = 0x00; + private static final byte DATA_INTERFACE_ARG_ADDSTARTSTOPBYTE = 0x04; + // private static final byte DATA_INTERFACE_ARG_TXCOMPLETE = 0x10; + + private static final byte SERIAL_NUMBER_0 = 0x1B; + private static final byte SERIAL_NUMBER_1 = 0x1C; + private static final byte SERIAL_NUMBER_2 = 0x1D; + private static final byte SERIAL_NUMBER_3 = 0x1E; + private static final byte SERIAL_NUMBER_4 = 0x1F; + private static final byte SERIAL_NUMBER_5 = 0x20; + + private static final byte DOMAIN_ADDRESS_0 = 0x21; + private static final byte DOMAIN_ADDRESS_1 = 0x22; + private static final byte DOMAIN_ADDRESS_2 = 0x23; + private static final byte DOMAIN_ADDRESS_3 = 0x24; + private static final byte DOMAIN_ADDRESS_4 = 0x25; + private static final byte DOMAIN_ADDRESS_5 = 0x26; + + private static final byte CONFIG_MODE_TEST_MODE_0 = 0x30; + private static final byte CONFIG_MODE_MEMORY_CONFIGURATION = 0x4D; + private static final byte CONFIG_MODE_MEMORY_CONFIGURATION_EXIT = (byte) 0xFF; + + private final DataOutputStream os; + private final DataInputStream is; + private final LogService logger; + private final Semaphore io; + + /** + * Used to configure the RC1180 chip + * + * @param is UART TDX pin + * @param os UART RDX pin + * @param io semaphore used to lock the input and output stream + * @param logger + */ + public Configure(DataInputStream is, DataOutputStream os, Semaphore io, LogService logger) { + this.is = is; + this.os = os; + this.io = io; + this.logger = logger; + } + + /** + * Sets the specific settings + * + * @throws KNXException + */ + public void set() throws KNXException { + try { + io.acquireUninterruptibly(); + logger.trace("enter configuration mode for RC1180-KNX1"); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + + byte[] memory = readMemory(); + + configure(memory, RF_POWER, RF_POWER_ARG_DEFAULT, "Default RF output power"); + configure(memory, KNX_MODE, KNX_MODE_ARG_DEFAULT, "Set mode to S2"); + configure(memory, SLEEP_MODE, SLEEP_MODE_ARG_DEFAULT, "Disable sleep mode"); + configure(memory, RSSI_MODE, RSSI_MODE_ARG_DEFAULT, "Do not append RSSI to received data"); + configure(memory, PREAMBLE_LENGTH, PREAMBLE_LENGTH_ARG_LONG, "Long preamble (KNX Ready)"); + configure(memory, BATTERY_THRESHOLD, BATTERY_THRESHOLD_ARG_DEFAULT, "Threshold battery voltage (2.5V) for alarm"); + configure(memory, TIMEOUT, TIMEOUT_ARG_DEFAULT, "Modem clears buffer after 2s"); + configure(memory, NETWORK_ROLE, NETWORK_ROLE_ARG_DEFAULT, "Transmitter/Receiver"); + configure(memory, DATA_INTERFACE, (DATA_INTERFACE_ARG_ADDSTARTSTOPBYTE), "Add start (68h) and stop (16h) byte"); + + logger.trace("exit configuration mode"); + sendByte(CONFIG_MODE_EXIT); + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + } + + /** + * Performs a factory reset of the RC1180 chip + * + * @throws KNXException + */ + public void factoryReset() throws KNXException { + try { + io.acquireUninterruptibly(); + logger.info("factory reset..."); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); + + int[] memory = new int[]{0x0B, 0x05, 0x02, 0x00, 0x00, 0x00, 0x64, 0x00, 0x05, 0x3C, 0x00, 0x55, 0x00, 0x00, 0x80, 0x80, + 0x7C, 0x00, 0x00, 0x01, 0x00, 0x00, 0x17, 0x00, 0x00, 0xFF, 0x00, 0x12, 0x34, 0x56, 0x78, 0x90, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x04, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x08, 0x00, 0x01, 0x05, 0x00, + 0x00, 0x01, 0x2B, 0x00, 0x00, 0x44, 0x06, 0x02, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF}; + + for (int i = 0x00; i < 0x60; i++) { + sendConfig(i, memory[i]); + } + for (int i = 0x78; i <= 0xFF; i++) { + sendConfig(i, memory[i]); + } + + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); + sendByte(CONFIG_MODE_EXIT); + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + } + + /** + * @return the serial number saved on the chip + * @throws KNXException + */ + public byte[] getSerialNumber() throws KNXException { + byte[] serialNumber = new byte[6]; + try { + io.acquireUninterruptibly(); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + byte[] memory = readMemory(); + sendByte(CONFIG_MODE_EXIT); + serialNumber[0] = memory[SERIAL_NUMBER_0]; + serialNumber[1] = memory[SERIAL_NUMBER_1]; + serialNumber[2] = memory[SERIAL_NUMBER_2]; + serialNumber[3] = memory[SERIAL_NUMBER_3]; + serialNumber[4] = memory[SERIAL_NUMBER_4]; + serialNumber[5] = memory[SERIAL_NUMBER_5]; + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + return serialNumber; + } + + /** + * @return the domain address saved on the chip + * @throws KNXException + */ + public byte[] getDomainAddress() throws KNXException { + byte[] domainAddress = new byte[6]; + try { + io.acquireUninterruptibly(); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + byte[] memory = readMemory(); + sendByte(CONFIG_MODE_EXIT); + domainAddress[0] = memory[DOMAIN_ADDRESS_0]; + domainAddress[1] = memory[DOMAIN_ADDRESS_1]; + domainAddress[2] = memory[DOMAIN_ADDRESS_2]; + domainAddress[3] = memory[DOMAIN_ADDRESS_3]; + domainAddress[4] = memory[DOMAIN_ADDRESS_4]; + domainAddress[5] = memory[DOMAIN_ADDRESS_5]; + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + return domainAddress; + } + + /** + * Writes the serial number to the chip. A write will only be performed if the address on the chip differs + * + * @param serialNumber byte array containing the serial number + * @throws KNXException + */ + public void setSerialNumber(final byte[] serialNumber) throws KNXException { + if (serialNumber.length != 6) { + throw new KNXIllegalArgumentException("wrong length of serial number"); + } + byte[] oldSerialNumber = getSerialNumber(); + if (!Arrays.equals(oldSerialNumber, serialNumber)) { + try { + io.acquireUninterruptibly(); + logger.info("setting serial number to " + DataUnitBuilder.toHex(serialNumber, ":")); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); + + sendConfig(SERIAL_NUMBER_0, serialNumber[0]); + sendConfig(SERIAL_NUMBER_1, serialNumber[1]); + sendConfig(SERIAL_NUMBER_2, serialNumber[2]); + sendConfig(SERIAL_NUMBER_3, serialNumber[3]); + sendConfig(SERIAL_NUMBER_4, serialNumber[4]); + sendConfig(SERIAL_NUMBER_5, serialNumber[5]); + + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); + sendByte(CONFIG_MODE_EXIT); + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + } + } + + /** + * Writes the domain address to the chip. A write will only be performed if the address on the chip differs + * + * @param domainAddress byte array containing the domain address + * @throws KNXException + */ + public void setDomainAddress(final byte[] domainAddress) throws KNXException { + if (domainAddress.length != 6) { + throw new KNXIllegalArgumentException("wrong length of domain address"); + } + byte[] oldDomainAddress = getDomainAddress(); + if (!Arrays.equals(oldDomainAddress, domainAddress)) { + try { + io.acquireUninterruptibly(); + logger.info("setting domain addres to " + DataUnitBuilder.toHex(domainAddress, ":")); + sendAndWaitForResponse(CONFIG_MODE_ENTER, CONFIG_MODE_GT_PROMPT); + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); + + sendConfig(DOMAIN_ADDRESS_0, domainAddress[0]); + sendConfig(DOMAIN_ADDRESS_1, domainAddress[1]); + sendConfig(DOMAIN_ADDRESS_2, domainAddress[2]); + sendConfig(DOMAIN_ADDRESS_3, domainAddress[3]); + sendConfig(DOMAIN_ADDRESS_4, domainAddress[4]); + sendConfig(DOMAIN_ADDRESS_5, domainAddress[5]); + + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); + sendByte(CONFIG_MODE_EXIT); + } catch (KNXException e) { + throw e; + } finally { + io.release(); + } + } + } + + private void configure(byte[] memory, byte parameter, byte argument, String description) throws KNXException { + if (memory[parameter] != argument) { + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION, CONFIG_MODE_GT_PROMPT); + logger.info(description); + sendConfig(parameter, argument); + sendAndWaitForResponse(CONFIG_MODE_MEMORY_CONFIGURATION_EXIT, CONFIG_MODE_GT_PROMPT); + } + } + + private byte[] readMemory() throws KNXException { + int length = 257; // length = 0xff + end_prompt ('>') + byte[] memory = new byte[length]; + sendByte(CONFIG_MODE_TEST_MODE_0); + int available; + int read = 0; + int timeout = 1000; + do { + try { + available = is.available(); + is.read(memory, read, available); + read += available; + } catch (IOException e) { + logger.error(e.getMessage()); + throw new KNXException(e.getMessage(), e); + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + timeout -= 100; + if (timeout == 0) { + throw new KNXTimeoutException("memory read failed"); + } + } while (read < length); + + return memory; + } + + private void sendByte(int send) { + try { + os.writeByte(send); + os.flush(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void sendConfig(int command, int argument) throws KNXException { + // sendAndWaitForResponse(command, CONFIG_MODE_GT_PROMPT); + // sendAndWaitForResponse(argument, CONFIG_MODE_GT_PROMPT); + sendByte(command); + sendByte(argument); + } + + private void sendAndWaitForResponse(int send, byte response) throws KNXException { + sendByte(send); + int timeout = 1000; + boolean wait = true; + int available; + do { + try { + available = is.available(); + if (available > 0) { + byte[] buffer = new byte[available]; + is.read(buffer); + for (byte b : buffer) { + if (b == response) { + wait = false; + break; + } + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + timeout -= 100; + if (timeout == 0) { + throw new KNXTimeoutException("configuring failed"); + } + } + } catch (IOException e) { + logger.error(e.getMessage()); + throw new KNXException(e.getMessage(), e); + } + + } while (wait); + + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/RC1180Connection.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/RC1180Connection.java index f0a13937..207ba812 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/RC1180Connection.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/RC1180Connection.java @@ -22,6 +22,12 @@ import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; +import tuwien.auto.calimero.*; +import tuwien.auto.calimero.exception.KNXException; +import tuwien.auto.calimero.internal.EventListeners; +import tuwien.auto.calimero.link.KNXLinkClosedException; +import tuwien.auto.calimero.log.LogManager; +import tuwien.auto.calimero.log.LogService; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -32,398 +38,366 @@ import java.util.Map; import java.util.concurrent.Semaphore; -import tuwien.auto.calimero.DataUnitBuilder; -import tuwien.auto.calimero.FrameEvent; -import tuwien.auto.calimero.IndividualAddress; -import tuwien.auto.calimero.KNXAddress; -import tuwien.auto.calimero.KNXListener; -import tuwien.auto.calimero.exception.KNXException; -import tuwien.auto.calimero.internal.EventListeners; -import tuwien.auto.calimero.link.KNXLinkClosedException; -import tuwien.auto.calimero.log.LogManager; -import tuwien.auto.calimero.log.LogService; - /** * RF connection based on the RC1180 chip - * + * * @author Frederic Robra - * */ public class RC1180Connection { - private static final boolean DEFAULT_AET = false; - - private final LogService logger; - private SerialPort serialPort; - private DataOutputStream os; - private DataInputStream is; - private final Receiver receiver; - private volatile boolean open = false; - private final Configure configure; - private final Semaphore io = new Semaphore(1, true); - private boolean addressExtensionType = DEFAULT_AET; - - private final EventListeners listeners = new EventListeners(); - - private final Map linkLayerFrameNumbers = new LinkedHashMap(); - private final Map addressContainer = new LinkedHashMap(); - - /** - * RF connection based on the RC1180 chip - * - * @param portID - * identifier of the serial device (e.g. /dev/ttyUSB0) - * @throws KNXException - */ - public RC1180Connection(String portID) throws KNXException { - logger = LogManager.getManager().getLogService("RC1180 " + portID); - - try { - io.acquireUninterruptibly(); - CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portID); - serialPort = (SerialPort) commPortIdentifier.open("knx", 2000); - - serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); - - os = new DataOutputStream(serialPort.getOutputStream()); - is = new DataInputStream(serialPort.getInputStream()); - - int available = is.available(); - if (available > 0) { - byte[] buffer = new byte[available]; - is.read(buffer); - } - open = true; - logger.trace("connected to serial port " + serialPort.getName()); - } catch (Exception e) { - logger.error(e.getMessage()); - throw new KNXException(e.getMessage(), e); - } finally { - io.release(); - } + private static final boolean DEFAULT_AET = false; + + private final LogService logger; + private SerialPort serialPort; + private DataOutputStream os; + private DataInputStream is; + private final Receiver receiver; + private volatile boolean open = false; + private final Configure configure; + private final Semaphore io = new Semaphore(1, true); + private boolean addressExtensionType = DEFAULT_AET; + + private final EventListeners listeners = new EventListeners(); + + private final Map linkLayerFrameNumbers = new LinkedHashMap(); + private final Map addressContainer = new LinkedHashMap(); + + /** + * RF connection based on the RC1180 chip + * + * @param portID identifier of the serial device (e.g. /dev/ttyUSB0) + * @throws KNXException + */ + public RC1180Connection(String portID) throws KNXException { + logger = LogManager.getManager().getLogService("RC1180 " + portID); + + try { + io.acquireUninterruptibly(); + CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portID); + serialPort = (SerialPort) commPortIdentifier.open("knx", 2000); + + serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); + + os = new DataOutputStream(serialPort.getOutputStream()); + is = new DataInputStream(serialPort.getInputStream()); + + int available = is.available(); + if (available > 0) { + byte[] buffer = new byte[available]; + is.read(buffer); + } + open = true; + logger.trace("connected to serial port " + serialPort.getName()); + } catch (Exception e) { + logger.error(e.getMessage()); + throw new KNXException(e.getMessage(), e); + } finally { + io.release(); + } /* Configure CALAO USB-KNX-RF-C01 */ - try { - Thread.sleep(500); - } catch (InterruptedException e) { - } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } - configure = new Configure(is, os, io, logger); + configure = new Configure(is, os, io, logger); - configure.set(); + configure.set(); /* Create receiver, start listening */ - receiver = new Receiver(); - receiver.start(); - } - - public void putInAddressContainer(KNXAddress dst, SNorDoA address) { - addressContainer.put(dst, address); - } - - public Map getAddressContainer() { - return Collections.unmodifiableMap(addressContainer); - } - - /** - * Same as sendRequest()
    - * The function tries to find and set the source address and the serial number or domain address corresponding to - * the destination address. - * - * @param dst - * destination address - * @param hopCount - * repetition counter - * @param nsdu - * network layer service data unit - * @param wait - * true to wait, false to immediately return - * @throws KNXLinkClosedException - */ - public void sendSpoofingRequest(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu, boolean wait) - throws KNXLinkClosedException { - if (addressContainer.containsKey(dst)) { - logger.trace("send spoofing request"); - SNorDoA address = addressContainer.get(dst); - addressExtensionType = address.isDomainAddress(); - if (addressExtensionType) { - setDomainAddress(address.get()); - } - else { - setSerialNumber(address.get()); - } - } - sendRequest(src, dst, hopCount, nsdu, wait); - addressExtensionType = DEFAULT_AET; - } - - /** - * Send a message. If this is the first message to the destination, this method will send the message 8 times, so - * the frame number fits - * - * @param src - * source address - * @param dst - * destination address - * @param hopCount - * repetition counter - * @param nsdu - * network layer service data unit - * @param wait - * true to wait, false to immediately return - * @throws KNXLinkClosedException - */ - public void sendRequest(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu, boolean wait) - throws KNXLinkClosedException { - if (!linkLayerFrameNumbers.containsKey(dst)) { // if we don't know the frame number, take it over - linkLayerFrameNumbers.put(dst, -1); - for (int i = 0; i < 8; i++) { - sendRequest(src, dst, hopCount, nsdu, true); - } - return; - } - - int linkLayerFrameNumber = linkLayerFrameNumbers.get(dst); - linkLayerFrameNumber = (linkLayerFrameNumber + 1) % 8; - linkLayerFrameNumbers.put(dst, linkLayerFrameNumber); - - TransmittingFrame frame = new TransmittingFrame(src, dst, hopCount, linkLayerFrameNumber, addressExtensionType, - nsdu); - - try { - logger.trace("sending " + frame); - io.acquireUninterruptibly(); - os.write(frame.getFrame()); - os.flush(); - - if (wait) { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - } - } - } catch (IOException e) { - logger.error(e.getMessage()); - throw new KNXLinkClosedException(e.getMessage()); - } finally { - io.release(); - } - - } - - /** - * - * @return the status of the connection - */ - public boolean isOpen() { - return open; - } - - /** - * The connection is closed - */ - public void close() { - if (open) { - io.acquireUninterruptibly(); - receiver.stopReceiver(); - serialPort.close(); - open = false; - io.release(); - } - } - - /** - * Adds the specified event listener l to receive events from this connection. - *

    - * If l was already added as listener, no action is performed. - * - * @param l - * the listener to add - */ - public void addConnectionListener(final KNXListener l) { - listeners.add(l); - } - - /** - * Removes the specified event listener l, so it does no longer receive events from this connection. - *

    - * If l was not added in the first place, no action is performed. - * - * @param l - * the listener to remove - */ - public void removeConnectionListener(final KNXListener l) { - listeners.remove(l); - } - - /** - * Sets the serial number to the RC1180 chip - * - * @param serialNumber - * byte array containing the serial number - */ - public void setSerialNumber(final byte[] serialNumber) { - try { - configure.setSerialNumber(serialNumber); - } catch (KNXException e) { - logger.warn("failed to set serial number: " + DataUnitBuilder.toHex(serialNumber, ":")); - } - } - - /** - * Gets the serial number from the RC1180 chip - * - * @return byte array containing the serial number - */ - public byte[] getSerialNumber() { - byte[] serialNumber = null; - try { - serialNumber = configure.getSerialNumber(); - } catch (KNXException e) { - logger.warn("failed to get serial number"); - serialNumber = new byte[6]; - } - return serialNumber; - } - - /** - * Sets the domain address to the RC1180 chip - * - * @param domainAddress - * byte array containing the domain address - */ - public void setDomainAddress(final byte[] domainAddress) { - try { - configure.setDomainAddress(domainAddress); - } catch (KNXException e) { - logger.warn("failed to set domain address: " + DataUnitBuilder.toHex(domainAddress, ":")); - } - } - - /** - * Gets the domain address from the RC1180 chip - * - * @return byte array containing the domain address - */ - public byte[] getDomainAddress() { - byte[] domainAddress = null; - try { - domainAddress = configure.getDomainAddress(); - } catch (KNXException e) { - logger.warn("failed to get domain address"); - domainAddress = new byte[6]; - } - return domainAddress; - } - - private final class Receiver extends Thread { - - private static final byte START_BYTE = 0x68; - private static final byte END_BYTE = 0x16; - private static final int BUFFER_LENGTH = 255; - - private volatile boolean running; - - public Receiver() { - super("RF receiver"); - setDaemon(true); - running = false; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Thread#run() - */ - @Override - public void run() { - int available; - int read = 0; - int pos; - byte[] buffer = new byte[BUFFER_LENGTH]; - running = true; - while (running) { - try { - io.acquireUninterruptibly(); - available = is.available(); - if (available > 0) { - is.read(buffer, read, available); - read += available; + receiver = new Receiver(); + receiver.start(); + } + + public void putInAddressContainer(KNXAddress dst, SNorDoA address) { + addressContainer.put(dst, address); + } + + public Map getAddressContainer() { + return Collections.unmodifiableMap(addressContainer); + } + + /** + * Same as sendRequest()
    + * The function tries to find and set the source address and the serial number or domain address corresponding to + * the destination address. + * + * @param dst destination address + * @param hopCount repetition counter + * @param nsdu network layer service data unit + * @param wait true to wait, false to immediately return + * @throws KNXLinkClosedException + */ + public void sendSpoofingRequest(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu, boolean wait) throws + KNXLinkClosedException { + if (addressContainer.containsKey(dst)) { + logger.trace("send spoofing request"); + SNorDoA address = addressContainer.get(dst); + addressExtensionType = address.isDomainAddress(); + if (addressExtensionType) { + setDomainAddress(address.get()); + } else { + setSerialNumber(address.get()); + } + } + sendRequest(src, dst, hopCount, nsdu, wait); + addressExtensionType = DEFAULT_AET; + } + + /** + * Send a message. If this is the first message to the destination, this method will send the message 8 times, so + * the frame number fits + * + * @param src source address + * @param dst destination address + * @param hopCount repetition counter + * @param nsdu network layer service data unit + * @param wait true to wait, false to immediately return + * @throws KNXLinkClosedException + */ + public void sendRequest(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu, boolean wait) throws KNXLinkClosedException { + if (!linkLayerFrameNumbers.containsKey(dst)) { // if we don't know the frame number, take it over + linkLayerFrameNumbers.put(dst, -1); + for (int i = 0; i < 8; i++) { + sendRequest(src, dst, hopCount, nsdu, true); + } + return; + } + + int linkLayerFrameNumber = linkLayerFrameNumbers.get(dst); + linkLayerFrameNumber = (linkLayerFrameNumber + 1) % 8; + linkLayerFrameNumbers.put(dst, linkLayerFrameNumber); + + TransmittingFrame frame = new TransmittingFrame(src, dst, hopCount, linkLayerFrameNumber, addressExtensionType, nsdu); + + try { + logger.trace("sending " + frame); + io.acquireUninterruptibly(); + os.write(frame.getFrame()); + os.flush(); + + if (wait) { + try { + Thread.sleep(200); + } catch (InterruptedException e) { + } + } + } catch (IOException e) { + logger.error(e.getMessage()); + throw new KNXLinkClosedException(e.getMessage()); + } finally { + io.release(); + } + + } + + /** + * @return the status of the connection + */ + public boolean isOpen() { + return open; + } + + /** + * The connection is closed + */ + public void close() { + if (open) { + io.acquireUninterruptibly(); + receiver.stopReceiver(); + serialPort.close(); + open = false; + io.release(); + } + } + + /** + * Adds the specified event listener l to receive events from this connection. + *

    + * If l was already added as listener, no action is performed. + * + * @param l the listener to add + */ + public void addConnectionListener(final KNXListener l) { + listeners.add(l); + } + + /** + * Removes the specified event listener l, so it does no longer receive events from this connection. + *

    + * If l was not added in the first place, no action is performed. + * + * @param l the listener to remove + */ + public void removeConnectionListener(final KNXListener l) { + listeners.remove(l); + } + + /** + * Sets the serial number to the RC1180 chip + * + * @param serialNumber byte array containing the serial number + */ + public void setSerialNumber(final byte[] serialNumber) { + try { + configure.setSerialNumber(serialNumber); + } catch (KNXException e) { + logger.warn("failed to set serial number: " + DataUnitBuilder.toHex(serialNumber, ":")); + } + } + + /** + * Gets the serial number from the RC1180 chip + * + * @return byte array containing the serial number + */ + public byte[] getSerialNumber() { + byte[] serialNumber = null; + try { + serialNumber = configure.getSerialNumber(); + } catch (KNXException e) { + logger.warn("failed to get serial number"); + serialNumber = new byte[6]; + } + return serialNumber; + } + + /** + * Sets the domain address to the RC1180 chip + * + * @param domainAddress byte array containing the domain address + */ + public void setDomainAddress(final byte[] domainAddress) { + try { + configure.setDomainAddress(domainAddress); + } catch (KNXException e) { + logger.warn("failed to set domain address: " + DataUnitBuilder.toHex(domainAddress, ":")); + } + } + + /** + * Gets the domain address from the RC1180 chip + * + * @return byte array containing the domain address + */ + public byte[] getDomainAddress() { + byte[] domainAddress = null; + try { + domainAddress = configure.getDomainAddress(); + } catch (KNXException e) { + logger.warn("failed to get domain address"); + domainAddress = new byte[6]; + } + return domainAddress; + } + + private final class Receiver extends Thread { + + private static final byte START_BYTE = 0x68; + private static final byte END_BYTE = 0x16; + private static final int BUFFER_LENGTH = 255; + + private volatile boolean running; + + public Receiver() { + super("RF receiver"); + setDaemon(true); + running = false; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Thread#run() + */ + @Override + public void run() { + int available; + int read = 0; + int pos; + byte[] buffer = new byte[BUFFER_LENGTH]; + running = true; + while (running) { + try { + io.acquireUninterruptibly(); + available = is.available(); + if (available > 0) { + is.read(buffer, read, available); + read += available; /* Check if message reached end */ - while ((pos = containsEndByte(buffer)) > 0) { - int nextPos = pos + 1; - if (buffer[0] == START_BYTE) { - byte[] message = new byte[pos - 1]; - - System.arraycopy(buffer, 1, message, 0, message.length); - - try { - /* parse buffer and fire event */ - logger.trace("received message: " + DataUnitBuilder.toHex(message, ":")); - fireFrameReceived(new ReceivingFrame(message)); - } catch (KNXException e) { - logger.warn("message " + DataUnitBuilder.toHex(message, ":") - + " could not be parsed: " + e.getMessage()); - } - } - else { - logger.warn("start byte not received, skipping"); - } - byte[] newBuffer = new byte[BUFFER_LENGTH]; - System.arraycopy(buffer, nextPos, newBuffer, 0, BUFFER_LENGTH - nextPos); - buffer = newBuffer; - read -= nextPos; - } - } - } catch (IOException e) { - e.printStackTrace(); - logger.error(e.getMessage()); - running = false; - } finally { - io.release(); - } - - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - } - - public synchronized void stopReceiver() { - running = false; - } - - private int containsEndByte(byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - if (bytes[i] == END_BYTE) { - return i; - } - } - return -1; - } - - private void fireFrameReceived(ReceivingFrame frame) { - KNXAddress dst = frame.getDstAddress(); - if (!linkLayerFrameNumbers.containsKey(dst) - || frame.getLinkLayerFrameNumber() == ((linkLayerFrameNumbers.get(dst) + 1) % 8)) { - linkLayerFrameNumbers.put(frame.getDstAddress(), frame.getLinkLayerFrameNumber()); - } - - if (!addressContainer.containsKey(dst)) { - addressContainer.put(dst, new SNorDoA(frame.getAET(), frame.getSNorDoA())); - - } - - FrameEvent event = new FrameEvent(this, frame.getCemilData()); - for (EventListener listener : listeners.listeners()) { - try { - ((KNXListener) listener).frameReceived(event); - } catch (final RuntimeException e) { - removeConnectionListener((KNXListener) listener); - logger.error("removed event listener", e); - } - } - } - } + while ((pos = containsEndByte(buffer)) > 0) { + int nextPos = pos + 1; + if (buffer[0] == START_BYTE) { + byte[] message = new byte[pos - 1]; + + System.arraycopy(buffer, 1, message, 0, message.length); + + try { + /* parse buffer and fire event */ + logger.trace("received message: " + DataUnitBuilder.toHex(message, ":")); + fireFrameReceived(new ReceivingFrame(message)); + } catch (KNXException e) { + logger.warn( + "message " + DataUnitBuilder.toHex(message, ":") + " could not be parsed: " + e.getMessage()); + } + } else { + logger.warn("start byte not received, skipping"); + } + byte[] newBuffer = new byte[BUFFER_LENGTH]; + System.arraycopy(buffer, nextPos, newBuffer, 0, BUFFER_LENGTH - nextPos); + buffer = newBuffer; + read -= nextPos; + } + } + } catch (IOException e) { + e.printStackTrace(); + logger.error(e.getMessage()); + running = false; + } finally { + io.release(); + } + + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } + } + + public synchronized void stopReceiver() { + running = false; + } + + private int containsEndByte(byte[] bytes) { + for (int i = 0; i < bytes.length; i++) { + if (bytes[i] == END_BYTE) { + return i; + } + } + return -1; + } + + private void fireFrameReceived(ReceivingFrame frame) { + KNXAddress dst = frame.getDstAddress(); + if (!linkLayerFrameNumbers.containsKey(dst) || frame.getLinkLayerFrameNumber() == ((linkLayerFrameNumbers.get(dst) + 1) % 8)) { + linkLayerFrameNumbers.put(frame.getDstAddress(), frame.getLinkLayerFrameNumber()); + } + + if (!addressContainer.containsKey(dst)) { + addressContainer.put(dst, new SNorDoA(frame.getAET(), frame.getSNorDoA())); + + } + + FrameEvent event = new FrameEvent(this, frame.getCemilData()); + for (EventListener listener : listeners.listeners()) { + try { + ((KNXListener) listener).frameReceived(event); + } catch (final RuntimeException e) { + removeConnectionListener((KNXListener) listener); + logger.error("removed event listener", e); + } + } + } + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/ReceivingFrame.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/ReceivingFrame.java index 9e199268..ddae575c 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/ReceivingFrame.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/ReceivingFrame.java @@ -30,115 +30,110 @@ /** * Container for a frame coming from a RC1180 chip - * + * * @author Frederic Robra - * */ class ReceivingFrame { - private final byte KNXCtrl; - private final IndividualAddress srcAddress; - private KNXAddress dstAddress; - private final byte[] tpdu; - private final int hopCount; - private final int linkLayerFrameNumber; - private final boolean addressExtensionType; - private final byte[] address; + private final byte KNXCtrl; + private final IndividualAddress srcAddress; + private KNXAddress dstAddress; + private final byte[] tpdu; + private final int hopCount; + private final int linkLayerFrameNumber; + private final boolean addressExtensionType; + private final byte[] address; - /** - * Container for a frame coming from a RC1180 chip - * - * @param message - * byte array containing the raw message - * @throws KNXFormatException - */ - public ReceivingFrame(byte[] message) throws KNXFormatException { - byte length = message[0]; - if (length != message.length - 1) { - throw new KNXFormatException("wrong length of message"); - } - byte C = message[1]; - if (C != (byte) 0x44) { - throw new KNXFormatException("wrong C field"); - } - byte Esc = message[2]; - if (Esc != (byte) 0xFF) { - throw new KNXFormatException("wrong Esc field"); - } + /** + * Container for a frame coming from a RC1180 chip + * + * @param message byte array containing the raw message + * @throws KNXFormatException + */ + public ReceivingFrame(byte[] message) throws KNXFormatException { + byte length = message[0]; + if (length != message.length - 1) { + throw new KNXFormatException("wrong length of message"); + } + byte C = message[1]; + if (C != (byte) 0x44) { + throw new KNXFormatException("wrong C field"); + } + byte Esc = message[2]; + if (Esc != (byte) 0xFF) { + throw new KNXFormatException("wrong Esc field"); + } - address = new byte[6]; - System.arraycopy(message, 4, address, 0, 6); - addressExtensionType = (message[15] & 0x01) == 0 ? false : true; + address = new byte[6]; + System.arraycopy(message, 4, address, 0, 6); + addressExtensionType = (message[15] & 0x01) == 0 ? false : true; - KNXCtrl = message[10]; - byte[] srcAddress = new byte[2]; - System.arraycopy(message, 11, srcAddress, 0, 2); - this.srcAddress = new IndividualAddress(srcAddress); + KNXCtrl = message[10]; + byte[] srcAddress = new byte[2]; + System.arraycopy(message, 11, srcAddress, 0, 2); + this.srcAddress = new IndividualAddress(srcAddress); - byte[] dstAddress = new byte[2]; - System.arraycopy(message, 13, dstAddress, 0, 2); - if (((message[15] >> 7) & 1) > 0) { - this.dstAddress = new GroupAddress(dstAddress); - } - else { - this.dstAddress = new IndividualAddress(dstAddress); - } + byte[] dstAddress = new byte[2]; + System.arraycopy(message, 13, dstAddress, 0, 2); + if (((message[15] >> 7) & 1) > 0) { + this.dstAddress = new GroupAddress(dstAddress); + } else { + this.dstAddress = new IndividualAddress(dstAddress); + } - hopCount = (message[15] >> 4) & 0x07; - linkLayerFrameNumber = (message[15] >> 1) & 0x07; + hopCount = (message[15] >> 4) & 0x07; + linkLayerFrameNumber = (message[15] >> 1) & 0x07; - tpdu = new byte[message.length - 16]; - System.arraycopy(message, 16, tpdu, 0, tpdu.length); - } + tpdu = new byte[message.length - 16]; + System.arraycopy(message, 16, tpdu, 0, tpdu.length); + } - /** - * @return Linklayer Frame Number - */ - public int getLinkLayerFrameNumber() { - return linkLayerFrameNumber; - } + /** + * @return Linklayer Frame Number + */ + public int getLinkLayerFrameNumber() { + return linkLayerFrameNumber; + } - /** - * @return destination address - */ - public KNXAddress getDstAddress() { - return dstAddress; - } + /** + * @return destination address + */ + public KNXAddress getDstAddress() { + return dstAddress; + } - /** - * @return calimero cemil data - */ - public CEMILData getCemilData() { - if (KNXCtrl == 0x00) { - return new CEMILData(CEMILData.MC_LDATA_IND, srcAddress, dstAddress, tpdu, Priority.NORMAL, true, hopCount); - } - else { // Extended frame format - return new CEMILDataEx(CEMILData.MC_LDATA_IND, srcAddress, dstAddress, tpdu, Priority.NORMAL, true, - hopCount); - } - } + /** + * @return calimero cemil data + */ + public CEMILData getCemilData() { + if (KNXCtrl == 0x00) { + return new CEMILData(CEMILData.MC_LDATA_IND, srcAddress, dstAddress, tpdu, Priority.NORMAL, true, hopCount); + } else { // Extended frame format + return new CEMILDataEx(CEMILData.MC_LDATA_IND, srcAddress, dstAddress, tpdu, Priority.NORMAL, true, hopCount); + } + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return getCemilData().toString(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return getCemilData().toString(); + } - /** - * @return - */ - public Boolean getAET() { - return addressExtensionType; - } + /** + * @return + */ + public Boolean getAET() { + return addressExtensionType; + } - /** - * @return - */ - public byte[] getSNorDoA() { - return address; - } + /** + * @return + */ + public byte[] getSNorDoA() { + return address; + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/SNorDoA.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/SNorDoA.java index 8cde3421..ffa87369 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/SNorDoA.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/SNorDoA.java @@ -20,36 +20,35 @@ */ package tuwien.auto.calimero.serial.rc1180; -import java.util.Arrays; - import tuwien.auto.calimero.exception.KNXIllegalArgumentException; +import java.util.Arrays; + /** * @author Frederic Robra - * */ public class SNorDoA { - private final boolean AET; - private final byte[] number; + private final boolean AET; + private final byte[] number; - public SNorDoA(boolean AET, byte[] number) { - if (number.length != 6) { - throw new KNXIllegalArgumentException("wrong length of SN or DoA"); - } - this.AET = AET; - this.number = number; - } + public SNorDoA(boolean AET, byte[] number) { + if (number.length != 6) { + throw new KNXIllegalArgumentException("wrong length of SN or DoA"); + } + this.AET = AET; + this.number = number; + } - public boolean isSerialNumber() { - return !AET; - } + public boolean isSerialNumber() { + return !AET; + } - public boolean isDomainAddress() { - return AET; - } + public boolean isDomainAddress() { + return AET; + } - public byte[] get() { - return Arrays.copyOf(number, number.length); - } + public byte[] get() { + return Arrays.copyOf(number, number.length); + } } diff --git a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/TransmittingFrame.java b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/TransmittingFrame.java index a765e8c6..b6cd9d51 100644 --- a/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/TransmittingFrame.java +++ b/projects/driver/knx/src/main/java/tuwien/auto/calimero/serial/rc1180/TransmittingFrame.java @@ -27,101 +27,89 @@ /** * Container for a frame going to a RC1180 chip - * + * * @author Frederic Robra - * */ class TransmittingFrame { - private byte[] frame; - - /** - * Container for a frame going to a RC1180 chip. - *

    - * The Linklayer Frame Number will be 0 - * - * @param src - * source address - * @param dst - * destination address - * @param hopCount - * repetition counter - * @param nsdu - * network layer service data unit - */ - public TransmittingFrame(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu) { - init(src, dst, hopCount, 0, false, nsdu); - } - - /** - * Container for a frame going to a RC1180 chip. - * - * @param src - * source address - * @param dst - * destination address - * @param hopCount - * repetition counter - * @param addressExtentionType - * For the Standard Frame, the AET shall be used as follows:
    - * 0: The field SN/DoA in the first block shall be interpreted as the KNX Serial Number of the sender.
    - * 1: The field SN/DoA in the first block shall be interpreted as the RF Domain Address. - * @param linkLayerFrameNumber - * Linklayer Frame Number - * @param nsdu - * network layer service data unit - */ - public TransmittingFrame(IndividualAddress src, KNXAddress dst, int hopCount, int linkLayerFrameNumber, - boolean addressExtentionType, byte[] nsdu) { - init(src, dst, hopCount, linkLayerFrameNumber, addressExtentionType, nsdu); - } - - private void init(IndividualAddress src, KNXAddress dst, int hopCount, int linkLayerFrameNumber, - boolean addressExtentionType, byte[] nsdu) { - frame = new byte[nsdu.length + 7]; - - frame[0] = (byte) (frame.length - 1); - if (nsdu.length > 16) { // Extended frame format - frame[1] = 0x04; - } - else { - frame[1] = 0x00; - } - - frame[2] = (byte) (src.getRawAddress() >> 8); - frame[3] = (byte) src.getRawAddress(); - - frame[4] = (byte) (dst.getRawAddress() >> 8); - frame[5] = (byte) dst.getRawAddress(); - - frame[6] = 0; - if (dst instanceof GroupAddress) { - frame[6] = (byte) 0x80; - } - frame[6] |= hopCount << 4; - frame[6] |= addressExtentionType ? 1 : 0; // chip uses domain address or serial number - - frame[6] |= linkLayerFrameNumber << 1; - - System.arraycopy(nsdu, 0, frame, 7, nsdu.length); - - } - - /** - * @return byte array containing the raw frame - */ - public byte[] getFrame() { - return frame; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "frame = " + DataUnitBuilder.toHex(frame, ":"); - } + private byte[] frame; + + /** + * Container for a frame going to a RC1180 chip. + *

    + * The Linklayer Frame Number will be 0 + * + * @param src source address + * @param dst destination address + * @param hopCount repetition counter + * @param nsdu network layer service data unit + */ + public TransmittingFrame(IndividualAddress src, KNXAddress dst, int hopCount, byte[] nsdu) { + init(src, dst, hopCount, 0, false, nsdu); + } + + /** + * Container for a frame going to a RC1180 chip. + * + * @param src source address + * @param dst destination address + * @param hopCount repetition counter + * @param addressExtentionType For the Standard Frame, the AET shall be used as follows:
    + * 0: The field SN/DoA in the first block shall be interpreted as the KNX Serial Number of the sender.
    + * 1: The field SN/DoA in the first block shall be interpreted as the RF Domain Address. + * @param linkLayerFrameNumber Linklayer Frame Number + * @param nsdu network layer service data unit + */ + public TransmittingFrame(IndividualAddress src, KNXAddress dst, int hopCount, int linkLayerFrameNumber, boolean addressExtentionType, + byte[] nsdu) { + init(src, dst, hopCount, linkLayerFrameNumber, addressExtentionType, nsdu); + } + + private void init(IndividualAddress src, KNXAddress dst, int hopCount, int linkLayerFrameNumber, boolean addressExtentionType, byte[] + nsdu) { + frame = new byte[nsdu.length + 7]; + + frame[0] = (byte) (frame.length - 1); + if (nsdu.length > 16) { // Extended frame format + frame[1] = 0x04; + } else { + frame[1] = 0x00; + } + + frame[2] = (byte) (src.getRawAddress() >> 8); + frame[3] = (byte) src.getRawAddress(); + + frame[4] = (byte) (dst.getRawAddress() >> 8); + frame[5] = (byte) dst.getRawAddress(); + + frame[6] = 0; + if (dst instanceof GroupAddress) { + frame[6] = (byte) 0x80; + } + frame[6] |= hopCount << 4; + frame[6] |= addressExtentionType ? 1 : 0; // chip uses domain address or serial number + + frame[6] |= linkLayerFrameNumber << 1; + + System.arraycopy(nsdu, 0, frame, 7, nsdu.length); + + } + + /** + * @return byte array containing the raw frame + */ + public byte[] getFrame() { + return frame; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "frame = " + DataUnitBuilder.toHex(frame, ":"); + } } diff --git a/projects/driver/knx/src/main/resources/OSGI-INF/components.xml b/projects/driver/knx/src/main/resources/OSGI-INF/components.xml index 8479b4d5..7207a341 100644 --- a/projects/driver/knx/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/knx/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/knx/src/test/java/org/openmuc/framework/driver/knx/test/KnxGroupDPTest.java b/projects/driver/knx/src/test/java/org/openmuc/framework/driver/knx/test/KnxGroupDPTest.java index 3f17a1bd..312040df 100644 --- a/projects/driver/knx/src/test/java/org/openmuc/framework/driver/knx/test/KnxGroupDPTest.java +++ b/projects/driver/knx/src/test/java/org/openmuc/framework/driver/knx/test/KnxGroupDPTest.java @@ -20,15 +20,9 @@ */ package org.openmuc.framework.driver.knx.test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Map; - import org.junit.Test; import org.openmuc.framework.data.Value; import org.openmuc.framework.driver.knx.KnxGroupDP; - import tuwien.auto.calimero.GroupAddress; import tuwien.auto.calimero.dptxlator.DPT; import tuwien.auto.calimero.dptxlator.TranslatorTypes; @@ -36,39 +30,43 @@ import tuwien.auto.calimero.exception.KNXException; import tuwien.auto.calimero.exception.KNXFormatException; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * @author Frederic Robra - * */ public class KnxGroupDPTest { - @Test - public void test() throws KNXException { - @SuppressWarnings("unchecked") - Map mainTypes = TranslatorTypes.getAllMainTypes(); - KnxGroupDP dp = null; - GroupAddress main = new GroupAddress(new byte[] { 0x08, 0x00 }); - for (Map.Entry mainType : mainTypes.entrySet()) { - @SuppressWarnings("unchecked") - Map subTypes = mainType.getValue().getSubTypes(); + @Test + public void test() throws KNXException { + @SuppressWarnings("unchecked") + Map mainTypes = TranslatorTypes.getAllMainTypes(); + KnxGroupDP dp = null; + GroupAddress main = new GroupAddress(new byte[]{0x08, 0x00}); + for (Map.Entry mainType : mainTypes.entrySet()) { + @SuppressWarnings("unchecked") + Map subTypes = mainType.getValue().getSubTypes(); - for (Map.Entry subType : subTypes.entrySet()) { - DPT dpt = subType.getValue(); - System.out.println("testing: " + dpt.toString()); - try { - dp = new KnxGroupDP(main, dpt.getDescription(), dpt.getID()); - } catch (KNXException e) { - fail("could not create KnxGroupDP with: " + dpt.toString()); - } - try { - dp.getKnxValue().setDPTValue(dpt.getLowerValue()); - dp.getKnxValue().setDPTValue(dpt.getUpperValue()); - } catch (KNXFormatException e) { - fail("could not set upper and lower value to KnxGroupDP: " + dpt.toString()); - } - assertTrue(dp.getKnxValue().getOpenMucValue() instanceof Value); - } - } - } + for (Map.Entry subType : subTypes.entrySet()) { + DPT dpt = subType.getValue(); + System.out.println("testing: " + dpt.toString()); + try { + dp = new KnxGroupDP(main, dpt.getDescription(), dpt.getID()); + } catch (KNXException e) { + fail("could not create KnxGroupDP with: " + dpt.toString()); + } + try { + dp.getKnxValue().setDPTValue(dpt.getLowerValue()); + dp.getKnxValue().setDPTValue(dpt.getUpperValue()); + } catch (KNXFormatException e) { + fail("could not set upper and lower value to KnxGroupDP: " + dpt.toString()); + } + assertTrue(dp.getKnxValue().getOpenMucValue() instanceof Value); + } + } + } } diff --git a/projects/driver/mbus/build.gradle b/projects/driver/mbus/build.gradle index 39432e1a..118c53c6 100644 --- a/projects/driver/mbus/build.gradle +++ b/projects/driver/mbus/build.gradle @@ -1,4 +1,3 @@ - configurations.create('embed') def jmbusversion = "2.1.1-SNAPSHOT" @@ -7,24 +6,24 @@ dependencies { // compile group: 'org.openmuc', name: 'jmbus', version: jmbusversion // embed group: 'org.openmuc', name: 'jmbus', version: jmbusversion - compile files('dependencies/jmbus-' + jmbusversion + '.jar') - embed files('dependencies/jmbus-' + jmbusversion + '.jar') + compile files('dependencies/jmbus-' + jmbusversion + '.jar') + embed files('dependencies/jmbus-' + jmbusversion + '.jar') - compile project(':openmuc-core-spi') + compile project(':openmuc-core-spi') } jar { - manifest { - name = "OpenMUC Driver - M-Bus" - instruction 'Bundle-ClassPath', '.,lib/jmbus-' + jmbusversion + '.jar' - instruction 'Import-Package', '!org.openmuc.jmbus*,gnu.io,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - M-Bus" + instruction 'Bundle-ClassPath', '.,lib/jmbus-' + jmbusversion + '.jar' + instruction 'Import-Package', '!org.openmuc.jmbus*,gnu.io,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusConnection.java b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusConnection.java index 7eb5bdcd..b0cab590 100644 --- a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusConnection.java +++ b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusConnection.java @@ -20,313 +20,292 @@ */ package org.openmuc.framework.driver.mbus; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.data.*; +import org.openmuc.framework.driver.spi.*; +import org.openmuc.jmbus.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeoutException; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import org.openmuc.jmbus.Bcd; -import org.openmuc.jmbus.DataRecord; -import org.openmuc.jmbus.DecodingException; -import org.openmuc.jmbus.HexConverter; -import org.openmuc.jmbus.VariableDataStructure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class MBusConnection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(MBusConnection.class); - - private final MBusSerialInterface serialInterface; - private final int mBusAddress; - - public MBusConnection(MBusSerialInterface serialInterface, int mBusAddress) { - this.serialInterface = serialInterface; - this.mBusAddress = mBusAddress; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - - synchronized (serialInterface) { - - List chanScanInf = new ArrayList(); - - try { - VariableDataStructure msg = serialInterface.getMBusSap().read(mBusAddress); - msg.decodeDeep(); - - List vdb = msg.getDataRecords(); - - for (DataRecord block : vdb) { - - block.decode(); - - String vib = HexConverter.getShortHexStringFromByteArray(block.getVIB()); - String dib = HexConverter.getShortHexStringFromByteArray(block.getDIB()); - - ValueType valueType; - Integer valueLength; - - switch (block.getDataValueType()) { - case DATE: - valueType = ValueType.BYTE_ARRAY; - valueLength = 250; - break; - case STRING: - valueType = ValueType.BYTE_ARRAY; - valueLength = 250; - break; - case LONG: - valueType = ValueType.LONG; - valueLength = null; - break; - case DOUBLE: - valueType = ValueType.DOUBLE; - valueLength = null; - break; - default: - valueType = ValueType.BYTE_ARRAY; - valueLength = 250; - break; - } - - chanScanInf.add(new ChannelScanInfo(dib + ":" + vib, block.getDescription().toString(), valueType, - valueLength)); - } - } catch (IOException e) { - throw new ConnectionException(e); - } catch (TimeoutException e) { - return null; - } catch (DecodingException e) { - e.printStackTrace(); - logger.debug("Skipped invalid or unsupported M-Bus VariableDataBlock:" + e.getMessage()); - } - - return chanScanInf; - - } - } - - @Override - public void disconnect() { - - synchronized (serialInterface) { - - if (!serialInterface.isOpen()) { - return; - } - - serialInterface.decreaseConnectionCounter(); - } - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - synchronized (serialInterface) { - - if (!serialInterface.isOpen()) { - throw new ConnectionException(); - } - - VariableDataStructure variableDataStructure = null; - try { - variableDataStructure = serialInterface.getMBusSap().read(mBusAddress); - } catch (IOException e1) { - serialInterface.close(); - throw new ConnectionException(e1); - } catch (TimeoutException e1) { - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); - } - return null; - } - - try { - variableDataStructure.decodeDeep(); - } catch (DecodingException e1) { - e1.printStackTrace(); - } - - long timestamp = System.currentTimeMillis(); - - List dataRecords = variableDataStructure.getDataRecords(); - String[] dibvibs = new String[dataRecords.size()]; - - int i = 0; - for (DataRecord dataRecord : dataRecords) { - dibvibs[i++] = HexConverter.getShortHexStringFromByteArray(dataRecord.getDIB()) + ':' - + HexConverter.getShortHexStringFromByteArray(dataRecord.getVIB()); - } - - boolean selectForReadoutSet = false; - - for (ChannelRecordContainer container : containers) { - - if (container.getChannelAddress().startsWith("X")) { - String[] dibAndVib = container.getChannelAddress().split(":"); - if (dibAndVib.length != 2) { - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); - } - List dataRecordsToSelectForReadout = new ArrayList(1); - dataRecordsToSelectForReadout.add(new DataRecord(HexConverter - .getByteArrayFromShortHexString(dibAndVib[0].substring(1)), HexConverter - .getByteArrayFromShortHexString(dibAndVib[1]), new byte[] {}, 0)); - - selectForReadoutSet = true; - - try { - serialInterface.getMBusSap().selectForReadout(mBusAddress, dataRecordsToSelectForReadout); - } catch (IOException e) { - serialInterface.close(); - throw new ConnectionException(e); - } catch (TimeoutException e) { - container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); - continue; - } - - VariableDataStructure variableDataStructure2 = null; - try { - variableDataStructure2 = serialInterface.getMBusSap().read(mBusAddress); - } catch (IOException e1) { - serialInterface.close(); - throw new ConnectionException(e1); - } catch (TimeoutException e1) { - container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); - continue; - } - - try { - variableDataStructure2.decodeDeep(); - } catch (DecodingException e1) { - container.setRecord(new Record(Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED)); - logger.debug("Unable to parse VariableDataBlock received via M-Bus", e1); - continue; - } - - DataRecord dataRecord = variableDataStructure2.getDataRecords().get(0); - - setContainersRecord(timestamp, container, dataRecord); - - continue; - - } - - i = 0; - for (DataRecord dataRecord : dataRecords) { - - if (dibvibs[i++].equalsIgnoreCase(container.getChannelAddress())) { - - try { - dataRecord.decode(); - } catch (DecodingException e) { - container.setRecord(new Record(Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED)); - logger.debug("Unable to parse VariableDataBlock received via M-Bus", e); - break; - } - - setContainersRecord(timestamp, container, dataRecord); - - break; - - } - - } - - if (container.getRecord() == null) { - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); - } - - } - - if (selectForReadoutSet) { - try { - serialInterface.getMBusSap().resetReadout(mBusAddress); - } catch (IOException e) { - serialInterface.close(); - throw new ConnectionException(e); - } catch (TimeoutException e) { - try { - serialInterface.getMBusSap().normalize(mBusAddress); - } catch (IOException e1) { - serialInterface.close(); - throw new ConnectionException(e1); - } catch (TimeoutException e1) { - serialInterface.close(); - throw new ConnectionException(e1); - } - } - } - - return null; - - } - } - - private void setContainersRecord(long timestamp, ChannelRecordContainer container, DataRecord dataRecord) { - switch (dataRecord.getDataValueType()) { - case DATE: - container.setRecord(new Record(new StringValue(((Date) dataRecord.getDataValue()).toString()), timestamp)); - break; - case STRING: - container.setRecord(new Record(new StringValue((String) dataRecord.getDataValue()), timestamp)); - break; - case DOUBLE: - container.setRecord(new Record(new DoubleValue(dataRecord.getScaledDataValue()), timestamp)); - break; - case LONG: - if (dataRecord.getMultiplierExponent() == 0) { - container.setRecord(new Record(new LongValue((Long) dataRecord.getDataValue()), timestamp)); - } - else { - container.setRecord(new Record(new DoubleValue(dataRecord.getScaledDataValue()), timestamp)); - } - break; - case BCD: - if (dataRecord.getMultiplierExponent() == 0) { - container - .setRecord(new Record(new LongValue(((Bcd) dataRecord.getDataValue()).longValue()), timestamp)); - } - else { - container.setRecord(new Record(new DoubleValue(((Bcd) dataRecord.getDataValue()).longValue() - * Math.pow(10, dataRecord.getMultiplierExponent())), timestamp)); - } - break; - case NONE: - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION)); - if (logger.isWarnEnabled()) { - logger.warn("Received data record with : = " + container.getChannelAddress() - + " has value type NONE."); - } - break; - } - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } + private final static Logger logger = LoggerFactory.getLogger(MBusConnection.class); + + private final MBusSerialInterface serialInterface; + private final int mBusAddress; + + public MBusConnection(MBusSerialInterface serialInterface, int mBusAddress) { + this.serialInterface = serialInterface; + this.mBusAddress = mBusAddress; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + + synchronized (serialInterface) { + + List chanScanInf = new ArrayList(); + + try { + VariableDataStructure msg = serialInterface.getMBusSap().read(mBusAddress); + msg.decodeDeep(); + + List vdb = msg.getDataRecords(); + + for (DataRecord block : vdb) { + + block.decode(); + + String vib = HexConverter.getShortHexStringFromByteArray(block.getVIB()); + String dib = HexConverter.getShortHexStringFromByteArray(block.getDIB()); + + ValueType valueType; + Integer valueLength; + + switch (block.getDataValueType()) { + case DATE: + valueType = ValueType.BYTE_ARRAY; + valueLength = 250; + break; + case STRING: + valueType = ValueType.BYTE_ARRAY; + valueLength = 250; + break; + case LONG: + valueType = ValueType.LONG; + valueLength = null; + break; + case DOUBLE: + valueType = ValueType.DOUBLE; + valueLength = null; + break; + default: + valueType = ValueType.BYTE_ARRAY; + valueLength = 250; + break; + } + + chanScanInf.add(new ChannelScanInfo(dib + ":" + vib, block.getDescription().toString(), valueType, valueLength)); + } + } catch (IOException e) { + throw new ConnectionException(e); + } catch (TimeoutException e) { + return null; + } catch (DecodingException e) { + e.printStackTrace(); + logger.debug("Skipped invalid or unsupported M-Bus VariableDataBlock:" + e.getMessage()); + } + + return chanScanInf; + + } + } + + @Override + public void disconnect() { + + synchronized (serialInterface) { + + if (!serialInterface.isOpen()) { + return; + } + + serialInterface.decreaseConnectionCounter(); + } + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + synchronized (serialInterface) { + + if (!serialInterface.isOpen()) { + throw new ConnectionException(); + } + + VariableDataStructure variableDataStructure = null; + try { + variableDataStructure = serialInterface.getMBusSap().read(mBusAddress); + } catch (IOException e1) { + serialInterface.close(); + throw new ConnectionException(e1); + } catch (TimeoutException e1) { + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); + } + return null; + } + + try { + variableDataStructure.decodeDeep(); + } catch (DecodingException e1) { + e1.printStackTrace(); + } + + long timestamp = System.currentTimeMillis(); + + List dataRecords = variableDataStructure.getDataRecords(); + String[] dibvibs = new String[dataRecords.size()]; + + int i = 0; + for (DataRecord dataRecord : dataRecords) { + dibvibs[i++] = HexConverter.getShortHexStringFromByteArray(dataRecord.getDIB()) + ':' + HexConverter + .getShortHexStringFromByteArray(dataRecord.getVIB()); + } + + boolean selectForReadoutSet = false; + + for (ChannelRecordContainer container : containers) { + + if (container.getChannelAddress().startsWith("X")) { + String[] dibAndVib = container.getChannelAddress().split(":"); + if (dibAndVib.length != 2) { + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); + } + List dataRecordsToSelectForReadout = new ArrayList(1); + dataRecordsToSelectForReadout.add(new DataRecord(HexConverter.getByteArrayFromShortHexString(dibAndVib[0].substring(1)), + HexConverter.getByteArrayFromShortHexString(dibAndVib[1]), + new byte[]{}, 0)); + + selectForReadoutSet = true; + + try { + serialInterface.getMBusSap().selectForReadout(mBusAddress, dataRecordsToSelectForReadout); + } catch (IOException e) { + serialInterface.close(); + throw new ConnectionException(e); + } catch (TimeoutException e) { + container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); + continue; + } + + VariableDataStructure variableDataStructure2 = null; + try { + variableDataStructure2 = serialInterface.getMBusSap().read(mBusAddress); + } catch (IOException e1) { + serialInterface.close(); + throw new ConnectionException(e1); + } catch (TimeoutException e1) { + container.setRecord(new Record(Flag.DRIVER_ERROR_TIMEOUT)); + continue; + } + + try { + variableDataStructure2.decodeDeep(); + } catch (DecodingException e1) { + container.setRecord(new Record(Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED)); + logger.debug("Unable to parse VariableDataBlock received via M-Bus", e1); + continue; + } + + DataRecord dataRecord = variableDataStructure2.getDataRecords().get(0); + + setContainersRecord(timestamp, container, dataRecord); + + continue; + + } + + i = 0; + for (DataRecord dataRecord : dataRecords) { + + if (dibvibs[i++].equalsIgnoreCase(container.getChannelAddress())) { + + try { + dataRecord.decode(); + } catch (DecodingException e) { + container.setRecord(new Record(Flag.DRIVER_ERROR_DECODING_RESPONSE_FAILED)); + logger.debug("Unable to parse VariableDataBlock received via M-Bus", e); + break; + } + + setContainersRecord(timestamp, container, dataRecord); + + break; + + } + + } + + if (container.getRecord() == null) { + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_WITH_THIS_ADDRESS_NOT_FOUND)); + } + + } + + if (selectForReadoutSet) { + try { + serialInterface.getMBusSap().resetReadout(mBusAddress); + } catch (IOException e) { + serialInterface.close(); + throw new ConnectionException(e); + } catch (TimeoutException e) { + try { + serialInterface.getMBusSap().normalize(mBusAddress); + } catch (IOException e1) { + serialInterface.close(); + throw new ConnectionException(e1); + } catch (TimeoutException e1) { + serialInterface.close(); + throw new ConnectionException(e1); + } + } + } + + return null; + + } + } + + private void setContainersRecord(long timestamp, ChannelRecordContainer container, DataRecord dataRecord) { + switch (dataRecord.getDataValueType()) { + case DATE: + container.setRecord(new Record(new StringValue(((Date) dataRecord.getDataValue()).toString()), timestamp)); + break; + case STRING: + container.setRecord(new Record(new StringValue((String) dataRecord.getDataValue()), timestamp)); + break; + case DOUBLE: + container.setRecord(new Record(new DoubleValue(dataRecord.getScaledDataValue()), timestamp)); + break; + case LONG: + if (dataRecord.getMultiplierExponent() == 0) { + container.setRecord(new Record(new LongValue((Long) dataRecord.getDataValue()), timestamp)); + } else { + container.setRecord(new Record(new DoubleValue(dataRecord.getScaledDataValue()), timestamp)); + } + break; + case BCD: + if (dataRecord.getMultiplierExponent() == 0) { + container.setRecord(new Record(new LongValue(((Bcd) dataRecord.getDataValue()).longValue()), timestamp)); + } else { + container.setRecord(new Record(new DoubleValue( + ((Bcd) dataRecord.getDataValue()).longValue() * Math.pow(10, dataRecord.getMultiplierExponent())), timestamp)); + } + break; + case NONE: + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_VALUE_TYPE_CONVERSION_EXCEPTION)); + if (logger.isWarnEnabled()) { + logger.warn("Received data record with : = " + container.getChannelAddress() + " has value type NONE."); + } + break; + } + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusDriver.java b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusDriver.java index e38dfc45..3c538eb4 100644 --- a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusDriver.java +++ b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusDriver.java @@ -20,16 +20,7 @@ */ package org.openmuc.framework.driver.mbus; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverInfo; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import org.openmuc.framework.config.*; import org.openmuc.framework.driver.spi.Connection; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.DriverDeviceScanListener; @@ -38,171 +29,178 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeoutException; + public class MBusDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(MBusDriver.class); - - private final Map interfaces = new HashMap(); - - private final static DriverInfo info = new DriverInfo("mbus", // id - // description - "M-Bus (wired) is a protocol to read out meters.", - // device address - "Synopsis: :\nExample for : /dev/ttyS0 (Unix), COM1 (Windows)\nExample for : 5 for primary address 5", - // settings - "Synopsis: []\nThe default baud rate is 2400", - // channel address - "Synopsis: [X]:\nThe DIB and VIB fields in hexadecimal form seperated by a collon. If the channel address starts with an X then the specific data record will be selected for readout before reading it.", - // device scan parameters - "Synopsis: [baud_rate]\nExamples for : /dev/ttyS0 (Unix), COM1 (Windows)"); - - private boolean interruptScan; - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - - interruptScan = false; - - String[] args = settings.split("\\s+"); - if (args.length < 1 || args.length > 2) { - throw new ArgumentSyntaxException( - "Less than one or more than two arguments in the settings are not allowed."); - } - - int baudRate = 2400; - if (args.length == 2) { - try { - baudRate = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException(" is not an integer"); - } - } - - MBusSap mBusSap; - if (!interfaces.containsKey(args[0])) { - mBusSap = new MBusSap(args[0], baudRate); - try { - mBusSap.open(); - } catch (IllegalArgumentException e) { - throw new ArgumentSyntaxException(); - } catch (IOException e) { - throw new ScanException(e); - } - } - else { - mBusSap = interfaces.get(args[0]).getMBusSap(); - } - - mBusSap.setTimeout(1000); - - try { - for (int i = 0; i <= 250; i++) { - - if (interruptScan) { - throw new ScanInterruptedException(); - } - - if (i % 5 == 0) { - listener.scanProgressUpdate(i * 100 / 250); - } - logger.debug("scanning for meter with primary address {}", i); - try { - mBusSap.read(i); - } catch (TimeoutException e) { - continue; - } catch (IOException e) { - throw new ScanException(e); - } - listener.deviceFound(new DeviceScanInfo(args[0] + ":" + i, "", "")); - logger.debug("found meter: {}", i); - } - } finally { - mBusSap.close(); - } - - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - interruptScan = true; - - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - - String[] deviceAddressTokens = deviceAddress.trim().split(":"); - - if (deviceAddressTokens.length != 2) { - throw new ArgumentSyntaxException("The device address does not consist of two parameters."); - } - - String serialPortName = deviceAddressTokens[0]; - Integer mBusAddress = Integer.decode(deviceAddressTokens[1]); - if (mBusAddress == null) { - throw new ArgumentSyntaxException("Settings: mBusAddress (" + deviceAddressTokens[1] + ") is not a int"); - } - - MBusSerialInterface serialInterface; - - synchronized (this) { - - synchronized (interfaces) { - - serialInterface = interfaces.get(serialPortName); - - if (serialInterface == null) { - - int baudrate = 2400; - - if (!settings.isEmpty()) { - try { - baudrate = Integer.parseInt(settings); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException("Settings: baudrate is not a parsable number"); - } - } - - MBusSap mBusSap = new MBusSap(serialPortName, baudrate); - - try { - mBusSap.open(); - } catch (IOException e1) { - throw new ConnectionException("Unable to bind local interface: " + deviceAddressTokens[0]); - } - - serialInterface = new MBusSerialInterface(mBusSap, serialPortName, interfaces); - - } - } - - synchronized (serialInterface) { - try { - serialInterface.getMBusSap().read(mBusAddress); - } catch (IOException e) { - serialInterface.close(); - throw new ConnectionException(e); - } catch (TimeoutException e) { - if (serialInterface.getDeviceCounter() == 0) { - serialInterface.close(); - } - throw new ConnectionException(e); - } + private final static Logger logger = LoggerFactory.getLogger(MBusDriver.class); + + private final Map interfaces = new HashMap(); + + private final static DriverInfo info = new DriverInfo("mbus", // id + // description + "M-Bus (wired) is a protocol to read out meters.", + // device address + "Synopsis: :\nExample for : /dev/ttyS0 " + + "(Unix), COM1 (Windows)\nExample for : 5 for primary " + + "address 5", + // settings + "Synopsis: []\nThe default baud rate is 2400", + // channel address + "Synopsis: [X]:\nThe DIB and VIB fields in hexadecimal form seperated" + + " by a collon. If the channel address starts with an X then the " + + "specific data record will be selected for readout before reading it.", + // device scan parameters + "Synopsis: [baud_rate]\nExamples for : /dev/ttyS0 " + + "(Unix), COM1 (Windows)"); + + private boolean interruptScan; + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + + interruptScan = false; + + String[] args = settings.split("\\s+"); + if (args.length < 1 || args.length > 2) { + throw new ArgumentSyntaxException("Less than one or more than two arguments in the settings are not allowed."); + } + + int baudRate = 2400; + if (args.length == 2) { + try { + baudRate = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException(" is not an integer"); + } + } + + MBusSap mBusSap; + if (!interfaces.containsKey(args[0])) { + mBusSap = new MBusSap(args[0], baudRate); + try { + mBusSap.open(); + } catch (IllegalArgumentException e) { + throw new ArgumentSyntaxException(); + } catch (IOException e) { + throw new ScanException(e); + } + } else { + mBusSap = interfaces.get(args[0]).getMBusSap(); + } + + mBusSap.setTimeout(1000); + + try { + for (int i = 0; i <= 250; i++) { + + if (interruptScan) { + throw new ScanInterruptedException(); + } + + if (i % 5 == 0) { + listener.scanProgressUpdate(i * 100 / 250); + } + logger.debug("scanning for meter with primary address {}", i); + try { + mBusSap.read(i); + } catch (TimeoutException e) { + continue; + } catch (IOException e) { + throw new ScanException(e); + } + listener.deviceFound(new DeviceScanInfo(args[0] + ":" + i, "", "")); + logger.debug("found meter: {}", i); + } + } finally { + mBusSap.close(); + } + + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + interruptScan = true; + + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + + String[] deviceAddressTokens = deviceAddress.trim().split(":"); + + if (deviceAddressTokens.length != 2) { + throw new ArgumentSyntaxException("The device address does not consist of two parameters."); + } + + String serialPortName = deviceAddressTokens[0]; + Integer mBusAddress = Integer.decode(deviceAddressTokens[1]); + if (mBusAddress == null) { + throw new ArgumentSyntaxException("Settings: mBusAddress (" + deviceAddressTokens[1] + ") is not a int"); + } + + MBusSerialInterface serialInterface; + + synchronized (this) { + + synchronized (interfaces) { + + serialInterface = interfaces.get(serialPortName); + + if (serialInterface == null) { + + int baudrate = 2400; + + if (!settings.isEmpty()) { + try { + baudrate = Integer.parseInt(settings); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException("Settings: baudrate is not a parsable number"); + } + } + + MBusSap mBusSap = new MBusSap(serialPortName, baudrate); + + try { + mBusSap.open(); + } catch (IOException e1) { + throw new ConnectionException("Unable to bind local interface: " + deviceAddressTokens[0]); + } + + serialInterface = new MBusSerialInterface(mBusSap, serialPortName, interfaces); + + } + } + + synchronized (serialInterface) { + try { + serialInterface.getMBusSap().read(mBusAddress); + } catch (IOException e) { + serialInterface.close(); + throw new ConnectionException(e); + } catch (TimeoutException e) { + if (serialInterface.getDeviceCounter() == 0) { + serialInterface.close(); + } + throw new ConnectionException(e); + } - serialInterface.increaseConnectionCounter(); + serialInterface.increaseConnectionCounter(); - } + } - } + } - return new MBusConnection(serialInterface, mBusAddress); + return new MBusConnection(serialInterface, mBusAddress); - } + } } diff --git a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusSerialInterface.java b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusSerialInterface.java index 43a635d5..5d69f9e6 100644 --- a/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusSerialInterface.java +++ b/projects/driver/mbus/src/main/java/org/openmuc/framework/driver/mbus/MBusSerialInterface.java @@ -20,63 +20,62 @@ */ package org.openmuc.framework.driver.mbus; -import java.util.Map; - import org.openmuc.jmbus.MBusSap; +import java.util.Map; + /** * Class representing an MBus Connection.
    * This class will bind to the local com-interface.
    - * */ public class MBusSerialInterface { - private int connectionCounter = 0; - private final MBusSap mBusSap; - private boolean open = true; - private final String serialPortName; - private final Map interfaces; + private int connectionCounter = 0; + private final MBusSap mBusSap; + private boolean open = true; + private final String serialPortName; + private final Map interfaces; - public MBusSerialInterface(MBusSap mBusSap, String serialPortName, Map interfaces) { - this.mBusSap = mBusSap; - this.serialPortName = serialPortName; - this.interfaces = interfaces; - interfaces.put(serialPortName, this); - } + public MBusSerialInterface(MBusSap mBusSap, String serialPortName, Map interfaces) { + this.mBusSap = mBusSap; + this.serialPortName = serialPortName; + this.interfaces = interfaces; + interfaces.put(serialPortName, this); + } - public MBusSap getMBusSap() { - return mBusSap; - } + public MBusSap getMBusSap() { + return mBusSap; + } - public void increaseConnectionCounter() { - connectionCounter++; - } + public void increaseConnectionCounter() { + connectionCounter++; + } - public void decreaseConnectionCounter() { - connectionCounter--; - if (connectionCounter == 0) { - close(); - } - } + public void decreaseConnectionCounter() { + connectionCounter--; + if (connectionCounter == 0) { + close(); + } + } - public int getDeviceCounter() { - return connectionCounter; - } + public int getDeviceCounter() { + return connectionCounter; + } - public boolean isOpen() { - return open; - } + public boolean isOpen() { + return open; + } - public void close() { - synchronized (interfaces) { - mBusSap.close(); - open = false; - interfaces.remove(serialPortName); - } - } + public void close() { + synchronized (interfaces) { + mBusSap.close(); + open = false; + interfaces.remove(serialPortName); + } + } - public String getInterfaceAddress() { - return serialPortName; - } + public String getInterfaceAddress() { + return serialPortName; + } } diff --git a/projects/driver/mbus/src/main/resources/OSGI-INF/components.xml b/projects/driver/mbus/src/main/resources/OSGI-INF/components.xml index 3ae08fa6..4f800a27 100644 --- a/projects/driver/mbus/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/mbus/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/mbus/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java b/projects/driver/mbus/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java index e05a8c72..3fc20c68 100644 --- a/projects/driver/mbus/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java +++ b/projects/driver/mbus/src/test/java/org/openmuc/mbus/test/MBusObjectLocatorTest.java @@ -22,29 +22,29 @@ public class MBusObjectLocatorTest { - // @Test - // public void mbusStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); - // - // byte[] difs = locator.getDifs(); - // - // Assert.assertEquals(1, difs.length); - // Assert.assertEquals((byte) 4, difs[0]); - // - // byte[] vifs = locator.getVifs(); - // - // Assert.assertEquals(2, vifs.length); - // Assert.assertEquals((byte) 0x94, vifs[0]); - // Assert.assertEquals((byte) 0x3a, vifs[1]); - // - // } - // - // @Test - // public void obisStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); - // } + // @Test + // public void mbusStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); + // + // byte[] difs = locator.getDifs(); + // + // Assert.assertEquals(1, difs.length); + // Assert.assertEquals((byte) 4, difs[0]); + // + // byte[] vifs = locator.getVifs(); + // + // Assert.assertEquals(2, vifs.length); + // Assert.assertEquals((byte) 0x94, vifs[0]); + // Assert.assertEquals((byte) 0x3a, vifs[1]); + // + // } + // + // @Test + // public void obisStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); + // } } diff --git a/projects/driver/modbus/build.gradle b/projects/driver/modbus/build.gradle index 4c809f87..90763dfa 100644 --- a/projects/driver/modbus/build.gradle +++ b/projects/driver/modbus/build.gradle @@ -1,31 +1,30 @@ - configurations.create('embed') repositories { - mavenCentral() + mavenCentral() } dependencies { - compile project(':openmuc-core-spi') - compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') + compile project(':openmuc-core-spi') + compile files('../../../dependencies/rxtxcomm_api-2.2pre2.jar') - compile group: 'net.wimpi', name: 'jamod', version: '1.2' + compile group: 'net.wimpi', name: 'jamod', version: '1.2' - embed group: 'net.wimpi', name: 'jamod', version: '1.2' + embed group: 'net.wimpi', name: 'jamod', version: '1.2' } jar { - manifest { - name = "OpenMUC Modbus Driver" - instruction 'Bundle-ClassPath', '.,lib/jamod-1.2.jar' - instruction 'Import-Package', '!net.wimpi*,gnu.io;resolution:=optional,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Modbus Driver" + instruction 'Bundle-ClassPath', '.,lib/jamod-1.2.jar' + instruction 'Import-Package', '!net.wimpi*,gnu.io;resolution:=optional,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EDatatype.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EDatatype.java index f4038f9b..50710040 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EDatatype.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EDatatype.java @@ -23,99 +23,97 @@ public enum EDatatype { - BOOLEAN("boolean", 1), // 1 Bit - SHORT("short", 1), // 1 Register - INT("int", 2), // 2 Registers - FLOAT("float", 2), // 2 Registers - DOUBLE("double", 4), // 4 Registers - LONG("long", 4), // 4 Registers - BYTEARRAY("bytearray", 0), // registerCount is calculated dynamically, the 0 will be overwritten - BYTE_HIGH("byte_high", 1), BYTE_LOW("byte_low", 1); - - private final String datatype; - private final int registerCount; - - EDatatype(String datatypeAsString, int registerSize) { - datatype = datatypeAsString; - registerCount = registerSize; - } - - public int getRegisterCount() { - return registerCount; - } - - @Override - public String toString() { - return datatype; - } - - /** - * @param enumAsString - * @return the EDatatype - */ - public static EDatatype getEnumFromString(String enumAsString) { - EDatatype returnValue = null; - - if (enumAsString != null) { - - for (EDatatype type : EDatatype.values()) { - if (enumAsString.equals(type.datatype)) { - returnValue = EDatatype.valueOf(enumAsString.toUpperCase()); - break; - } - else if (enumAsString.toUpperCase().matches("BYTEARRAY\\[\\d+\\]")) { - // Special check for BYTEARRAY[n] datatyp - returnValue = EDatatype.BYTEARRAY; - break; - } - } - } - - if (returnValue == null) { - throw new RuntimeException(enumAsString - + " is not supported. Use one of the following supported datatypes: " + getSupportedDatatypes()); - } - - return returnValue; - - } - - /** - * @return all supported datatypes - */ - public static String getSupportedDatatypes() { - - String supported = ""; - - for (EDatatype type : EDatatype.values()) { - supported += type.toString() + ", "; - } - - return supported; - } - - /** - * Checks if the datatype is valid - * - * @param enumAsString - * @return true if valid, otherwise false - */ - public static boolean isValidDatatype(String enumAsString) { - boolean returnValue = false; - - for (EDatatype type : EDatatype.values()) { - - if (type.toString().toLowerCase().equals(enumAsString.toLowerCase())) { - returnValue = true; - break; - } - else if (enumAsString.toUpperCase().matches("BYTEARRAY\\[\\d+\\]")) { - // Special check for BYTEARRAY[n] datatyp - returnValue = true; - break; - } - } - - return returnValue; - } + BOOLEAN("boolean", 1), // 1 Bit + SHORT("short", 1), // 1 Register + INT("int", 2), // 2 Registers + FLOAT("float", 2), // 2 Registers + DOUBLE("double", 4), // 4 Registers + LONG("long", 4), // 4 Registers + BYTEARRAY("bytearray", 0), // registerCount is calculated dynamically, the 0 will be overwritten + BYTE_HIGH("byte_high", 1), BYTE_LOW("byte_low", 1); + + private final String datatype; + private final int registerCount; + + EDatatype(String datatypeAsString, int registerSize) { + datatype = datatypeAsString; + registerCount = registerSize; + } + + public int getRegisterCount() { + return registerCount; + } + + @Override + public String toString() { + return datatype; + } + + /** + * @param enumAsString + * @return the EDatatype + */ + public static EDatatype getEnumFromString(String enumAsString) { + EDatatype returnValue = null; + + if (enumAsString != null) { + + for (EDatatype type : EDatatype.values()) { + if (enumAsString.equals(type.datatype)) { + returnValue = EDatatype.valueOf(enumAsString.toUpperCase()); + break; + } else if (enumAsString.toUpperCase().matches("BYTEARRAY\\[\\d+\\]")) { + // Special check for BYTEARRAY[n] datatyp + returnValue = EDatatype.BYTEARRAY; + break; + } + } + } + + if (returnValue == null) { + throw new RuntimeException( + enumAsString + " is not supported. Use one of the following supported datatypes: " + getSupportedDatatypes()); + } + + return returnValue; + + } + + /** + * @return all supported datatypes + */ + public static String getSupportedDatatypes() { + + String supported = ""; + + for (EDatatype type : EDatatype.values()) { + supported += type.toString() + ", "; + } + + return supported; + } + + /** + * Checks if the datatype is valid + * + * @param enumAsString + * @return true if valid, otherwise false + */ + public static boolean isValidDatatype(String enumAsString) { + boolean returnValue = false; + + for (EDatatype type : EDatatype.values()) { + + if (type.toString().toLowerCase().equals(enumAsString.toLowerCase())) { + returnValue = true; + break; + } else if (enumAsString.toUpperCase().matches("BYTEARRAY\\[\\d+\\]")) { + // Special check for BYTEARRAY[n] datatyp + returnValue = true; + break; + } + } + + return returnValue; + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EFunctionCode.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EFunctionCode.java index 11d05da0..f59416ce 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EFunctionCode.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EFunctionCode.java @@ -25,12 +25,12 @@ * Supported modbuss function codes */ public enum EFunctionCode { - FC_01_READ_COILS, // - FC_02_READ_DISCRETE_INPUTS, // - FC_03_READ_HOLDING_REGISTERS, // - FC_04_READ_INPUT_REGISTERS, // - FC_05_WRITE_SINGLE_COIL, // - FC_06_WRITE_SINGLE_REGISTER, // - FC_15_WRITE_MULITPLE_COILS, // - FC_16_WRITE_MULTIPLE_REGISTERS // + FC_01_READ_COILS, // + FC_02_READ_DISCRETE_INPUTS, // + FC_03_READ_HOLDING_REGISTERS, // + FC_04_READ_INPUT_REGISTERS, // + FC_05_WRITE_SINGLE_COIL, // + FC_06_WRITE_SINGLE_REGISTER, // + FC_15_WRITE_MULITPLE_COILS, // + FC_16_WRITE_MULTIPLE_REGISTERS // } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EPrimaryTable.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EPrimaryTable.java index 3c86fe51..11a05212 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EPrimaryTable.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/EPrimaryTable.java @@ -25,48 +25,48 @@ */ public enum EPrimaryTable { - COILS, // - DISCRETE_INPUTS, // - INPUT_REGISTERS, // - HOLDING_REGISTERS; + COILS, // + DISCRETE_INPUTS, // + INPUT_REGISTERS, // + HOLDING_REGISTERS; - public static EPrimaryTable getEnumfromString(String enumAsString) { - EPrimaryTable returnValue = null; - if (enumAsString != null) { - for (EPrimaryTable value : EPrimaryTable.values()) { - if (enumAsString.toUpperCase().equals(value.toString())) { - returnValue = EPrimaryTable.valueOf(enumAsString.toUpperCase()); - break; - } - } - } - if (returnValue == null) { - throw new RuntimeException(enumAsString - + " is not supported. Use one of the following supported primary tables: " + getSupportedValues()); - } - return returnValue; - } + public static EPrimaryTable getEnumfromString(String enumAsString) { + EPrimaryTable returnValue = null; + if (enumAsString != null) { + for (EPrimaryTable value : EPrimaryTable.values()) { + if (enumAsString.toUpperCase().equals(value.toString())) { + returnValue = EPrimaryTable.valueOf(enumAsString.toUpperCase()); + break; + } + } + } + if (returnValue == null) { + throw new RuntimeException( + enumAsString + " is not supported. Use one of the following supported primary tables: " + getSupportedValues()); + } + return returnValue; + } - /** - * @return all supported values as a comma separated string - */ - public static String getSupportedValues() { - String supported = ""; - for (EPrimaryTable value : EPrimaryTable.values()) { - supported += value.toString() + ", "; - } - return supported; - } + /** + * @return all supported values as a comma separated string + */ + public static String getSupportedValues() { + String supported = ""; + for (EPrimaryTable value : EPrimaryTable.values()) { + supported += value.toString() + ", "; + } + return supported; + } - public static boolean isValidValue(String enumAsString) { - boolean returnValue = false; - for (EPrimaryTable type : EPrimaryTable.values()) { - if (type.toString().toLowerCase().equals(enumAsString.toLowerCase())) { - returnValue = true; - break; - } - } - return returnValue; - } + public static boolean isValidValue(String enumAsString) { + boolean returnValue = false; + for (EPrimaryTable type : EPrimaryTable.values()) { + if (type.toString().toLowerCase().equals(enumAsString.toLowerCase())) { + returnValue = true; + break; + } + } + return returnValue; + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannel.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannel.java index 8f326e35..edb4d4e1 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannel.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannel.java @@ -25,288 +25,299 @@ public class ModbusChannel { - private final static Logger logger = LoggerFactory.getLogger(ModbusDriver.class); - - /** Contains values to define the access method of the channel */ - public static enum EAccess { - READ, WRITE - } - - /** A Parameter of the channel address */ - public static final int IGNORE_UNIT_ID = -1; - - /** A Parameter of the channel address */ - private final int UNITID = 0; - - /** A Parameter of the channel address */ - private final int PRIMARYTABLE = 1; - - /** A Parameter of the channel address */ - private final int ADDRESS = 2; - - /** A Parameter of the channel address */ - private final int DATATYPE = 3; - - /** Start address to read or write from */ - private int startAddress; - - /** Number of registers/coils to be read or written */ - private int count; - - /** Used to determine the register/coil count */ - private EDatatype datatype; - - /** Used to determine the appropriate transaction method */ - private EFunctionCode functionCode; - - /** Specifies whether the channel should be read or written */ - private EAccess accessFlag; - - /** */ - private EPrimaryTable primaryTable; - - private String channelAddress; - - /** - * Is needed when the target device is behind a gateway/bridge which connects Modbus TCP with Modbus+ or Modbus - * Serial. Note: Some devices requires the unitId even if they are in a Modbus TCP Network and have their own IP. - * "Like when a device ties its Ethernet and RS-485 ports together and broadcasts whatever shows up on one side, - * onto the other if the packet isn't for themselves, but isn't "just a bridge"." - */ - private int unitId; - - public ModbusChannel(String channelAddress, EAccess accessFlag) { - - channelAddress = channelAddress.toLowerCase(); - String[] addressParams = decomposeAddress(channelAddress); - if (addressParams != null && checkAddressParams(addressParams)) { - this.channelAddress = channelAddress; - setUnitId(addressParams[UNITID]); - setPrimaryTable(addressParams[PRIMARYTABLE]); - setStartAddress(addressParams[ADDRESS]); - setDatatype(addressParams[DATATYPE]); - setCount(addressParams[DATATYPE]); - setAccessFlag(accessFlag); - setFunctionCode(); - } - else { - throw new RuntimeException("Address initialization faild! Invalid parameters used: " + channelAddress); - } - - } - - public void update(EAccess access) { - setAccessFlag(access); - setFunctionCode(); - } - - private String[] decomposeAddress(String channelAddress) { - - String[] param = new String[4]; - String[] addressParams = channelAddress.toLowerCase().split(":"); - if (addressParams.length == 3) { - param[UNITID] = ""; - param[PRIMARYTABLE] = addressParams[0]; - param[ADDRESS] = addressParams[1]; - param[DATATYPE] = addressParams[2]; - } - else if (addressParams.length == 4) { - param[UNITID] = addressParams[0]; - param[PRIMARYTABLE] = addressParams[1]; - param[ADDRESS] = addressParams[2]; - param[DATATYPE] = addressParams[3]; - } - else { - return null; - } - return param; - } - - private boolean checkAddressParams(String[] params) { - boolean returnValue = false; - if ((params[UNITID].matches("\\d+?") || params[UNITID].equals("")) - && EPrimaryTable.isValidValue(params[PRIMARYTABLE]) && params[ADDRESS].matches("\\d+?") - && EDatatype.isValidDatatype(params[DATATYPE])) { - returnValue = true; - } - return returnValue; - } - - private void setFunctionCode() { - if (accessFlag.equals(EAccess.READ)) { - setFunctionCodeForReading(); - } - else { - setFunctionCodeForWriting(); - } - } - - /** - * Matches data type with function code - * - * @throws Exception - */ - private void setFunctionCodeForReading() { - - switch (datatype) { - case BOOLEAN: - if (primaryTable.equals(EPrimaryTable.COILS)) { - functionCode = EFunctionCode.FC_01_READ_COILS; - } - else if (primaryTable.equals(EPrimaryTable.DISCRETE_INPUTS)) { - functionCode = EFunctionCode.FC_02_READ_DISCRETE_INPUTS; - } - else { - invalidReadAddressParameterCombination(); - } - break; - case SHORT: - case INT: - case FLOAT: - case DOUBLE: - case LONG: - case BYTE_HIGH: - case BYTE_LOW: - case BYTEARRAY: - if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { - functionCode = EFunctionCode.FC_03_READ_HOLDING_REGISTERS; - } - else if (primaryTable.equals(EPrimaryTable.INPUT_REGISTERS)) { - functionCode = EFunctionCode.FC_04_READ_INPUT_REGISTERS; - } - else { - invalidReadAddressParameterCombination(); - } - break; - default: - throw new RuntimeException("read: Datatype " + datatype.toString() + " not supported yet!"); - } - } - - private void setFunctionCodeForWriting() { - switch (datatype) { - case BOOLEAN: - if (primaryTable.equals(EPrimaryTable.COILS)) { - functionCode = EFunctionCode.FC_05_WRITE_SINGLE_COIL; - } - else { - invalidWriteAddressParameterCombination(); - } - break; - case BYTE_HIGH: - case BYTE_LOW: - case SHORT: - if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { - functionCode = EFunctionCode.FC_06_WRITE_SINGLE_REGISTER; - } - else { - invalidWriteAddressParameterCombination(); - } - break; - case INT: - case FLOAT: - case DOUBLE: - case LONG: - case BYTEARRAY: - if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { - functionCode = EFunctionCode.FC_16_WRITE_MULTIPLE_REGISTERS; - } - else { - invalidWriteAddressParameterCombination(); - } - break; - default: - throw new RuntimeException("write: Datatype " + datatype.toString() + " not supported yet!"); - } - } - - private void invalidWriteAddressParameterCombination() { - throw new RuntimeException("Invalid channel address parameter combination for writing. \n Datatype: " - + datatype.toString().toUpperCase() + " PrimaryTable: " + primaryTable.toString().toUpperCase()); - } - - private void invalidReadAddressParameterCombination() { - throw new RuntimeException("Invalid channel address parameter combination for reading. \n Datatype: " - + datatype.toString().toUpperCase() + " PrimaryTable: " + primaryTable.toString().toUpperCase()); - } - - private void setStartAddress(String startAddress) { - this.startAddress = Integer.parseInt(startAddress); - } - - private void setDatatype(String datatype) { - this.datatype = EDatatype.getEnumFromString(datatype); - } - - private void setUnitId(String unitId) { - if (unitId.equals("")) { - this.unitId = IGNORE_UNIT_ID; - } - else { - this.unitId = Integer.parseInt(unitId); - } - } - - private void setPrimaryTable(String primaryTable) { - this.primaryTable = EPrimaryTable.getEnumfromString(primaryTable); - } - - public EPrimaryTable getPrimaryTable() { - return primaryTable; - } - - private void setCount(String addressParamDatatyp) { - if (datatype.equals(EDatatype.BYTEARRAY)) { - // TODO check syntax first? bytearray[n] - - // special handling of the BYTEARRAY datatyp - String[] datatypParts = addressParamDatatyp.split("\\[|\\]"); // split string either at [ or ] - if (datatypParts.length == 2) { - count = Integer.parseInt(datatypParts[1]); - } - } - else { - // all other datatyps - count = datatype.getRegisterCount(); - } - } - - private void setAccessFlag(EAccess accessFlag) { - this.accessFlag = accessFlag; - } - - public int getStartAddress() { - return startAddress; - } - - public int getCount() { - return count; - } - - public EDatatype getDatatype() { - return datatype; - } - - public EFunctionCode getFunctionCode() { - return functionCode; - } - - public EAccess getAccessFlag() { - return accessFlag; - } - - public int getUnitId() { - return unitId; - } - - public String getChannelAddress() { - return channelAddress; - } - - @Override - public String toString() { - return "channeladdress: " + unitId + ":" + primaryTable.toString() + ":" + startAddress + ":" - + datatype.toString(); - } + private final static Logger logger = LoggerFactory.getLogger(ModbusDriver.class); + + /** + * Contains values to define the access method of the channel + */ + public static enum EAccess { + READ, WRITE + } + + /** + * A Parameter of the channel address + */ + public static final int IGNORE_UNIT_ID = -1; + + /** + * A Parameter of the channel address + */ + private final int UNITID = 0; + + /** + * A Parameter of the channel address + */ + private final int PRIMARYTABLE = 1; + + /** + * A Parameter of the channel address + */ + private final int ADDRESS = 2; + + /** + * A Parameter of the channel address + */ + private final int DATATYPE = 3; + + /** + * Start address to read or write from + */ + private int startAddress; + + /** + * Number of registers/coils to be read or written + */ + private int count; + + /** + * Used to determine the register/coil count + */ + private EDatatype datatype; + + /** + * Used to determine the appropriate transaction method + */ + private EFunctionCode functionCode; + + /** + * Specifies whether the channel should be read or written + */ + private EAccess accessFlag; + + /** */ + private EPrimaryTable primaryTable; + + private String channelAddress; + + /** + * Is needed when the target device is behind a gateway/bridge which connects Modbus TCP with Modbus+ or Modbus + * Serial. Note: Some devices requires the unitId even if they are in a Modbus TCP Network and have their own IP. + * "Like when a device ties its Ethernet and RS-485 ports together and broadcasts whatever shows up on one side, + * onto the other if the packet isn't for themselves, but isn't "just a bridge"." + */ + private int unitId; + + public ModbusChannel(String channelAddress, EAccess accessFlag) { + + channelAddress = channelAddress.toLowerCase(); + String[] addressParams = decomposeAddress(channelAddress); + if (addressParams != null && checkAddressParams(addressParams)) { + this.channelAddress = channelAddress; + setUnitId(addressParams[UNITID]); + setPrimaryTable(addressParams[PRIMARYTABLE]); + setStartAddress(addressParams[ADDRESS]); + setDatatype(addressParams[DATATYPE]); + setCount(addressParams[DATATYPE]); + setAccessFlag(accessFlag); + setFunctionCode(); + } else { + throw new RuntimeException("Address initialization faild! Invalid parameters used: " + channelAddress); + } + + } + + public void update(EAccess access) { + setAccessFlag(access); + setFunctionCode(); + } + + private String[] decomposeAddress(String channelAddress) { + + String[] param = new String[4]; + String[] addressParams = channelAddress.toLowerCase().split(":"); + if (addressParams.length == 3) { + param[UNITID] = ""; + param[PRIMARYTABLE] = addressParams[0]; + param[ADDRESS] = addressParams[1]; + param[DATATYPE] = addressParams[2]; + } else if (addressParams.length == 4) { + param[UNITID] = addressParams[0]; + param[PRIMARYTABLE] = addressParams[1]; + param[ADDRESS] = addressParams[2]; + param[DATATYPE] = addressParams[3]; + } else { + return null; + } + return param; + } + + private boolean checkAddressParams(String[] params) { + boolean returnValue = false; + if ((params[UNITID].matches("\\d+?") || params[UNITID].equals("")) && EPrimaryTable + .isValidValue(params[PRIMARYTABLE]) && params[ADDRESS].matches("\\d+?") && EDatatype.isValidDatatype(params[DATATYPE])) { + returnValue = true; + } + return returnValue; + } + + private void setFunctionCode() { + if (accessFlag.equals(EAccess.READ)) { + setFunctionCodeForReading(); + } else { + setFunctionCodeForWriting(); + } + } + + /** + * Matches data type with function code + * + * @throws Exception + */ + private void setFunctionCodeForReading() { + + switch (datatype) { + case BOOLEAN: + if (primaryTable.equals(EPrimaryTable.COILS)) { + functionCode = EFunctionCode.FC_01_READ_COILS; + } else if (primaryTable.equals(EPrimaryTable.DISCRETE_INPUTS)) { + functionCode = EFunctionCode.FC_02_READ_DISCRETE_INPUTS; + } else { + invalidReadAddressParameterCombination(); + } + break; + case SHORT: + case INT: + case FLOAT: + case DOUBLE: + case LONG: + case BYTE_HIGH: + case BYTE_LOW: + case BYTEARRAY: + if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { + functionCode = EFunctionCode.FC_03_READ_HOLDING_REGISTERS; + } else if (primaryTable.equals(EPrimaryTable.INPUT_REGISTERS)) { + functionCode = EFunctionCode.FC_04_READ_INPUT_REGISTERS; + } else { + invalidReadAddressParameterCombination(); + } + break; + default: + throw new RuntimeException("read: Datatype " + datatype.toString() + " not supported yet!"); + } + } + + private void setFunctionCodeForWriting() { + switch (datatype) { + case BOOLEAN: + if (primaryTable.equals(EPrimaryTable.COILS)) { + functionCode = EFunctionCode.FC_05_WRITE_SINGLE_COIL; + } else { + invalidWriteAddressParameterCombination(); + } + break; + case BYTE_HIGH: + case BYTE_LOW: + case SHORT: + if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { + functionCode = EFunctionCode.FC_06_WRITE_SINGLE_REGISTER; + } else { + invalidWriteAddressParameterCombination(); + } + break; + case INT: + case FLOAT: + case DOUBLE: + case LONG: + case BYTEARRAY: + if (primaryTable.equals(EPrimaryTable.HOLDING_REGISTERS)) { + functionCode = EFunctionCode.FC_16_WRITE_MULTIPLE_REGISTERS; + } else { + invalidWriteAddressParameterCombination(); + } + break; + default: + throw new RuntimeException("write: Datatype " + datatype.toString() + " not supported yet!"); + } + } + + private void invalidWriteAddressParameterCombination() { + throw new RuntimeException("Invalid channel address parameter combination for writing. \n Datatype: " + datatype.toString() + .toUpperCase() + + " PrimaryTable: " + primaryTable + .toString().toUpperCase()); + } + + private void invalidReadAddressParameterCombination() { + throw new RuntimeException("Invalid channel address parameter combination for reading. \n Datatype: " + datatype.toString() + .toUpperCase() + + " PrimaryTable: " + primaryTable + .toString().toUpperCase()); + } + + private void setStartAddress(String startAddress) { + this.startAddress = Integer.parseInt(startAddress); + } + + private void setDatatype(String datatype) { + this.datatype = EDatatype.getEnumFromString(datatype); + } + + private void setUnitId(String unitId) { + if (unitId.equals("")) { + this.unitId = IGNORE_UNIT_ID; + } else { + this.unitId = Integer.parseInt(unitId); + } + } + + private void setPrimaryTable(String primaryTable) { + this.primaryTable = EPrimaryTable.getEnumfromString(primaryTable); + } + + public EPrimaryTable getPrimaryTable() { + return primaryTable; + } + + private void setCount(String addressParamDatatyp) { + if (datatype.equals(EDatatype.BYTEARRAY)) { + // TODO check syntax first? bytearray[n] + + // special handling of the BYTEARRAY datatyp + String[] datatypParts = addressParamDatatyp.split("\\[|\\]"); // split string either at [ or ] + if (datatypParts.length == 2) { + count = Integer.parseInt(datatypParts[1]); + } + } else { + // all other datatyps + count = datatype.getRegisterCount(); + } + } + + private void setAccessFlag(EAccess accessFlag) { + this.accessFlag = accessFlag; + } + + public int getStartAddress() { + return startAddress; + } + + public int getCount() { + return count; + } + + public EDatatype getDatatype() { + return datatype; + } + + public EFunctionCode getFunctionCode() { + return functionCode; + } + + public EAccess getAccessFlag() { + return accessFlag; + } + + public int getUnitId() { + return unitId; + } + + public String getChannelAddress() { + return channelAddress; + } + + @Override + public String toString() { + return "channeladdress: " + unitId + ":" + primaryTable.toString() + ":" + startAddress + ":" + datatype.toString(); + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannelGroup.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannelGroup.java index 3ce1ed1a..97a3062e 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannelGroup.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusChannelGroup.java @@ -21,12 +21,8 @@ package org.openmuc.framework.driver.modbus; -import java.util.ArrayList; -import java.util.List; - import net.wimpi.modbus.procimg.InputRegister; import net.wimpi.modbus.util.BitVector; - import org.openmuc.framework.data.BooleanValue; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; @@ -34,223 +30,229 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * Represents a group of channels which is used for a multiple read request - * + * * @author Marco Mittelsdorf */ public class ModbusChannelGroup { - private final static Logger logger = LoggerFactory.getLogger(ModbusChannelGroup.class); - - private static final int INVALID = -1; - - private EPrimaryTable primaryTable; - private final ArrayList channels; - - /** Start address to read from */ - private int startAddress; - - /** Number of Registers/Coils to be read from startAddress */ - private int count; - - private int unitId; - private EFunctionCode functionCode; - private final String samplingGroup; - - public ModbusChannelGroup(String samplingGroup, ArrayList channels) { - this.samplingGroup = samplingGroup; - this.channels = channels; - setPrimaryTable(); - setUnitId(); - setStartAddress(); - setCount(); - setFunctionCode(); - } - - public String getInfo() { - String info = "SamplingGroup: '" + samplingGroup + "' Channels: "; - for (ModbusChannel channel : channels) { - info += channel.getStartAddress() + ":" + channel.getDatatype() + ", "; - } - return info; - } - - private void setFunctionCode() { - - boolean init = false; - EFunctionCode tempFunctionCode = null; - - for (ModbusChannel channel : channels) { - if (!init) { - tempFunctionCode = channel.getFunctionCode(); - init = true; - } - else { - if (!tempFunctionCode.equals(channel.getFunctionCode())) { - throw new RuntimeException("FunctionCodes of all channels within the samplingGroup '" - + samplingGroup + "' are not equal! Change your openmuc config."); - } - } - } - - functionCode = tempFunctionCode; - } - - /** - * Checks if the primary table of all channels of the sampling group is equal and sets the value for the channel - * group. - */ - private void setPrimaryTable() { - - boolean init = false; - EPrimaryTable tempPrimaryTable = null; - - for (ModbusChannel channel : channels) { - if (!init) { - tempPrimaryTable = channel.getPrimaryTable(); - init = true; - } - else { - if (!tempPrimaryTable.equals(channel.getPrimaryTable())) { - throw new RuntimeException("Primary tables of all channels within the samplingGroup '" - + samplingGroup + "' are not equal! Change your openmuc config."); - } - } - } - - primaryTable = tempPrimaryTable; - } - - private void setUnitId() { - int idOfFirstChannel = INVALID; - for (ModbusChannel channel : channels) { - if (idOfFirstChannel == INVALID) { - idOfFirstChannel = channel.getUnitId(); - } - else { - if (channel.getUnitId() != idOfFirstChannel) { - - // TODO ??? - // channel 1 device 1 = unitId 1 - // channel 1 device 2 = unitId 2 - // Does openmuc calls the read method for channels of different devices? - // If so, then the check for UnitID has to be modified. Only channels of the same device - // need to have the same unitId... - throw new RuntimeException("UnitIds of all channels within the samplingGroup '" + samplingGroup - + "' are not equal! Change your openmuc config."); - } - } - } - unitId = idOfFirstChannel; - } - - /** - * StartAddress is the smallest channel address of the group - */ - private void setStartAddress() { - - startAddress = INVALID; - for (ModbusChannel channel : channels) { - if (startAddress == INVALID) { - startAddress = channel.getStartAddress(); - } - else { - startAddress = Math.min(startAddress, channel.getStartAddress()); - } - } - } - - /** - * - */ - private void setCount() { - - int maximumAddress = startAddress; - - for (ModbusChannel channel : channels) { - maximumAddress = Math.max(maximumAddress, channel.getStartAddress() + channel.getCount()); - } - - count = maximumAddress - startAddress; - } - - public void setChannelValues(InputRegister[] inputRegisters, List containers) { - - for (ModbusChannel channel : channels) { - // determine start index of the registers which contain the values of the channel - int registerIndex = channel.getStartAddress() - getStartAddress(); - // create a temporary register array - InputRegister[] registers = new InputRegister[channel.getCount()]; - // copy relevant registers for the channel - for (int i = 0; i < channel.getCount(); i++) { - registers[i] = inputRegisters[registerIndex + i]; - } - // now we have a register array which contains the value of the channel - ChannelRecordContainer container = searchContainer(channel.getChannelAddress(), containers); - ModbusDriverUtil util = new ModbusDriverUtil(); - long receiveTime = System.currentTimeMillis(); - - Value value = util.getRegistersValue(registers, channel.getDatatype()); - // logger.debug("got value: " + value + " for channel: " + channel.getChannelAddress()); - container.setRecord(new Record(value, receiveTime)); - } - } - - public void setChannelValues(BitVector bitVector, List containers) { - - for (ModbusChannel channel : channels) { - - long receiveTime = System.currentTimeMillis(); - - // determine start index of the registers which contain the values of the channel - int index = channel.getStartAddress() - getStartAddress(); - - BooleanValue value = new BooleanValue(bitVector.getBit(index)); - ChannelRecordContainer container = searchContainer(channel.getChannelAddress(), containers); - container.setRecord(new Record(value, receiveTime)); - } - } - - private ChannelRecordContainer searchContainer(String channelAddress, List containers) { - for (ChannelRecordContainer container : containers) { - if (container.getChannelAddress().toUpperCase().equals(channelAddress.toUpperCase())) { - return container; - } - } - throw new RuntimeException("No ChannelRecordContainer found for channelAddress " + channelAddress); - } - - public boolean isEmpty() { - boolean result = true; - if (channels.size() != 0) { - result = false; - } - return result; - } - - public EPrimaryTable getPrimaryTable() { - return primaryTable; - } - - public int getStartAddress() { - return startAddress; - } - - public int getCount() { - return count; - } - - public int getUnitId() { - return unitId; - } - - public EFunctionCode getFunctionCode() { - return functionCode; - } - - public ArrayList getChannels() { - return channels; - } + private final static Logger logger = LoggerFactory.getLogger(ModbusChannelGroup.class); + + private static final int INVALID = -1; + + private EPrimaryTable primaryTable; + private final ArrayList channels; + + /** + * Start address to read from + */ + private int startAddress; + + /** + * Number of Registers/Coils to be read from startAddress + */ + private int count; + + private int unitId; + private EFunctionCode functionCode; + private final String samplingGroup; + + public ModbusChannelGroup(String samplingGroup, ArrayList channels) { + this.samplingGroup = samplingGroup; + this.channels = channels; + setPrimaryTable(); + setUnitId(); + setStartAddress(); + setCount(); + setFunctionCode(); + } + + public String getInfo() { + String info = "SamplingGroup: '" + samplingGroup + "' Channels: "; + for (ModbusChannel channel : channels) { + info += channel.getStartAddress() + ":" + channel.getDatatype() + ", "; + } + return info; + } + + private void setFunctionCode() { + + boolean init = false; + EFunctionCode tempFunctionCode = null; + + for (ModbusChannel channel : channels) { + if (!init) { + tempFunctionCode = channel.getFunctionCode(); + init = true; + } else { + if (!tempFunctionCode.equals(channel.getFunctionCode())) { + throw new RuntimeException( + "FunctionCodes of all channels within the samplingGroup '" + samplingGroup + "' are not equal! Change your " + + "openmuc config."); + } + } + } + + functionCode = tempFunctionCode; + } + + /** + * Checks if the primary table of all channels of the sampling group is equal and sets the value for the channel + * group. + */ + private void setPrimaryTable() { + + boolean init = false; + EPrimaryTable tempPrimaryTable = null; + + for (ModbusChannel channel : channels) { + if (!init) { + tempPrimaryTable = channel.getPrimaryTable(); + init = true; + } else { + if (!tempPrimaryTable.equals(channel.getPrimaryTable())) { + throw new RuntimeException( + "Primary tables of all channels within the samplingGroup '" + samplingGroup + "' are not equal! Change your " + + "openmuc config."); + } + } + } + + primaryTable = tempPrimaryTable; + } + + private void setUnitId() { + int idOfFirstChannel = INVALID; + for (ModbusChannel channel : channels) { + if (idOfFirstChannel == INVALID) { + idOfFirstChannel = channel.getUnitId(); + } else { + if (channel.getUnitId() != idOfFirstChannel) { + + // TODO ??? + // channel 1 device 1 = unitId 1 + // channel 1 device 2 = unitId 2 + // Does openmuc calls the read method for channels of different devices? + // If so, then the check for UnitID has to be modified. Only channels of the same device + // need to have the same unitId... + throw new RuntimeException( + "UnitIds of all channels within the samplingGroup '" + samplingGroup + "' are not equal! Change your openmuc " + + "config."); + } + } + } + unitId = idOfFirstChannel; + } + + /** + * StartAddress is the smallest channel address of the group + */ + private void setStartAddress() { + + startAddress = INVALID; + for (ModbusChannel channel : channels) { + if (startAddress == INVALID) { + startAddress = channel.getStartAddress(); + } else { + startAddress = Math.min(startAddress, channel.getStartAddress()); + } + } + } + + /** + * + */ + private void setCount() { + + int maximumAddress = startAddress; + + for (ModbusChannel channel : channels) { + maximumAddress = Math.max(maximumAddress, channel.getStartAddress() + channel.getCount()); + } + + count = maximumAddress - startAddress; + } + + public void setChannelValues(InputRegister[] inputRegisters, List containers) { + + for (ModbusChannel channel : channels) { + // determine start index of the registers which contain the values of the channel + int registerIndex = channel.getStartAddress() - getStartAddress(); + // create a temporary register array + InputRegister[] registers = new InputRegister[channel.getCount()]; + // copy relevant registers for the channel + for (int i = 0; i < channel.getCount(); i++) { + registers[i] = inputRegisters[registerIndex + i]; + } + // now we have a register array which contains the value of the channel + ChannelRecordContainer container = searchContainer(channel.getChannelAddress(), containers); + ModbusDriverUtil util = new ModbusDriverUtil(); + long receiveTime = System.currentTimeMillis(); + + Value value = util.getRegistersValue(registers, channel.getDatatype()); + // logger.debug("got value: " + value + " for channel: " + channel.getChannelAddress()); + container.setRecord(new Record(value, receiveTime)); + } + } + + public void setChannelValues(BitVector bitVector, List containers) { + + for (ModbusChannel channel : channels) { + + long receiveTime = System.currentTimeMillis(); + + // determine start index of the registers which contain the values of the channel + int index = channel.getStartAddress() - getStartAddress(); + + BooleanValue value = new BooleanValue(bitVector.getBit(index)); + ChannelRecordContainer container = searchContainer(channel.getChannelAddress(), containers); + container.setRecord(new Record(value, receiveTime)); + } + } + + private ChannelRecordContainer searchContainer(String channelAddress, List containers) { + for (ChannelRecordContainer container : containers) { + if (container.getChannelAddress().toUpperCase().equals(channelAddress.toUpperCase())) { + return container; + } + } + throw new RuntimeException("No ChannelRecordContainer found for channelAddress " + channelAddress); + } + + public boolean isEmpty() { + boolean result = true; + if (channels.size() != 0) { + result = false; + } + return result; + } + + public EPrimaryTable getPrimaryTable() { + return primaryTable; + } + + public int getStartAddress() { + return startAddress; + } + + public int getCount() { + return count; + } + + public int getUnitId() { + return unitId; + } + + public EFunctionCode getFunctionCode() { + return functionCode; + } + + public ArrayList getChannels() { + return channels; + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusConnection.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusConnection.java index dbd36615..a5c56c7e 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusConnection.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusConnection.java @@ -20,30 +20,15 @@ */ package org.openmuc.framework.driver.modbus; -import java.util.Hashtable; -import java.util.List; - import net.wimpi.modbus.ModbusException; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.ModbusSlaveException; import net.wimpi.modbus.io.ModbusTransaction; -import net.wimpi.modbus.msg.ReadCoilsRequest; -import net.wimpi.modbus.msg.ReadCoilsResponse; -import net.wimpi.modbus.msg.ReadInputDiscretesRequest; -import net.wimpi.modbus.msg.ReadInputDiscretesResponse; -import net.wimpi.modbus.msg.ReadInputRegistersRequest; -import net.wimpi.modbus.msg.ReadInputRegistersResponse; -import net.wimpi.modbus.msg.ReadMultipleRegistersRequest; -import net.wimpi.modbus.msg.ReadMultipleRegistersResponse; -import net.wimpi.modbus.msg.WriteCoilRequest; -import net.wimpi.modbus.msg.WriteMultipleCoilsRequest; -import net.wimpi.modbus.msg.WriteMultipleRegistersRequest; -import net.wimpi.modbus.msg.WriteSingleRegisterRequest; +import net.wimpi.modbus.msg.*; import net.wimpi.modbus.procimg.InputRegister; import net.wimpi.modbus.procimg.Register; import net.wimpi.modbus.procimg.SimpleRegister; import net.wimpi.modbus.util.BitVector; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; @@ -51,277 +36,278 @@ import org.openmuc.framework.driver.spi.ChannelRecordContainer; import org.openmuc.framework.driver.spi.Connection; +import java.util.Hashtable; +import java.util.List; + public abstract class ModbusConnection implements Connection { - private final ReadCoilsRequest readCoilsRequest; - private final ReadInputDiscretesRequest readInputDiscretesRequest; - private final WriteCoilRequest writeCoilRequest; - private final WriteMultipleCoilsRequest writeMultipleCoilsRequest; - private final ReadInputRegistersRequest readInputRegistersRequest; - private final ReadMultipleRegistersRequest readHoldingRegisterRequest; - private final WriteSingleRegisterRequest writeSingleRegisterRequest; - private final WriteMultipleRegistersRequest writeMultipleRegistersRequest; - - private ModbusTransaction transaction; - private final ModbusDriverUtil util; - // List do manage Channel Objects to avoid to check the syntax of each channel address for every read or write - private final Hashtable modbusChannels; - - public abstract void connect() throws Exception; - - @Override - public abstract void disconnect(); - - public ModbusConnection() { - - transaction = null; - util = new ModbusDriverUtil(); - modbusChannels = new Hashtable(); - - readCoilsRequest = new ReadCoilsRequest(); - readInputDiscretesRequest = new ReadInputDiscretesRequest(); - readInputRegistersRequest = new ReadInputRegistersRequest(); - readHoldingRegisterRequest = new ReadMultipleRegistersRequest(); - writeCoilRequest = new WriteCoilRequest(); - writeMultipleCoilsRequest = new WriteMultipleCoilsRequest(); - writeSingleRegisterRequest = new WriteSingleRegisterRequest(); - writeMultipleRegistersRequest = new WriteMultipleRegistersRequest(); - } - - public void setTransaction(ModbusTransaction transaction) { - this.transaction = transaction; - } - - public Value readChannel(ModbusChannel channel) throws ModbusException { - Value value = null; - - switch (channel.getFunctionCode()) { - case FC_01_READ_COILS: - value = util.getBitVectorsValue(readCoils(channel)); - break; - case FC_02_READ_DISCRETE_INPUTS: - value = util.getBitVectorsValue(readDiscreteInputs(channel)); - break; - case FC_03_READ_HOLDING_REGISTERS: - value = util.getRegistersValue(readHoldingRegisters(channel), channel.getDatatype()); - break; - case FC_04_READ_INPUT_REGISTERS: - value = util.getRegistersValue(readInputRegisters(channel), channel.getDatatype()); - break; - default: - throw new RuntimeException("FunctionCode " + channel.getFunctionCode() + " not supported yet"); - } - - return value; - } - - public void readChannelGroup(ModbusChannelGroup channelGroup, List containers) - throws ModbusException { - - switch (channelGroup.getFunctionCode()) { - case FC_01_READ_COILS: - BitVector coils = readCoils(channelGroup); - channelGroup.setChannelValues(coils, containers); - break; - case FC_02_READ_DISCRETE_INPUTS: - BitVector discretInput = readDiscreteInputs(channelGroup); - channelGroup.setChannelValues(discretInput, containers); - break; - case FC_03_READ_HOLDING_REGISTERS: - Register[] registers = readHoldingRegisters(channelGroup); - channelGroup.setChannelValues(registers, containers); - break; - case FC_04_READ_INPUT_REGISTERS: - InputRegister[] inputRegisters = readInputRegisters(channelGroup); - channelGroup.setChannelValues(inputRegisters, containers); - break; - default: - throw new RuntimeException("FunctionCode " + channelGroup.getFunctionCode() + " not supported yet"); - } - } - - public void writeChannel(ModbusChannel channel, Value value) throws ModbusException, RuntimeException { - - switch (channel.getFunctionCode()) { - case FC_05_WRITE_SINGLE_COIL: - writeSingleCoil(channel, value.asBoolean()); - break; - case FC_15_WRITE_MULITPLE_COILS: - writeMultipleCoils(channel, util.getBitVectorFromByteArray(value)); - break; - case FC_06_WRITE_SINGLE_REGISTER: - writeSingleRegister(channel, new SimpleRegister(value.asShort())); - break; - case FC_16_WRITE_MULTIPLE_REGISTERS: - writeMultipleRegisters(channel, util.valueToRegisters(value, channel.getDatatype())); - break; - default: - throw new RuntimeException("FunctionCode " + channel.getFunctionCode().toString() + " not supported yet"); - } - } - - public void setChannelsWithErrorFlag(List containers) { - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(null, null, Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE)); - } - } - - protected ModbusChannel getModbusChannel(String channelAddress, EAccess access) { - - ModbusChannel modbusChannel = null; - - // check if the channel object already exists in the list - if (modbusChannels.containsKey(channelAddress)) { - modbusChannel = modbusChannels.get(channelAddress); - - // if the channel object exists the access flag might has to be updated - // (this is case occurs when the channel is readable and writable) - if (!modbusChannel.getAccessFlag().equals(access)) { - modbusChannel.update(access); - } - } - // create a new channel object - else { - modbusChannel = new ModbusChannel(channelAddress, access); - modbusChannels.put(channelAddress, modbusChannel); - } - - return modbusChannel; - - } - - private synchronized BitVector readCoils(int startAddress, int count, int unitID) throws ModbusException { - readCoilsRequest.setReference(startAddress); - readCoilsRequest.setBitCount(count); - readCoilsRequest.setUnitID(unitID); - transaction.setRequest(readCoilsRequest); - transaction.execute(); - BitVector bitvector = ((ReadCoilsResponse) transaction.getResponse()).getCoils(); - bitvector.forceSize(count); - return bitvector; - - } - - public BitVector readCoils(ModbusChannel channel) throws ModbusException { - return readCoils(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); - } - - public BitVector readCoils(ModbusChannelGroup channelGroup) throws ModbusException { - return readCoils(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); - } - - private synchronized BitVector readDiscreteInputs(int startAddress, int count, int unitID) throws ModbusException { - readInputDiscretesRequest.setReference(startAddress); - readInputDiscretesRequest.setBitCount(count); - readInputDiscretesRequest.setUnitID(unitID); - transaction.setRequest(readInputDiscretesRequest); - transaction.execute(); - BitVector bitvector = ((ReadInputDiscretesResponse) transaction.getResponse()).getDiscretes(); - bitvector.forceSize(count); - return bitvector; - } - - public BitVector readDiscreteInputs(ModbusChannel channel) throws ModbusException { - return readDiscreteInputs(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); - } - - public BitVector readDiscreteInputs(ModbusChannelGroup channelGroup) throws ModbusException { - return readDiscreteInputs(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); - } - - private synchronized Register[] readHoldingRegisters(int startAddress, int count, int unitID) - throws ModbusException { - readHoldingRegisterRequest.setReference(startAddress); - readHoldingRegisterRequest.setWordCount(count); - readHoldingRegisterRequest.setUnitID(unitID); - transaction.setRequest(readHoldingRegisterRequest); - transaction.execute(); - return ((ReadMultipleRegistersResponse) transaction.getResponse()).getRegisters(); - } - - public Register[] readHoldingRegisters(ModbusChannel channel) throws ModbusException { - return readHoldingRegisters(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); - } - - public Register[] readHoldingRegisters(ModbusChannelGroup channelGroup) throws ModbusException { - return readHoldingRegisters(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); - } - - /** - * Read InputRegisters - * - * @param startAddress - * @param count - * @param unitID - * @return the InputRegister[] - * @throws ModbusIOException - * @throws ModbusSlaveException - * @throws ModbusException - */ - private synchronized InputRegister[] readInputRegisters(int startAddress, int count, int unitID) - throws ModbusIOException, ModbusSlaveException, ModbusException { - readInputRegistersRequest.setReference(startAddress); - readInputRegistersRequest.setWordCount(count); - readInputRegistersRequest.setUnitID(unitID); - transaction.setRequest(readInputRegistersRequest); - transaction.execute(); - InputRegister[] registers = ((ReadInputRegistersResponse) transaction.getResponse()).getRegisters(); - return registers; - } - - /** - * Read InputRegisters for a channel - * - * @param channel - * @return the InputRegister - * @throws ModbusException - */ - public InputRegister[] readInputRegisters(ModbusChannel channel) throws ModbusException { - return readInputRegisters(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); - } - - /** - * Read InputRegisters for a channelGroup - * - * @param channelGroup - * @return the InputRegister - * @throws ModbusException - */ - public InputRegister[] readInputRegisters(ModbusChannelGroup channelGroup) throws ModbusException { - return readInputRegisters(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); - } - - public synchronized void writeSingleCoil(ModbusChannel channel, boolean state) throws ModbusException { - writeCoilRequest.setReference(channel.getStartAddress()); - writeCoilRequest.setCoil(state); - writeCoilRequest.setUnitID(channel.getUnitId()); - transaction.setRequest(writeCoilRequest); - transaction.execute(); - } - - public synchronized void writeMultipleCoils(ModbusChannel channel, BitVector coils) throws ModbusException { - writeMultipleCoilsRequest.setReference(channel.getStartAddress()); - writeMultipleCoilsRequest.setCoils(coils); - writeMultipleCoilsRequest.setUnitID(channel.getUnitId()); - transaction.setRequest(writeMultipleCoilsRequest); - transaction.execute(); - } - - public synchronized void writeSingleRegister(ModbusChannel channel, Register register) throws ModbusException { - - writeSingleRegisterRequest.setReference(channel.getStartAddress()); - writeSingleRegisterRequest.setRegister(register); - writeSingleRegisterRequest.setUnitID(channel.getUnitId()); - transaction.setRequest(writeSingleRegisterRequest); - transaction.execute(); - } - - public synchronized void writeMultipleRegisters(ModbusChannel channel, Register[] registers) throws ModbusException { - writeMultipleRegistersRequest.setReference(channel.getStartAddress()); - writeMultipleRegistersRequest.setRegisters(registers); - writeMultipleRegistersRequest.setUnitID(channel.getUnitId()); - transaction.setRequest(writeMultipleRegistersRequest); - transaction.execute(); - } + private final ReadCoilsRequest readCoilsRequest; + private final ReadInputDiscretesRequest readInputDiscretesRequest; + private final WriteCoilRequest writeCoilRequest; + private final WriteMultipleCoilsRequest writeMultipleCoilsRequest; + private final ReadInputRegistersRequest readInputRegistersRequest; + private final ReadMultipleRegistersRequest readHoldingRegisterRequest; + private final WriteSingleRegisterRequest writeSingleRegisterRequest; + private final WriteMultipleRegistersRequest writeMultipleRegistersRequest; + + private ModbusTransaction transaction; + private final ModbusDriverUtil util; + // List do manage Channel Objects to avoid to check the syntax of each channel address for every read or write + private final Hashtable modbusChannels; + + public abstract void connect() throws Exception; + + @Override + public abstract void disconnect(); + + public ModbusConnection() { + + transaction = null; + util = new ModbusDriverUtil(); + modbusChannels = new Hashtable(); + + readCoilsRequest = new ReadCoilsRequest(); + readInputDiscretesRequest = new ReadInputDiscretesRequest(); + readInputRegistersRequest = new ReadInputRegistersRequest(); + readHoldingRegisterRequest = new ReadMultipleRegistersRequest(); + writeCoilRequest = new WriteCoilRequest(); + writeMultipleCoilsRequest = new WriteMultipleCoilsRequest(); + writeSingleRegisterRequest = new WriteSingleRegisterRequest(); + writeMultipleRegistersRequest = new WriteMultipleRegistersRequest(); + } + + public void setTransaction(ModbusTransaction transaction) { + this.transaction = transaction; + } + + public Value readChannel(ModbusChannel channel) throws ModbusException { + Value value = null; + + switch (channel.getFunctionCode()) { + case FC_01_READ_COILS: + value = util.getBitVectorsValue(readCoils(channel)); + break; + case FC_02_READ_DISCRETE_INPUTS: + value = util.getBitVectorsValue(readDiscreteInputs(channel)); + break; + case FC_03_READ_HOLDING_REGISTERS: + value = util.getRegistersValue(readHoldingRegisters(channel), channel.getDatatype()); + break; + case FC_04_READ_INPUT_REGISTERS: + value = util.getRegistersValue(readInputRegisters(channel), channel.getDatatype()); + break; + default: + throw new RuntimeException("FunctionCode " + channel.getFunctionCode() + " not supported yet"); + } + + return value; + } + + public void readChannelGroup(ModbusChannelGroup channelGroup, List containers) throws ModbusException { + + switch (channelGroup.getFunctionCode()) { + case FC_01_READ_COILS: + BitVector coils = readCoils(channelGroup); + channelGroup.setChannelValues(coils, containers); + break; + case FC_02_READ_DISCRETE_INPUTS: + BitVector discretInput = readDiscreteInputs(channelGroup); + channelGroup.setChannelValues(discretInput, containers); + break; + case FC_03_READ_HOLDING_REGISTERS: + Register[] registers = readHoldingRegisters(channelGroup); + channelGroup.setChannelValues(registers, containers); + break; + case FC_04_READ_INPUT_REGISTERS: + InputRegister[] inputRegisters = readInputRegisters(channelGroup); + channelGroup.setChannelValues(inputRegisters, containers); + break; + default: + throw new RuntimeException("FunctionCode " + channelGroup.getFunctionCode() + " not supported yet"); + } + } + + public void writeChannel(ModbusChannel channel, Value value) throws ModbusException, RuntimeException { + + switch (channel.getFunctionCode()) { + case FC_05_WRITE_SINGLE_COIL: + writeSingleCoil(channel, value.asBoolean()); + break; + case FC_15_WRITE_MULITPLE_COILS: + writeMultipleCoils(channel, util.getBitVectorFromByteArray(value)); + break; + case FC_06_WRITE_SINGLE_REGISTER: + writeSingleRegister(channel, new SimpleRegister(value.asShort())); + break; + case FC_16_WRITE_MULTIPLE_REGISTERS: + writeMultipleRegisters(channel, util.valueToRegisters(value, channel.getDatatype())); + break; + default: + throw new RuntimeException("FunctionCode " + channel.getFunctionCode().toString() + " not supported yet"); + } + } + + public void setChannelsWithErrorFlag(List containers) { + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(null, null, Flag.DRIVER_ERROR_CHANNEL_TEMPORARILY_NOT_ACCESSIBLE)); + } + } + + protected ModbusChannel getModbusChannel(String channelAddress, EAccess access) { + + ModbusChannel modbusChannel = null; + + // check if the channel object already exists in the list + if (modbusChannels.containsKey(channelAddress)) { + modbusChannel = modbusChannels.get(channelAddress); + + // if the channel object exists the access flag might has to be updated + // (this is case occurs when the channel is readable and writable) + if (!modbusChannel.getAccessFlag().equals(access)) { + modbusChannel.update(access); + } + } + // create a new channel object + else { + modbusChannel = new ModbusChannel(channelAddress, access); + modbusChannels.put(channelAddress, modbusChannel); + } + + return modbusChannel; + + } + + private synchronized BitVector readCoils(int startAddress, int count, int unitID) throws ModbusException { + readCoilsRequest.setReference(startAddress); + readCoilsRequest.setBitCount(count); + readCoilsRequest.setUnitID(unitID); + transaction.setRequest(readCoilsRequest); + transaction.execute(); + BitVector bitvector = ((ReadCoilsResponse) transaction.getResponse()).getCoils(); + bitvector.forceSize(count); + return bitvector; + + } + + public BitVector readCoils(ModbusChannel channel) throws ModbusException { + return readCoils(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); + } + + public BitVector readCoils(ModbusChannelGroup channelGroup) throws ModbusException { + return readCoils(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); + } + + private synchronized BitVector readDiscreteInputs(int startAddress, int count, int unitID) throws ModbusException { + readInputDiscretesRequest.setReference(startAddress); + readInputDiscretesRequest.setBitCount(count); + readInputDiscretesRequest.setUnitID(unitID); + transaction.setRequest(readInputDiscretesRequest); + transaction.execute(); + BitVector bitvector = ((ReadInputDiscretesResponse) transaction.getResponse()).getDiscretes(); + bitvector.forceSize(count); + return bitvector; + } + + public BitVector readDiscreteInputs(ModbusChannel channel) throws ModbusException { + return readDiscreteInputs(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); + } + + public BitVector readDiscreteInputs(ModbusChannelGroup channelGroup) throws ModbusException { + return readDiscreteInputs(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); + } + + private synchronized Register[] readHoldingRegisters(int startAddress, int count, int unitID) throws ModbusException { + readHoldingRegisterRequest.setReference(startAddress); + readHoldingRegisterRequest.setWordCount(count); + readHoldingRegisterRequest.setUnitID(unitID); + transaction.setRequest(readHoldingRegisterRequest); + transaction.execute(); + return ((ReadMultipleRegistersResponse) transaction.getResponse()).getRegisters(); + } + + public Register[] readHoldingRegisters(ModbusChannel channel) throws ModbusException { + return readHoldingRegisters(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); + } + + public Register[] readHoldingRegisters(ModbusChannelGroup channelGroup) throws ModbusException { + return readHoldingRegisters(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); + } + + /** + * Read InputRegisters + * + * @param startAddress + * @param count + * @param unitID + * @return the InputRegister[] + * @throws ModbusIOException + * @throws ModbusSlaveException + * @throws ModbusException + */ + private synchronized InputRegister[] readInputRegisters(int startAddress, int count, int unitID) throws ModbusIOException, + ModbusSlaveException, ModbusException { + readInputRegistersRequest.setReference(startAddress); + readInputRegistersRequest.setWordCount(count); + readInputRegistersRequest.setUnitID(unitID); + transaction.setRequest(readInputRegistersRequest); + transaction.execute(); + InputRegister[] registers = ((ReadInputRegistersResponse) transaction.getResponse()).getRegisters(); + return registers; + } + + /** + * Read InputRegisters for a channel + * + * @param channel + * @return the InputRegister + * @throws ModbusException + */ + public InputRegister[] readInputRegisters(ModbusChannel channel) throws ModbusException { + return readInputRegisters(channel.getStartAddress(), channel.getCount(), channel.getUnitId()); + } + + /** + * Read InputRegisters for a channelGroup + * + * @param channelGroup + * @return the InputRegister + * @throws ModbusException + */ + public InputRegister[] readInputRegisters(ModbusChannelGroup channelGroup) throws ModbusException { + return readInputRegisters(channelGroup.getStartAddress(), channelGroup.getCount(), channelGroup.getUnitId()); + } + + public synchronized void writeSingleCoil(ModbusChannel channel, boolean state) throws ModbusException { + writeCoilRequest.setReference(channel.getStartAddress()); + writeCoilRequest.setCoil(state); + writeCoilRequest.setUnitID(channel.getUnitId()); + transaction.setRequest(writeCoilRequest); + transaction.execute(); + } + + public synchronized void writeMultipleCoils(ModbusChannel channel, BitVector coils) throws ModbusException { + writeMultipleCoilsRequest.setReference(channel.getStartAddress()); + writeMultipleCoilsRequest.setCoils(coils); + writeMultipleCoilsRequest.setUnitID(channel.getUnitId()); + transaction.setRequest(writeMultipleCoilsRequest); + transaction.execute(); + } + + public synchronized void writeSingleRegister(ModbusChannel channel, Register register) throws ModbusException { + + writeSingleRegisterRequest.setReference(channel.getStartAddress()); + writeSingleRegisterRequest.setRegister(register); + writeSingleRegisterRequest.setUnitID(channel.getUnitId()); + transaction.setRequest(writeSingleRegisterRequest); + transaction.execute(); + } + + public synchronized void writeMultipleRegisters(ModbusChannel channel, Register[] registers) throws ModbusException { + writeMultipleRegistersRequest.setReference(channel.getStartAddress()); + writeMultipleRegistersRequest.setRegisters(registers); + writeMultipleRegistersRequest.setUnitID(channel.getUnitId()); + transaction.setRequest(writeMultipleRegistersRequest); + transaction.execute(); + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriver.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriver.java index c582969d..7b08df51 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriver.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriver.java @@ -40,59 +40,55 @@ */ public final class ModbusDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(ModbusDriver.class); + private final static Logger logger = LoggerFactory.getLogger(ModbusDriver.class); - private final static DriverInfo info = new DriverInfo("modbus", "ModbusTCP and ModbusRTU are supported.", "?", "?", - "?", "?"); + private final static DriverInfo info = new DriverInfo("modbus", "ModbusTCP and ModbusRTU are supported.", "?", "?", "?", "?"); - // TODO get it from channel.xml - private final static int timeoutInMillisecons = 10000; + // TODO get it from channel.xml + private final static int timeoutInMillisecons = 10000; - @Override - public DriverInfo getInfo() { - return info; - } + @Override + public DriverInfo getInfo() { + return info; + } - @Override - public Connection connect(String deviceAddress, String settings) throws ConnectionException { + @Override + public Connection connect(String deviceAddress, String settings) throws ConnectionException { - // TODO refactor exception handling in this method + // TODO refactor exception handling in this method - ModbusConnection connection; + ModbusConnection connection; - if (settings.equals("")) { - throw new ConnectionException("no device settings found in config. Please specify settings."); - } - else { - String[] settingsArray = settings.split(":"); - String mode = settingsArray[0]; - if (mode.equalsIgnoreCase("RTU")) { - try { - connection = new ModbusRTUConnection(deviceAddress, settingsArray, timeoutInMillisecons); - } catch (ModbusConfigurationException e) { - logger.error("Unable to create ModbusRTUConnection", e); - throw new ConnectionException(); - } - } - else if (mode.equalsIgnoreCase("TCP")) { - connection = new ModbusTCPConnection(deviceAddress, timeoutInMillisecons); - } - else { - throw new ConnectionException("Unknown Mode. Use RTU or TCP."); - } - } - return connection; - } + if (settings.equals("")) { + throw new ConnectionException("no device settings found in config. Please specify settings."); + } else { + String[] settingsArray = settings.split(":"); + String mode = settingsArray[0]; + if (mode.equalsIgnoreCase("RTU")) { + try { + connection = new ModbusRTUConnection(deviceAddress, settingsArray, timeoutInMillisecons); + } catch (ModbusConfigurationException e) { + logger.error("Unable to create ModbusRTUConnection", e); + throw new ConnectionException(); + } + } else if (mode.equalsIgnoreCase("TCP")) { + connection = new ModbusTCPConnection(deviceAddress, timeoutInMillisecons); + } else { + throw new ConnectionException("Unknown Mode. Use RTU or TCP."); + } + } + return connection; + } - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - } + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + } - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriverUtil.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriverUtil.java index d99dc743..b5050548 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriverUtil.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/ModbusDriverUtil.java @@ -25,146 +25,136 @@ import net.wimpi.modbus.procimg.SimpleRegister; import net.wimpi.modbus.util.BitVector; import net.wimpi.modbus.util.ModbusUtil; - -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.Value; +import org.openmuc.framework.data.*; public class ModbusDriverUtil { - public Value getBitVectorsValue(BitVector bitVector) { - - Value readValue; - if (bitVector.size() == 1) { - - readValue = new BooleanValue(bitVector.getBit(0)); // read single bit - } - else { - readValue = new ByteArrayValue(bitVector.getBytes()); // read multiple bits - } - return readValue; - } - - public BitVector getBitVectorFromByteArray(Value value) { - BitVector bv = new BitVector(value.asByteArray().length * 8); - bv.setBytes(value.asByteArray()); - return bv; - } - - /** - * Converts the registers into the datatyp of the channel - * - * @param registers - * @param datatype - * @return the corresponding Value Object - */ - public Value getRegistersValue(InputRegister[] registers, EDatatype datatype) { - Value registerValue = null; - byte[] registerAsByteArray = inputRegisterToByteArray(registers); - - switch (datatype) { - case SHORT: - registerValue = new ShortValue(ModbusUtil.registerToShort(registerAsByteArray)); - break; - case INT: - registerValue = new IntValue(ModbusUtil.registersToInt(registerAsByteArray)); - break; - case FLOAT: - registerValue = new FloatValue(ModbusUtil.registersToFloat(registerAsByteArray)); - break; - case DOUBLE: - registerValue = new DoubleValue(ModbusUtil.registersToDouble(registerAsByteArray)); - break; - case LONG: - registerValue = new LongValue(ModbusUtil.registersToLong(registerAsByteArray)); - break; - case BYTEARRAY: - registerValue = new ByteArrayValue(registerAsByteArray); - break; - case BYTE_HIGH: - registerValue = new IntValue(registerAsByteArray[1] & 0xFF); - break; - case BYTE_LOW: - registerValue = new IntValue(registerAsByteArray[0] & 0xFF); - break; - default: - throw new RuntimeException("Datatype " + datatype.toString() + " not supported yet"); - } - return registerValue; - } - - public Register[] valueToRegisters(Value value, EDatatype datatype) { - - Register[] registers; - - switch (datatype) { - - case SHORT: - registers = byteArrayToRegister(ModbusUtil.shortToRegister(value.asShort())); - break; - case INT: - registers = byteArrayToRegister(ModbusUtil.intToRegisters(value.asInt())); - break; - case DOUBLE: - registers = byteArrayToRegister(ModbusUtil.doubleToRegisters(value.asDouble())); - break; - case FLOAT: - registers = byteArrayToRegister(ModbusUtil.floatToRegisters(value.asFloat())); - break; - case LONG: - registers = byteArrayToRegister(ModbusUtil.longToRegisters(value.asLong())); - break; - case BYTEARRAY: - registers = byteArrayToRegister(value.asByteArray()); - break; - case BYTE_HIGH: - case BYTE_LOW: - default: - throw new RuntimeException("Datatype " + datatype.toString() + " not supported yet"); - } - - return registers; - } - - /** - * Converts an array of input registers into a byte array - * - * @param inputRegister - * @return the InputRegister[] as byte[] - */ - private byte[] inputRegisterToByteArray(InputRegister[] inputRegister) { - byte[] registerAsBytes = new byte[inputRegister.length * 2]; // one register = 2 bytes - for (int i = 0; i < inputRegister.length; i++) { - System.arraycopy(inputRegister[i].toBytes(), 0, registerAsBytes, i * inputRegister[0].toBytes().length, - inputRegister[i].toBytes().length); - } - return registerAsBytes; - } - - // TODO check byte order e.g. is an Integer! - // TODO only works for even byteArray.length! - private Register[] byteArrayToRegister(byte[] byteArray) throws RuntimeException { - - // TODO byteArray might has a odd number of bytes... - SimpleRegister[] register; - - if (byteArray.length % 2 == 0) { - register = new SimpleRegister[byteArray.length / 2]; - int j = 0; - // for (int i = 0; i < byteArray.length; i++) { - for (int i = 0; i < byteArray.length / 2; i++) { - register[i] = new SimpleRegister(byteArray[j], byteArray[j + 1]); - j = j + 2; - } - } - else { - throw new RuntimeException("conversion vom byteArray to Register is not working for odd number of bytes"); - } - return register; - } + public Value getBitVectorsValue(BitVector bitVector) { + + Value readValue; + if (bitVector.size() == 1) { + + readValue = new BooleanValue(bitVector.getBit(0)); // read single bit + } else { + readValue = new ByteArrayValue(bitVector.getBytes()); // read multiple bits + } + return readValue; + } + + public BitVector getBitVectorFromByteArray(Value value) { + BitVector bv = new BitVector(value.asByteArray().length * 8); + bv.setBytes(value.asByteArray()); + return bv; + } + + /** + * Converts the registers into the datatyp of the channel + * + * @param registers + * @param datatype + * @return the corresponding Value Object + */ + public Value getRegistersValue(InputRegister[] registers, EDatatype datatype) { + Value registerValue = null; + byte[] registerAsByteArray = inputRegisterToByteArray(registers); + + switch (datatype) { + case SHORT: + registerValue = new ShortValue(ModbusUtil.registerToShort(registerAsByteArray)); + break; + case INT: + registerValue = new IntValue(ModbusUtil.registersToInt(registerAsByteArray)); + break; + case FLOAT: + registerValue = new FloatValue(ModbusUtil.registersToFloat(registerAsByteArray)); + break; + case DOUBLE: + registerValue = new DoubleValue(ModbusUtil.registersToDouble(registerAsByteArray)); + break; + case LONG: + registerValue = new LongValue(ModbusUtil.registersToLong(registerAsByteArray)); + break; + case BYTEARRAY: + registerValue = new ByteArrayValue(registerAsByteArray); + break; + case BYTE_HIGH: + registerValue = new IntValue(registerAsByteArray[1] & 0xFF); + break; + case BYTE_LOW: + registerValue = new IntValue(registerAsByteArray[0] & 0xFF); + break; + default: + throw new RuntimeException("Datatype " + datatype.toString() + " not supported yet"); + } + return registerValue; + } + + public Register[] valueToRegisters(Value value, EDatatype datatype) { + + Register[] registers; + + switch (datatype) { + + case SHORT: + registers = byteArrayToRegister(ModbusUtil.shortToRegister(value.asShort())); + break; + case INT: + registers = byteArrayToRegister(ModbusUtil.intToRegisters(value.asInt())); + break; + case DOUBLE: + registers = byteArrayToRegister(ModbusUtil.doubleToRegisters(value.asDouble())); + break; + case FLOAT: + registers = byteArrayToRegister(ModbusUtil.floatToRegisters(value.asFloat())); + break; + case LONG: + registers = byteArrayToRegister(ModbusUtil.longToRegisters(value.asLong())); + break; + case BYTEARRAY: + registers = byteArrayToRegister(value.asByteArray()); + break; + case BYTE_HIGH: + case BYTE_LOW: + default: + throw new RuntimeException("Datatype " + datatype.toString() + " not supported yet"); + } + + return registers; + } + + /** + * Converts an array of input registers into a byte array + * + * @param inputRegister + * @return the InputRegister[] as byte[] + */ + private byte[] inputRegisterToByteArray(InputRegister[] inputRegister) { + byte[] registerAsBytes = new byte[inputRegister.length * 2]; // one register = 2 bytes + for (int i = 0; i < inputRegister.length; i++) { + System.arraycopy(inputRegister[i].toBytes(), 0, registerAsBytes, i * inputRegister[0].toBytes().length, + inputRegister[i].toBytes().length); + } + return registerAsBytes; + } + + // TODO check byte order e.g. is an Integer! + // TODO only works for even byteArray.length! + private Register[] byteArrayToRegister(byte[] byteArray) throws RuntimeException { + + // TODO byteArray might has a odd number of bytes... + SimpleRegister[] register; + + if (byteArray.length % 2 == 0) { + register = new SimpleRegister[byteArray.length / 2]; + int j = 0; + // for (int i = 0; i < byteArray.length; i++) { + for (int i = 0; i < byteArray.length / 2; i++) { + register[i] = new SimpleRegister(byteArray[j], byteArray[j + 1]); + j = j + 2; + } + } else { + throw new RuntimeException("conversion vom byteArray to Register is not working for odd number of bytes"); + } + return register; + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusConfigurationException.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusConfigurationException.java index 99e8c3e9..2b74850a 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusConfigurationException.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusConfigurationException.java @@ -22,15 +22,15 @@ public class ModbusConfigurationException extends Exception { - private final String message; + private final String message; - public ModbusConfigurationException(String message) { - this.message = message; - } + public ModbusConfigurationException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusRTUConnection.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusRTUConnection.java index 37afb635..e39216e3 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusRTUConnection.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/rtu/ModbusRTUConnection.java @@ -22,16 +22,11 @@ import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; - -import java.util.Enumeration; -import java.util.List; - import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusException; import net.wimpi.modbus.io.ModbusSerialTransaction; import net.wimpi.modbus.net.SerialConnection; import net.wimpi.modbus.util.SerialParameters; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.config.ScanException; @@ -48,317 +43,289 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Enumeration; +import java.util.List; + /** - * * TODO - * */ public class ModbusRTUConnection extends ModbusConnection { - private final static Logger logger = LoggerFactory.getLogger(ModbusRTUConnection.class); - - private static final int ENCODING = 1; - private static final int BAUDRATE = 2; - private static final int DATABITS = 3; - private static final int PARITY = 4; - private static final int STOPBITS = 5; - private static final int ECHO = 6; - private static final int FLOWCONTROL_IN = 7; - private static final int FLOWCONTEOL_OUT = 8; - - private static final String SERIAL_ENCODING_RTU = "SERIAL_ENCODING_RTU"; - - private static final String ECHO_TRUE = "ECHO_TRUE"; - private static final String ECHO_FALSE = "ECHO_FALSE"; - - private final SerialConnection connection; - private ModbusSerialTransaction transaction; - - public ModbusRTUConnection(String deviceAddress, String[] settings, int timeout) - throws ModbusConfigurationException { - - super(); - - SerialParameters params = setParameters(deviceAddress, settings, timeout); - connection = new SerialConnection(params); - - try { - connect(); - transaction = new ModbusSerialTransaction(connection); - transaction.setSerialConnection(connection); - setTransaction(transaction); - - } catch (Exception e) { - e.printStackTrace(); - throw new ModbusConfigurationException("Wrong Modbus RTU configuration. Check configuration file"); - } - logger.info("Modbus Device: " + deviceAddress + " connected"); - } - - @Override - public void connect() throws Exception { - if (!connection.isOpen()) { - connection.open(); - } - } - - @Override - public void disconnect() { - if (connection.isOpen()) { - connection.close(); - } - } - - public void setReceiveTimeout(int timeout) { - connection.setReceiveTimeout(timeout); - } - - private SerialParameters setParameters(String address, String[] settings, int timeout) - throws ModbusConfigurationException { - - SerialParameters params = new SerialParameters(); - - checkIfAddressIsAvailbale(address); - params.setPortName(address); - - if (settings.length == 9) { - setEncoding(params, settings[ENCODING]); - setBaudrate(params, settings[BAUDRATE]); - setDatabits(params, settings[DATABITS]); - setParity(params, settings[PARITY]); - setStopbits(params, settings[STOPBITS]); - setEcho(params, settings[ECHO]); - setFlowControlIn(params, settings[FLOWCONTROL_IN]); - setFlowControlOut(params, settings[FLOWCONTEOL_OUT]); - } - else { - throw new ModbusConfigurationException("Settings parameter missing. Specify all settings parameter"); - } - - return params; - } - - /** - * Checks if the gnu.io.rxtx is able to find the specified address e.g. /dev/ttyUSB0 - * - * @param address - * @throws ModbusConfigurationException - */ - private void checkIfAddressIsAvailbale(String address) throws ModbusConfigurationException { - Enumeration ports = CommPortIdentifier.getPortIdentifiers(); - - boolean result = false; - - while (ports.hasMoreElements()) { - CommPortIdentifier cpi = (CommPortIdentifier) ports.nextElement(); - if (cpi.getName().equalsIgnoreCase(address)) { - result = true; - break; - } - } - - if (!result) { - String availablePorts = getAvailablePorts(); - throw new ModbusConfigurationException("gnu.io.rxtx is unable to detect address: " + address - + ". Available addresses are: '" + availablePorts + "'"); - } - } - - private String getAvailablePorts() { - - String availablePorts = ""; - - Enumeration ports = CommPortIdentifier.getPortIdentifiers(); - while (ports.hasMoreElements()) { - CommPortIdentifier cpi = (CommPortIdentifier) ports.nextElement(); - availablePorts += cpi.getName() + "; "; - } - - return availablePorts; - } - - private void setFlowControlIn(SerialParameters params, String flowControlIn) throws ModbusConfigurationException { - if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_NONE")) { - params.setFlowControlIn(SerialPort.FLOWCONTROL_NONE); - } - else if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_RTSCTS_IN")) { - params.setFlowControlIn(SerialPort.FLOWCONTROL_RTSCTS_IN); - } - else if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_XONXOFF_IN")) { - params.setFlowControlIn(SerialPort.FLOWCONTROL_XONXOFF_IN); - } - else { - throw new ModbusConfigurationException("Unknown flow control in setting. Check configuration file"); - } - - } - - private void setFlowControlOut(SerialParameters params, String flowControlOut) throws ModbusConfigurationException { - if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_NONE")) { - params.setFlowControlOut(SerialPort.FLOWCONTROL_NONE); - } - else if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_RTSCTS_OUT")) { - params.setFlowControlOut(SerialPort.FLOWCONTROL_RTSCTS_OUT); - } - else if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_XONXOFF_OUT")) { - params.setFlowControlOut(SerialPort.FLOWCONTROL_XONXOFF_OUT); - } - else { - throw new ModbusConfigurationException("Unknown flow control out setting. Check configuration file"); - } - - } - - private void setEcho(SerialParameters params, String echo) throws ModbusConfigurationException { - if (echo.equalsIgnoreCase(ECHO_TRUE)) { - params.setEcho(true); - } - else if (echo.equalsIgnoreCase(ECHO_FALSE)) { - params.setEcho(false); - } - else { - throw new ModbusConfigurationException("Unknown echo setting. Check configuration file"); - } - - } - - private void setStopbits(SerialParameters params, String stopbits) throws ModbusConfigurationException { - if (stopbits.equalsIgnoreCase("STOPBITS_1")) { - params.setStopbits(SerialPort.STOPBITS_1); - } - else if (stopbits.equalsIgnoreCase("STOPBITS_1_5")) { - params.setStopbits(SerialPort.STOPBITS_1_5); - } - else if (stopbits.equalsIgnoreCase("STOPBITS_2")) { - params.setStopbits(SerialPort.STOPBITS_2); - } - else { - throw new ModbusConfigurationException("Unknown stobit setting. Check configuration file"); - } - - } - - private void setParity(SerialParameters params, String parity) throws ModbusConfigurationException { - if (parity.equalsIgnoreCase("PARITY_EVEN")) { - params.setParity(SerialPort.PARITY_EVEN); - } - else if (parity.equalsIgnoreCase("PARITY_MARK")) { - params.setParity(SerialPort.PARITY_MARK); - } - else if (parity.equalsIgnoreCase("PARITY_NONE")) { - params.setParity(SerialPort.PARITY_NONE); - } - else if (parity.equalsIgnoreCase("PARITY_ODD")) { - params.setParity(SerialPort.PARITY_ODD); - } - else if (parity.equalsIgnoreCase("PARITY_SPACE")) { - params.setParity(SerialPort.PARITY_SPACE); - } - else { - throw new ModbusConfigurationException("Unknown parity setting. Check configuration file"); - } - - } - - private void setDatabits(SerialParameters params, String databits) throws ModbusConfigurationException { - if (databits.equalsIgnoreCase("DATABITS_5")) { - params.setDatabits(SerialPort.DATABITS_5); - } - else if (databits.equalsIgnoreCase("DATABITS_6")) { - params.setDatabits(SerialPort.DATABITS_6); - } - else if (databits.equalsIgnoreCase("DATABITS_7")) { - params.setDatabits(SerialPort.DATABITS_7); - } - else if (databits.equalsIgnoreCase("DATABITS_8")) { - params.setDatabits(SerialPort.DATABITS_8); - } - else { - throw new ModbusConfigurationException("Unknown databit setting. Check configuration file"); - } - } - - private void setBaudrate(SerialParameters params, String baudrate) { - params.setBaudRate(baudrate); - } - - private void setEncoding(SerialParameters params, String encoding) throws ModbusConfigurationException { - if (encoding.equalsIgnoreCase(SERIAL_ENCODING_RTU)) { - params.setEncoding(Modbus.SERIAL_ENCODING_RTU); - } - else { - throw new ModbusConfigurationException("Unknown encoding setting. Check configuration file"); - } - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelRecordContainer container : containers) { - long receiveTime = System.currentTimeMillis(); - ModbusChannel channel = getModbusChannel(container.getChannelAddress(), EAccess.READ); - Value value; - try { - value = readChannel(channel); - - logger.debug("{}: value = '{}'", channel.getChannelAddress(), value.toString()); - - container.setRecord(new Record(value, receiveTime)); - } catch (ModbusException e) { - e.printStackTrace(); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); - } - } - - // logger.debug("### readChannels duration in ms = " + ((new Date().getTime()) - startTime)); - - return null; - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - for (ChannelValueContainer container : containers) { - - ModbusChannel modbusChannel = getModbusChannel(container.getChannelAddress(), EAccess.WRITE); - if (modbusChannel != null) { - try { - writeChannel(modbusChannel, container.getValue()); - container.setFlag(Flag.VALID); - } catch (ModbusException modbusException) { - container.setFlag(Flag.UNKNOWN_ERROR); - modbusException.printStackTrace(); - throw new ConnectionException("Unable to write data on channel address: " - + container.getChannelAddress()); - } catch (Exception e) { - container.setFlag(Flag.UNKNOWN_ERROR); - e.printStackTrace(); - logger.error("Unable to write data on channel address: " + container.getChannelAddress()); - } - } - else { - // TODO - container.setFlag(Flag.UNKNOWN_ERROR); - logger.error("Unable to write data on channel address: " + container.getChannelAddress() - + "modbusChannel = null"); - } - } - - return null; - - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ArgumentSyntaxException, ScanException, ConnectionException { - throw new UnsupportedOperationException(); - } + private final static Logger logger = LoggerFactory.getLogger(ModbusRTUConnection.class); + + private static final int ENCODING = 1; + private static final int BAUDRATE = 2; + private static final int DATABITS = 3; + private static final int PARITY = 4; + private static final int STOPBITS = 5; + private static final int ECHO = 6; + private static final int FLOWCONTROL_IN = 7; + private static final int FLOWCONTEOL_OUT = 8; + + private static final String SERIAL_ENCODING_RTU = "SERIAL_ENCODING_RTU"; + + private static final String ECHO_TRUE = "ECHO_TRUE"; + private static final String ECHO_FALSE = "ECHO_FALSE"; + + private final SerialConnection connection; + private ModbusSerialTransaction transaction; + + public ModbusRTUConnection(String deviceAddress, String[] settings, int timeout) throws ModbusConfigurationException { + + super(); + + SerialParameters params = setParameters(deviceAddress, settings, timeout); + connection = new SerialConnection(params); + + try { + connect(); + transaction = new ModbusSerialTransaction(connection); + transaction.setSerialConnection(connection); + setTransaction(transaction); + + } catch (Exception e) { + e.printStackTrace(); + throw new ModbusConfigurationException("Wrong Modbus RTU configuration. Check configuration file"); + } + logger.info("Modbus Device: " + deviceAddress + " connected"); + } + + @Override + public void connect() throws Exception { + if (!connection.isOpen()) { + connection.open(); + } + } + + @Override + public void disconnect() { + if (connection.isOpen()) { + connection.close(); + } + } + + public void setReceiveTimeout(int timeout) { + connection.setReceiveTimeout(timeout); + } + + private SerialParameters setParameters(String address, String[] settings, int timeout) throws ModbusConfigurationException { + + SerialParameters params = new SerialParameters(); + + checkIfAddressIsAvailbale(address); + params.setPortName(address); + + if (settings.length == 9) { + setEncoding(params, settings[ENCODING]); + setBaudrate(params, settings[BAUDRATE]); + setDatabits(params, settings[DATABITS]); + setParity(params, settings[PARITY]); + setStopbits(params, settings[STOPBITS]); + setEcho(params, settings[ECHO]); + setFlowControlIn(params, settings[FLOWCONTROL_IN]); + setFlowControlOut(params, settings[FLOWCONTEOL_OUT]); + } else { + throw new ModbusConfigurationException("Settings parameter missing. Specify all settings parameter"); + } + + return params; + } + + /** + * Checks if the gnu.io.rxtx is able to find the specified address e.g. /dev/ttyUSB0 + * + * @param address + * @throws ModbusConfigurationException + */ + private void checkIfAddressIsAvailbale(String address) throws ModbusConfigurationException { + Enumeration ports = CommPortIdentifier.getPortIdentifiers(); + + boolean result = false; + + while (ports.hasMoreElements()) { + CommPortIdentifier cpi = (CommPortIdentifier) ports.nextElement(); + if (cpi.getName().equalsIgnoreCase(address)) { + result = true; + break; + } + } + + if (!result) { + String availablePorts = getAvailablePorts(); + throw new ModbusConfigurationException( + "gnu.io.rxtx is unable to detect address: " + address + ". Available addresses are: '" + availablePorts + "'"); + } + } + + private String getAvailablePorts() { + + String availablePorts = ""; + + Enumeration ports = CommPortIdentifier.getPortIdentifiers(); + while (ports.hasMoreElements()) { + CommPortIdentifier cpi = (CommPortIdentifier) ports.nextElement(); + availablePorts += cpi.getName() + "; "; + } + + return availablePorts; + } + + private void setFlowControlIn(SerialParameters params, String flowControlIn) throws ModbusConfigurationException { + if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_NONE")) { + params.setFlowControlIn(SerialPort.FLOWCONTROL_NONE); + } else if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_RTSCTS_IN")) { + params.setFlowControlIn(SerialPort.FLOWCONTROL_RTSCTS_IN); + } else if (flowControlIn.equalsIgnoreCase("FLOWCONTROL_XONXOFF_IN")) { + params.setFlowControlIn(SerialPort.FLOWCONTROL_XONXOFF_IN); + } else { + throw new ModbusConfigurationException("Unknown flow control in setting. Check configuration file"); + } + + } + + private void setFlowControlOut(SerialParameters params, String flowControlOut) throws ModbusConfigurationException { + if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_NONE")) { + params.setFlowControlOut(SerialPort.FLOWCONTROL_NONE); + } else if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_RTSCTS_OUT")) { + params.setFlowControlOut(SerialPort.FLOWCONTROL_RTSCTS_OUT); + } else if (flowControlOut.equalsIgnoreCase("FLOWCONTROL_XONXOFF_OUT")) { + params.setFlowControlOut(SerialPort.FLOWCONTROL_XONXOFF_OUT); + } else { + throw new ModbusConfigurationException("Unknown flow control out setting. Check configuration file"); + } + + } + + private void setEcho(SerialParameters params, String echo) throws ModbusConfigurationException { + if (echo.equalsIgnoreCase(ECHO_TRUE)) { + params.setEcho(true); + } else if (echo.equalsIgnoreCase(ECHO_FALSE)) { + params.setEcho(false); + } else { + throw new ModbusConfigurationException("Unknown echo setting. Check configuration file"); + } + + } + + private void setStopbits(SerialParameters params, String stopbits) throws ModbusConfigurationException { + if (stopbits.equalsIgnoreCase("STOPBITS_1")) { + params.setStopbits(SerialPort.STOPBITS_1); + } else if (stopbits.equalsIgnoreCase("STOPBITS_1_5")) { + params.setStopbits(SerialPort.STOPBITS_1_5); + } else if (stopbits.equalsIgnoreCase("STOPBITS_2")) { + params.setStopbits(SerialPort.STOPBITS_2); + } else { + throw new ModbusConfigurationException("Unknown stobit setting. Check configuration file"); + } + + } + + private void setParity(SerialParameters params, String parity) throws ModbusConfigurationException { + if (parity.equalsIgnoreCase("PARITY_EVEN")) { + params.setParity(SerialPort.PARITY_EVEN); + } else if (parity.equalsIgnoreCase("PARITY_MARK")) { + params.setParity(SerialPort.PARITY_MARK); + } else if (parity.equalsIgnoreCase("PARITY_NONE")) { + params.setParity(SerialPort.PARITY_NONE); + } else if (parity.equalsIgnoreCase("PARITY_ODD")) { + params.setParity(SerialPort.PARITY_ODD); + } else if (parity.equalsIgnoreCase("PARITY_SPACE")) { + params.setParity(SerialPort.PARITY_SPACE); + } else { + throw new ModbusConfigurationException("Unknown parity setting. Check configuration file"); + } + + } + + private void setDatabits(SerialParameters params, String databits) throws ModbusConfigurationException { + if (databits.equalsIgnoreCase("DATABITS_5")) { + params.setDatabits(SerialPort.DATABITS_5); + } else if (databits.equalsIgnoreCase("DATABITS_6")) { + params.setDatabits(SerialPort.DATABITS_6); + } else if (databits.equalsIgnoreCase("DATABITS_7")) { + params.setDatabits(SerialPort.DATABITS_7); + } else if (databits.equalsIgnoreCase("DATABITS_8")) { + params.setDatabits(SerialPort.DATABITS_8); + } else { + throw new ModbusConfigurationException("Unknown databit setting. Check configuration file"); + } + } + + private void setBaudrate(SerialParameters params, String baudrate) { + params.setBaudRate(baudrate); + } + + private void setEncoding(SerialParameters params, String encoding) throws ModbusConfigurationException { + if (encoding.equalsIgnoreCase(SERIAL_ENCODING_RTU)) { + params.setEncoding(Modbus.SERIAL_ENCODING_RTU); + } else { + throw new ModbusConfigurationException("Unknown encoding setting. Check configuration file"); + } + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + for (ChannelRecordContainer container : containers) { + long receiveTime = System.currentTimeMillis(); + ModbusChannel channel = getModbusChannel(container.getChannelAddress(), EAccess.READ); + Value value; + try { + value = readChannel(channel); + + logger.debug("{}: value = '{}'", channel.getChannelAddress(), value.toString()); + + container.setRecord(new Record(value, receiveTime)); + } catch (ModbusException e) { + e.printStackTrace(); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); + } + } + + // logger.debug("### readChannels duration in ms = " + ((new Date().getTime()) - startTime)); + + return null; + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + for (ChannelValueContainer container : containers) { + + ModbusChannel modbusChannel = getModbusChannel(container.getChannelAddress(), EAccess.WRITE); + if (modbusChannel != null) { + try { + writeChannel(modbusChannel, container.getValue()); + container.setFlag(Flag.VALID); + } catch (ModbusException modbusException) { + container.setFlag(Flag.UNKNOWN_ERROR); + modbusException.printStackTrace(); + throw new ConnectionException("Unable to write data on channel address: " + container.getChannelAddress()); + } catch (Exception e) { + container.setFlag(Flag.UNKNOWN_ERROR); + e.printStackTrace(); + logger.error("Unable to write data on channel address: " + container.getChannelAddress()); + } + } else { + // TODO + container.setFlag(Flag.UNKNOWN_ERROR); + logger.error("Unable to write data on channel address: " + container.getChannelAddress() + "modbusChannel = null"); + } + } + + return null; + + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ConnectionException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPConnection.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPConnection.java index 59122f56..a0a48092 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPConnection.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPConnection.java @@ -20,16 +20,10 @@ */ package org.openmuc.framework.driver.modbus.tcp; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - import net.wimpi.modbus.ModbusException; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.io.ModbusTCPTransaction; import net.wimpi.modbus.net.TCPMasterConnection; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.config.ScanException; @@ -47,196 +41,195 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; + /** * TODO */ public class ModbusTCPConnection extends ModbusConnection { - private final static Logger logger = LoggerFactory.getLogger(ModbusTCPConnection.class); - - private TCPMasterConnection connection; - private ModbusTCPTransaction transaction; - - public ModbusTCPConnection(String deviceAddress, int timeoutInSeconds) { - - super(); - ModbusTCPDeviceAddress address = new ModbusTCPDeviceAddress(deviceAddress); - try { - connection = new TCPMasterConnection(InetAddress.getByName(address.getIp())); - connection.setPort(address.getPort()); - // connection.setTimeout(timeoutInSeconds); - connect(); - } catch (UnknownHostException e) { - throw new RuntimeException(e.getMessage()); - } catch (Exception e) { - throw new RuntimeException(e.getMessage()); - } - logger.info("Modbus Device: " + deviceAddress + " connected"); - } - - @Override - public void connect() throws Exception { - - if (connection != null && !connection.isConnected()) { - connection.connect(); - transaction = new ModbusTCPTransaction(connection); - setTransaction(transaction); - if (!connection.isConnected()) { - throw new Exception("unable to connect"); - } - } - } - - @Override - public void disconnect() { - logger.info("Disconnect Modbus TCP device"); - if (connection != null && connection.isConnected()) { - connection.close(); - transaction = null; - } - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - // reads channels one by one - if (samplingGroup.isEmpty()) { - for (ChannelRecordContainer container : containers) { - long receiveTime = System.currentTimeMillis(); - ModbusChannel channel = getModbusChannel(container.getChannelAddress(), EAccess.READ); - Value value; - try { - value = readChannel(channel); - // logger.debug("{}: value = '{}'", channel.getChannelAddress(), value.toString()); - container.setRecord(new Record(value, receiveTime)); - } catch (ModbusIOException e) { - logger.error("Unable to read channel: " + container.getChannelAddress(), e); - disconnect(); - throw new ConnectionException("Try to reconnect to solve ModbusIOException"); - } catch (ModbusException e) { - logger.error("Unable to read channel: " + container.getChannelAddress(), e); - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); - } - } - } - // reads whole samplingGroup at once - else { - // TODO test channel group - logger.warn("Reading samplingGroup is not tested yet!"); - readChannelGroupHighLevel(containers, containerListHandle, samplingGroup); - } - - return null; - } - - private Object readChannelGroupHighLevel(List containers, Object containerListHandle, - String samplingGroup) { - - // NOTE: containerListHandle is null if something changed in configuration!!! - - ModbusChannelGroup channelGroup = null; - - // use existing channelGroup - if (containerListHandle != null) { - if (containerListHandle instanceof ModbusChannelGroup) { - channelGroup = (ModbusChannelGroup) containerListHandle; - } - } - - // create new channelGroup - if (channelGroup == null) { - ArrayList channelList = new ArrayList(); - for (ChannelRecordContainer container : containers) { - channelList.add(getModbusChannel(container.getChannelAddress(), EAccess.READ)); - } - channelGroup = new ModbusChannelGroup(samplingGroup, channelList); - } - - // read all channels of the group - try { - readChannelGroup(channelGroup, containers); - - } catch (ModbusException e) { - e.printStackTrace(); - - // set channel values and flag, otherwise the datamanager will throw a null pointer exception - // and the framework collapses. - setChannelsWithErrorFlag(containers); - } - - // logger.debug("### readChannelGroup duration in ms = " + ((new Date().getTime()) - startTime)); - - return channelGroup; - } - - // private ModbusChannel getModbusChannel(String channelAddress, EAccess access) { - // - // ModbusChannel modbusChannel = null; - // - // // check if the channel object already exists in the list - // if (modbusChannels.containsKey(channelAddress)) { - // modbusChannel = modbusChannels.get(channelAddress); - // - // // if the channel object exists the access flag might has to be updated - // // (this is case occurs when the channel is readable and writable) - // if (!modbusChannel.getAccessFlag().equals(access)) { - // modbusChannel.update(access); - // } - // } - // // create a new channel object - // else { - // modbusChannel = new ModbusChannel(channelAddress, access); - // modbusChannels.put(channelAddress, modbusChannel); - // } - // - // return modbusChannel; - // - // } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelValueContainer container : containers) { - - ModbusChannel modbusChannel = getModbusChannel(container.getChannelAddress(), EAccess.WRITE); - if (modbusChannel != null) { - try { - writeChannel(modbusChannel, container.getValue()); - container.setFlag(Flag.VALID); - } catch (ModbusException modbusException) { - container.setFlag(Flag.UNKNOWN_ERROR); - modbusException.printStackTrace(); - throw new ConnectionException("Unable to write data on channel address: " - + container.getChannelAddress()); - } catch (Exception e) { - container.setFlag(Flag.UNKNOWN_ERROR); - e.printStackTrace(); - logger.error("Unable to write data on channel address: " + container.getChannelAddress()); - } - } - else { - // TODO - container.setFlag(Flag.UNKNOWN_ERROR); - logger.error("Unable to write data on channel address: " + container.getChannelAddress() - + "modbusChannel = null"); - } - } - - return null; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ArgumentSyntaxException, ScanException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } + private final static Logger logger = LoggerFactory.getLogger(ModbusTCPConnection.class); + + private TCPMasterConnection connection; + private ModbusTCPTransaction transaction; + + public ModbusTCPConnection(String deviceAddress, int timeoutInSeconds) { + + super(); + ModbusTCPDeviceAddress address = new ModbusTCPDeviceAddress(deviceAddress); + try { + connection = new TCPMasterConnection(InetAddress.getByName(address.getIp())); + connection.setPort(address.getPort()); + // connection.setTimeout(timeoutInSeconds); + connect(); + } catch (UnknownHostException e) { + throw new RuntimeException(e.getMessage()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + logger.info("Modbus Device: " + deviceAddress + " connected"); + } + + @Override + public void connect() throws Exception { + + if (connection != null && !connection.isConnected()) { + connection.connect(); + transaction = new ModbusTCPTransaction(connection); + setTransaction(transaction); + if (!connection.isConnected()) { + throw new Exception("unable to connect"); + } + } + } + + @Override + public void disconnect() { + logger.info("Disconnect Modbus TCP device"); + if (connection != null && connection.isConnected()) { + connection.close(); + transaction = null; + } + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + // reads channels one by one + if (samplingGroup.isEmpty()) { + for (ChannelRecordContainer container : containers) { + long receiveTime = System.currentTimeMillis(); + ModbusChannel channel = getModbusChannel(container.getChannelAddress(), EAccess.READ); + Value value; + try { + value = readChannel(channel); + // logger.debug("{}: value = '{}'", channel.getChannelAddress(), value.toString()); + container.setRecord(new Record(value, receiveTime)); + } catch (ModbusIOException e) { + logger.error("Unable to read channel: " + container.getChannelAddress(), e); + disconnect(); + throw new ConnectionException("Try to reconnect to solve ModbusIOException"); + } catch (ModbusException e) { + logger.error("Unable to read channel: " + container.getChannelAddress(), e); + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_NOT_ACCESSIBLE)); + } + } + } + // reads whole samplingGroup at once + else { + // TODO test channel group + logger.warn("Reading samplingGroup is not tested yet!"); + readChannelGroupHighLevel(containers, containerListHandle, samplingGroup); + } + + return null; + } + + private Object readChannelGroupHighLevel(List containers, Object containerListHandle, String samplingGroup) { + + // NOTE: containerListHandle is null if something changed in configuration!!! + + ModbusChannelGroup channelGroup = null; + + // use existing channelGroup + if (containerListHandle != null) { + if (containerListHandle instanceof ModbusChannelGroup) { + channelGroup = (ModbusChannelGroup) containerListHandle; + } + } + + // create new channelGroup + if (channelGroup == null) { + ArrayList channelList = new ArrayList(); + for (ChannelRecordContainer container : containers) { + channelList.add(getModbusChannel(container.getChannelAddress(), EAccess.READ)); + } + channelGroup = new ModbusChannelGroup(samplingGroup, channelList); + } + + // read all channels of the group + try { + readChannelGroup(channelGroup, containers); + + } catch (ModbusException e) { + e.printStackTrace(); + + // set channel values and flag, otherwise the datamanager will throw a null pointer exception + // and the framework collapses. + setChannelsWithErrorFlag(containers); + } + + // logger.debug("### readChannelGroup duration in ms = " + ((new Date().getTime()) - startTime)); + + return channelGroup; + } + + // private ModbusChannel getModbusChannel(String channelAddress, EAccess access) { + // + // ModbusChannel modbusChannel = null; + // + // // check if the channel object already exists in the list + // if (modbusChannels.containsKey(channelAddress)) { + // modbusChannel = modbusChannels.get(channelAddress); + // + // // if the channel object exists the access flag might has to be updated + // // (this is case occurs when the channel is readable and writable) + // if (!modbusChannel.getAccessFlag().equals(access)) { + // modbusChannel.update(access); + // } + // } + // // create a new channel object + // else { + // modbusChannel = new ModbusChannel(channelAddress, access); + // modbusChannels.put(channelAddress, modbusChannel); + // } + // + // return modbusChannel; + // + // } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + + for (ChannelValueContainer container : containers) { + + ModbusChannel modbusChannel = getModbusChannel(container.getChannelAddress(), EAccess.WRITE); + if (modbusChannel != null) { + try { + writeChannel(modbusChannel, container.getValue()); + container.setFlag(Flag.VALID); + } catch (ModbusException modbusException) { + container.setFlag(Flag.UNKNOWN_ERROR); + modbusException.printStackTrace(); + throw new ConnectionException("Unable to write data on channel address: " + container.getChannelAddress()); + } catch (Exception e) { + container.setFlag(Flag.UNKNOWN_ERROR); + e.printStackTrace(); + logger.error("Unable to write data on channel address: " + container.getChannelAddress()); + } + } else { + // TODO + container.setFlag(Flag.UNKNOWN_ERROR); + logger.error("Unable to write data on channel address: " + container.getChannelAddress() + "modbusChannel = null"); + } + } + + return null; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPDeviceAddress.java b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPDeviceAddress.java index b8221002..0007044f 100644 --- a/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPDeviceAddress.java +++ b/projects/driver/modbus/src/main/java/org/openmuc/framework/driver/modbus/tcp/ModbusTCPDeviceAddress.java @@ -24,32 +24,31 @@ public class ModbusTCPDeviceAddress { - private String ip; - private int port; - - public ModbusTCPDeviceAddress(String deviceAddress) { - String[] address = deviceAddress.toLowerCase().split(":"); - - if (address.length == 1) { - ip = address[0]; - port = Modbus.DEFAULT_PORT; - } - else if (address.length == 2) { - ip = address[0]; - port = Integer.parseInt(address[1]); - } - else { - throw new RuntimeException("Invalid device address: '" + deviceAddress - + "'! Use following format: [ip:port] like localhost:1502 or 127.0.0.1:1502"); - } - } - - public String getIp() { - return ip; - } - - public int getPort() { - return port; - } + private String ip; + private int port; + + public ModbusTCPDeviceAddress(String deviceAddress) { + String[] address = deviceAddress.toLowerCase().split(":"); + + if (address.length == 1) { + ip = address[0]; + port = Modbus.DEFAULT_PORT; + } else if (address.length == 2) { + ip = address[0]; + port = Integer.parseInt(address[1]); + } else { + throw new RuntimeException( + "Invalid device address: '" + deviceAddress + "'! Use following format: [ip:port] like localhost:1502 or 127.0.0" + + ".1:1502"); + } + } + + public String getIp() { + return ip; + } + + public int getPort() { + return port; + } } diff --git a/projects/driver/modbus/src/main/resources/OSGI-INF/components.xml b/projects/driver/modbus/src/main/resources/OSGI-INF/components.xml index a98f1286..f18b4481 100644 --- a/projects/driver/modbus/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/modbus/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/modbus/src/test/java/org/openmuc/framework/driver/modbustcp/test/ModbusTcpChannelTest.java b/projects/driver/modbus/src/test/java/org/openmuc/framework/driver/modbustcp/test/ModbusTcpChannelTest.java index ba84a5f4..99d1bb7d 100644 --- a/projects/driver/modbus/src/test/java/org/openmuc/framework/driver/modbustcp/test/ModbusTcpChannelTest.java +++ b/projects/driver/modbus/src/test/java/org/openmuc/framework/driver/modbustcp/test/ModbusTcpChannelTest.java @@ -20,8 +20,6 @@ */ package org.openmuc.framework.driver.modbustcp.test; -import java.util.ArrayList; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -30,122 +28,119 @@ import org.openmuc.framework.driver.modbus.ModbusChannel; import org.openmuc.framework.driver.modbus.ModbusChannel.EAccess; +import java.util.ArrayList; + /** * This test class tests various parameter combination of the channel address - * + * * @author Marco Mittelsdorf - * */ public class ModbusTcpChannelTest { - private ArrayList validAddressCombinations; - - @Before - public void setUp() { - validAddressCombinations = new ArrayList(); - - validAddressCombinations.add("READ:COILS:BOOLEAN"); - validAddressCombinations.add("READ:DISCRETE_INPUTS:BOOLEAN"); - - validAddressCombinations.add("READ:HOLDING_REGISTERS:SHORT"); - validAddressCombinations.add("READ:HOLDING_REGISTERS:INT"); - validAddressCombinations.add("READ:HOLDING_REGISTERS:FLOAT"); - validAddressCombinations.add("READ:HOLDING_REGISTERS:DOUBLE"); - validAddressCombinations.add("READ:HOLDING_REGISTERS:LONG"); - - // TODO read holding register bytearray - - validAddressCombinations.add("READ:INPUT_REGISTERS:SHORT"); - validAddressCombinations.add("READ:INPUT_REGISTERS:INT"); - validAddressCombinations.add("READ:INPUT_REGISTERS:FLOAT"); - validAddressCombinations.add("READ:INPUT_REGISTERS:DOUBLE"); - validAddressCombinations.add("READ:INPUT_REGISTERS:LONG"); - - // TODO read input register bytearray - - validAddressCombinations.add("WRITE:COILS:BOOLEAN"); - validAddressCombinations.add("WRITE:HOLDING_REGISTERS:SHORT"); - validAddressCombinations.add("WRITE:HOLDING_REGISTERS:INT"); - validAddressCombinations.add("WRITE:HOLDING_REGISTERS:FLOAT"); - validAddressCombinations.add("WRITE:HOLDING_REGISTERS:DOUBLE"); - validAddressCombinations.add("WRITE:HOLDING_REGISTERS:LONG"); - - // TODO write holding register bytearray - - } - - @Test - public void testValidReadAddresses() { - - ArrayList validAddresses = new ArrayList(); - - validAddresses.add("0:DISCRETE_INPUTS:0:BOOLEAN"); - validAddresses.add("0:COILS:0:BOOLEAN"); - - validAddresses.add("0:INPUT_REGISTERS:0:SHORT"); - validAddresses.add("0:INPUT_REGISTERS:0:INT"); - validAddresses.add("0:INPUT_REGISTERS:0:FLOAT"); - validAddresses.add("0:INPUT_REGISTERS:0:DOUBLE"); - validAddresses.add("0:INPUT_REGISTERS:0:LONG"); - - validAddresses.add("0:HOLDING_REGISTERS:0:SHORT"); - validAddresses.add("0:HOLDING_REGISTERS:0:INT"); - validAddresses.add("0:HOLDING_REGISTERS:0:FLOAT"); - validAddresses.add("0:HOLDING_REGISTERS:0:DOUBLE"); - validAddresses.add("0:HOLDING_REGISTERS:0:LONG"); - - for (String channelAddress : validAddresses) { - try { - ModbusChannel channel = new ModbusChannel(channelAddress, EAccess.READ); - String testString = concatenate(channel.getAccessFlag(), channel.getPrimaryTable(), - channel.getDatatype()); - if (!validAddressCombinations.contains(testString.toUpperCase())) { - Assert.fail(testString + "is not a valid paramaeter combination"); - } - else { - System.out.println(channelAddress + " and resulting " + testString.toUpperCase() + " are valid."); - } - - } catch (Exception e) { - e.printStackTrace(); - Assert.fail("unexpected exception"); - } - } - } - - @Test - public void testValidWriteAddresses() { - - ArrayList validAddresses = new ArrayList(); - - validAddresses.add("0:COILS:0:BOOLEAN"); - - validAddresses.add("0:HOLDING_REGISTERS:0:SHORT"); - validAddresses.add("0:HOLDING_REGISTERS:0:INT"); - validAddresses.add("0:HOLDING_REGISTERS:0:FLOAT"); - validAddresses.add("0:HOLDING_REGISTERS:0:DOUBLE"); - validAddresses.add("0:HOLDING_REGISTERS:0:LONG"); - - for (String channelAddress : validAddresses) { - try { - ModbusChannel channel = new ModbusChannel(channelAddress, EAccess.WRITE); - String testString = concatenate(channel.getAccessFlag(), channel.getPrimaryTable(), - channel.getDatatype()); - if (!validAddressCombinations.contains(testString.toUpperCase())) { - Assert.fail(testString + "is not a valid paramaeter combination"); - } - else { - System.out.println(channelAddress + " and resulting " + testString.toUpperCase() + " are valid."); - } - } catch (Exception e) { - e.printStackTrace(); - Assert.fail("unexpected exception"); - } - } - } - - private String concatenate(EAccess a, EPrimaryTable p, EDatatype d) { - return a.toString() + ":" + p.toString() + ":" + d.toString(); - } + private ArrayList validAddressCombinations; + + @Before + public void setUp() { + validAddressCombinations = new ArrayList(); + + validAddressCombinations.add("READ:COILS:BOOLEAN"); + validAddressCombinations.add("READ:DISCRETE_INPUTS:BOOLEAN"); + + validAddressCombinations.add("READ:HOLDING_REGISTERS:SHORT"); + validAddressCombinations.add("READ:HOLDING_REGISTERS:INT"); + validAddressCombinations.add("READ:HOLDING_REGISTERS:FLOAT"); + validAddressCombinations.add("READ:HOLDING_REGISTERS:DOUBLE"); + validAddressCombinations.add("READ:HOLDING_REGISTERS:LONG"); + + // TODO read holding register bytearray + + validAddressCombinations.add("READ:INPUT_REGISTERS:SHORT"); + validAddressCombinations.add("READ:INPUT_REGISTERS:INT"); + validAddressCombinations.add("READ:INPUT_REGISTERS:FLOAT"); + validAddressCombinations.add("READ:INPUT_REGISTERS:DOUBLE"); + validAddressCombinations.add("READ:INPUT_REGISTERS:LONG"); + + // TODO read input register bytearray + + validAddressCombinations.add("WRITE:COILS:BOOLEAN"); + validAddressCombinations.add("WRITE:HOLDING_REGISTERS:SHORT"); + validAddressCombinations.add("WRITE:HOLDING_REGISTERS:INT"); + validAddressCombinations.add("WRITE:HOLDING_REGISTERS:FLOAT"); + validAddressCombinations.add("WRITE:HOLDING_REGISTERS:DOUBLE"); + validAddressCombinations.add("WRITE:HOLDING_REGISTERS:LONG"); + + // TODO write holding register bytearray + + } + + @Test + public void testValidReadAddresses() { + + ArrayList validAddresses = new ArrayList(); + + validAddresses.add("0:DISCRETE_INPUTS:0:BOOLEAN"); + validAddresses.add("0:COILS:0:BOOLEAN"); + + validAddresses.add("0:INPUT_REGISTERS:0:SHORT"); + validAddresses.add("0:INPUT_REGISTERS:0:INT"); + validAddresses.add("0:INPUT_REGISTERS:0:FLOAT"); + validAddresses.add("0:INPUT_REGISTERS:0:DOUBLE"); + validAddresses.add("0:INPUT_REGISTERS:0:LONG"); + + validAddresses.add("0:HOLDING_REGISTERS:0:SHORT"); + validAddresses.add("0:HOLDING_REGISTERS:0:INT"); + validAddresses.add("0:HOLDING_REGISTERS:0:FLOAT"); + validAddresses.add("0:HOLDING_REGISTERS:0:DOUBLE"); + validAddresses.add("0:HOLDING_REGISTERS:0:LONG"); + + for (String channelAddress : validAddresses) { + try { + ModbusChannel channel = new ModbusChannel(channelAddress, EAccess.READ); + String testString = concatenate(channel.getAccessFlag(), channel.getPrimaryTable(), channel.getDatatype()); + if (!validAddressCombinations.contains(testString.toUpperCase())) { + Assert.fail(testString + "is not a valid paramaeter combination"); + } else { + System.out.println(channelAddress + " and resulting " + testString.toUpperCase() + " are valid."); + } + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("unexpected exception"); + } + } + } + + @Test + public void testValidWriteAddresses() { + + ArrayList validAddresses = new ArrayList(); + + validAddresses.add("0:COILS:0:BOOLEAN"); + + validAddresses.add("0:HOLDING_REGISTERS:0:SHORT"); + validAddresses.add("0:HOLDING_REGISTERS:0:INT"); + validAddresses.add("0:HOLDING_REGISTERS:0:FLOAT"); + validAddresses.add("0:HOLDING_REGISTERS:0:DOUBLE"); + validAddresses.add("0:HOLDING_REGISTERS:0:LONG"); + + for (String channelAddress : validAddresses) { + try { + ModbusChannel channel = new ModbusChannel(channelAddress, EAccess.WRITE); + String testString = concatenate(channel.getAccessFlag(), channel.getPrimaryTable(), channel.getDatatype()); + if (!validAddressCombinations.contains(testString.toUpperCase())) { + Assert.fail(testString + "is not a valid paramaeter combination"); + } else { + System.out.println(channelAddress + " and resulting " + testString.toUpperCase() + " are valid."); + } + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("unexpected exception"); + } + } + } + + private String concatenate(EAccess a, EPrimaryTable p, EDatatype d) { + return a.toString() + ":" + p.toString() + ":" + d.toString(); + } } diff --git a/projects/driver/rest/build.gradle b/projects/driver/rest/build.gradle index 6e7f89bb..6642dc50 100644 --- a/projects/driver/rest/build.gradle +++ b/projects/driver/rest/build.gradle @@ -1,26 +1,26 @@ configurations.create('embed') dependencies { - compile project(':openmuc-core-spi') - compile group: 'org.apache.felix', name: 'javax.servlet', version: '1.0.0' - compile group: 'commons-codec', name: 'commons-codec', version: '1.8' - compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1' - embed group: 'com.google.code.gson', name: 'gson', version: '2.3.1' + compile project(':openmuc-core-spi') + compile group: 'org.apache.felix', name: 'javax.servlet', version: '1.0.0' + compile group: 'commons-codec', name: 'commons-codec', version: '1.8' + compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1' + embed group: 'com.google.code.gson', name: 'gson', version: '2.3.1' } jar { - manifest { - name = "OpenMUC Driver - Rest" - instruction 'Import-Package', '!com.google.gson.*,*' - instruction 'Bundle-Classpath', '.,lib/gson-2.3.1.jar' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - Rest" + instruction 'Import-Package', '!com.google.gson.*,*' + instruction 'Bundle-Classpath', '.,lib/gson-2.3.1.jar' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestConnection.java b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestConnection.java index 4dde5c40..d909bf9d 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestConnection.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestConnection.java @@ -20,6 +20,13 @@ */ package org.openmuc.framework.driver.rest; +import org.apache.commons.codec.binary.Base64; +import org.openmuc.framework.config.ChannelScanInfo; +import org.openmuc.framework.data.*; +import org.openmuc.framework.driver.rest.helper.JsonWrapper; +import org.openmuc.framework.driver.spi.*; + +import javax.net.ssl.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; @@ -31,312 +38,267 @@ import java.security.NoSuchAlgorithmException; import java.util.List; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.codec.binary.Base64; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.Value; -import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.driver.rest.helper.JsonWrapper; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; - public class RestConnection implements Connection { - private JsonWrapper wrapper; - private URL url; - private URLConnection con; - private String deviceAddress; - private int timeout; - private boolean isHTTPS; - private String authString; - - // private final static Logger logger = LoggerFactory.getLogger(RestConnection.class); - - public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException { - - this.timeout = timeout; - wrapper = new JsonWrapper(); - authString = new String(Base64.encodeBase64(credentials.getBytes())); - - if (!deviceAddress.endsWith("/")) { - this.deviceAddress = deviceAddress + "/channels/"; - } - else { - this.deviceAddress = deviceAddress + "channels/"; - } - - if (deviceAddress.startsWith("https://")) { - isHTTPS = true; - } - else { - isHTTPS = false; - } - - if (isHTTPS) { - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { - } - } }; - - try { - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } catch (KeyManagementException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - - // Create all-trusting host name verifier - HostnameVerifier allHostsValid = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); - // HttpsURLConnection.setFollowRedirects(false); - } - } - - public Record readChannel(String channelAddress, ValueType valueType) throws ConnectionException { - - Record newRecord = null; - try { - newRecord = wrapper.toRecord(get(channelAddress), valueType); - } catch (IOException e) { - e.printStackTrace(); - throw new ConnectionException(e.getMessage()); - } - return newRecord; - } - - public List readChannels() throws ConnectionException { - - List remoteChannels = null; - try { - remoteChannels = wrapper.toChannelList(get("")); - } catch (IOException e) { - e.printStackTrace(); - throw new ConnectionException(e.getMessage()); - } - return remoteChannels; - } - - public void writeChannel(String channelAddress, Value value, ValueType valueType) throws ConnectionException { - - Record remoteRecord = new Record(value, System.currentTimeMillis()); - put(channelAddress, wrapper.fromRecord(remoteRecord, valueType)); - } - - public void connect() throws ConnectionException { - - try { - url = new URL(deviceAddress); - con = url.openConnection(); - con.setRequestProperty("Connection", "Keep-Alive"); - con.setConnectTimeout(timeout); - con.setReadTimeout(timeout); - } catch (MalformedURLException e) { - e.printStackTrace(); - throw new ConnectionException("malformed URL: " + deviceAddress); - } catch (IOException e) { - throw new ConnectionException(e.getMessage()); - } - - try { - con.connect(); - checkResponseCode(con); - } catch (IOException e) { - throw new ConnectionException(e.getMessage()); - } - } - - private InputStream get(String suffix) throws ConnectionException { - - InputStream stream = null; - try { - url = new URL(deviceAddress + suffix); - con = url.openConnection(); - con.setRequestProperty("Connection", "Keep-Alive"); - con.setConnectTimeout(timeout); - con.setReadTimeout(timeout); - stream = con.getInputStream(); - } catch (MalformedURLException e) { - e.printStackTrace(); - throw new ConnectionException("malformed URL: " + deviceAddress); - } catch (IOException e) { - e.printStackTrace(); - throw new ConnectionException(e.getMessage()); - } - - checkResponseCode(con); - return stream; - } - - private void put(String suffix, String output) throws ConnectionException { - - try { - url = new URL(deviceAddress + suffix); - con = url.openConnection(); - con.setConnectTimeout(timeout); - con.setDoOutput(true); - con.setRequestProperty("Connection", "Keep-Alive"); - con.setRequestProperty("Content-Type", "application/json"); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("Authorization", "Basic " + authString); - con.setReadTimeout(timeout); - if (isHTTPS) { - ((HttpsURLConnection) con).setRequestMethod("PUT"); - } - else { - ((HttpURLConnection) con).setRequestMethod("PUT"); - } - OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); - out.write(output); - out.close(); - } catch (MalformedURLException e) { - e.printStackTrace(); - throw new ConnectionException("malformed URL: " + deviceAddress); - } catch (IOException e) { - e.printStackTrace(); - throw new ConnectionException(e.getMessage()); - } - - checkResponseCode(con); - } - - private void checkResponseCode(URLConnection con) throws ConnectionException { - - int respCode; - try { - if (isHTTPS) { - respCode = ((HttpsURLConnection) con).getResponseCode(); - if (!(respCode >= 200 && respCode < 300)) { - throw new ConnectionException("HTTPS " + respCode + ":" - + ((HttpsURLConnection) con).getResponseMessage()); - } - } - else { - respCode = ((HttpURLConnection) con).getResponseCode(); - if (!(respCode >= 200 && respCode < 300)) { - throw new ConnectionException("HTTP " + respCode + ":" - + ((HttpURLConnection) con).getResponseMessage()); - } - } - } catch (IOException e) { - e.printStackTrace(); - throw new ConnectionException(e.getMessage()); - } - } - - @Override - public void disconnect() { - - if (isHTTPS) { - ((HttpsURLConnection) con).disconnect(); - } - else { - ((HttpURLConnection) con).disconnect(); - } - } - - @Override - public Object read(List container, Object obj, String arg3) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelRecordContainer cont : container) { - - Record record = readChannel(cont.getChannelAddress(), cont.getChannel().getValueType()); - - if (record != null) { - cont.setRecord(record); - } - } - return null; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - - return readChannels(); - } - - @Override - public void startListening(List arg1, RecordsReceivedListener arg2) - throws UnsupportedOperationException, ConnectionException { - - throw new UnsupportedOperationException(); - } - - @Override - public Object write(List container, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelValueContainer cont : container) { - Value value = cont.getValue(); - - if (value instanceof DoubleValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.DOUBLE); - } - else if (value instanceof StringValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.STRING); - } - else if (value instanceof ByteArrayValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BYTE_ARRAY); - } - else if (value instanceof LongValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.LONG); - } - else if (value instanceof BooleanValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BOOLEAN); - } - else if (value instanceof FloatValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.FLOAT); - } - else if (value instanceof IntValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.INTEGER); - } - else if (value instanceof ShortValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.SHORT); - } - else if (value instanceof ByteValue) { - writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BYTE); - } - } - return null; - } + private JsonWrapper wrapper; + private URL url; + private URLConnection con; + private String deviceAddress; + private int timeout; + private boolean isHTTPS; + private String authString; + + // private final static Logger logger = LoggerFactory.getLogger(RestConnection.class); + + public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException { + + this.timeout = timeout; + wrapper = new JsonWrapper(); + authString = new String(Base64.encodeBase64(credentials.getBytes())); + + if (!deviceAddress.endsWith("/")) { + this.deviceAddress = deviceAddress + "/channels/"; + } else { + this.deviceAddress = deviceAddress + "channels/"; + } + + if (deviceAddress.startsWith("https://")) { + isHTTPS = true; + } else { + isHTTPS = false; + } + + if (isHTTPS) { + TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { + } + }}; + + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (KeyManagementException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + // Create all-trusting host name verifier + HostnameVerifier allHostsValid = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + // HttpsURLConnection.setFollowRedirects(false); + } + } + + public Record readChannel(String channelAddress, ValueType valueType) throws ConnectionException { + + Record newRecord = null; + try { + newRecord = wrapper.toRecord(get(channelAddress), valueType); + } catch (IOException e) { + e.printStackTrace(); + throw new ConnectionException(e.getMessage()); + } + return newRecord; + } + + public List readChannels() throws ConnectionException { + + List remoteChannels = null; + try { + remoteChannels = wrapper.toChannelList(get("")); + } catch (IOException e) { + e.printStackTrace(); + throw new ConnectionException(e.getMessage()); + } + return remoteChannels; + } + + public void writeChannel(String channelAddress, Value value, ValueType valueType) throws ConnectionException { + + Record remoteRecord = new Record(value, System.currentTimeMillis()); + put(channelAddress, wrapper.fromRecord(remoteRecord, valueType)); + } + + public void connect() throws ConnectionException { + + try { + url = new URL(deviceAddress); + con = url.openConnection(); + con.setRequestProperty("Connection", "Keep-Alive"); + con.setConnectTimeout(timeout); + con.setReadTimeout(timeout); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new ConnectionException("malformed URL: " + deviceAddress); + } catch (IOException e) { + throw new ConnectionException(e.getMessage()); + } + + try { + con.connect(); + checkResponseCode(con); + } catch (IOException e) { + throw new ConnectionException(e.getMessage()); + } + } + + private InputStream get(String suffix) throws ConnectionException { + + InputStream stream = null; + try { + url = new URL(deviceAddress + suffix); + con = url.openConnection(); + con.setRequestProperty("Connection", "Keep-Alive"); + con.setConnectTimeout(timeout); + con.setReadTimeout(timeout); + stream = con.getInputStream(); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new ConnectionException("malformed URL: " + deviceAddress); + } catch (IOException e) { + e.printStackTrace(); + throw new ConnectionException(e.getMessage()); + } + + checkResponseCode(con); + return stream; + } + + private void put(String suffix, String output) throws ConnectionException { + + try { + url = new URL(deviceAddress + suffix); + con = url.openConnection(); + con.setConnectTimeout(timeout); + con.setDoOutput(true); + con.setRequestProperty("Connection", "Keep-Alive"); + con.setRequestProperty("Content-Type", "application/json"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("Authorization", "Basic " + authString); + con.setReadTimeout(timeout); + if (isHTTPS) { + ((HttpsURLConnection) con).setRequestMethod("PUT"); + } else { + ((HttpURLConnection) con).setRequestMethod("PUT"); + } + OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); + out.write(output); + out.close(); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new ConnectionException("malformed URL: " + deviceAddress); + } catch (IOException e) { + e.printStackTrace(); + throw new ConnectionException(e.getMessage()); + } + + checkResponseCode(con); + } + + private void checkResponseCode(URLConnection con) throws ConnectionException { + + int respCode; + try { + if (isHTTPS) { + respCode = ((HttpsURLConnection) con).getResponseCode(); + if (!(respCode >= 200 && respCode < 300)) { + throw new ConnectionException("HTTPS " + respCode + ":" + ((HttpsURLConnection) con).getResponseMessage()); + } + } else { + respCode = ((HttpURLConnection) con).getResponseCode(); + if (!(respCode >= 200 && respCode < 300)) { + throw new ConnectionException("HTTP " + respCode + ":" + ((HttpURLConnection) con).getResponseMessage()); + } + } + } catch (IOException e) { + e.printStackTrace(); + throw new ConnectionException(e.getMessage()); + } + } + + @Override + public void disconnect() { + + if (isHTTPS) { + ((HttpsURLConnection) con).disconnect(); + } else { + ((HttpURLConnection) con).disconnect(); + } + } + + @Override + public Object read(List container, Object obj, String arg3) throws UnsupportedOperationException, + ConnectionException { + + for (ChannelRecordContainer cont : container) { + + Record record = readChannel(cont.getChannelAddress(), cont.getChannel().getValueType()); + + if (record != null) { + cont.setRecord(record); + } + } + return null; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + + return readChannels(); + } + + @Override + public void startListening(List arg1, RecordsReceivedListener arg2) throws UnsupportedOperationException, + ConnectionException { + + throw new UnsupportedOperationException(); + } + + @Override + public Object write(List container, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + + for (ChannelValueContainer cont : container) { + Value value = cont.getValue(); + + if (value instanceof DoubleValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.DOUBLE); + } else if (value instanceof StringValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.STRING); + } else if (value instanceof ByteArrayValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BYTE_ARRAY); + } else if (value instanceof LongValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.LONG); + } else if (value instanceof BooleanValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BOOLEAN); + } else if (value instanceof FloatValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.FLOAT); + } else if (value instanceof IntValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.INTEGER); + } else if (value instanceof ShortValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.SHORT); + } else if (value instanceof ByteValue) { + writeChannel(cont.getChannelAddress(), cont.getValue(), ValueType.BYTE); + } + } + return null; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestDriverImpl.java b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestDriverImpl.java index 139c77c6..b57648a8 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestDriverImpl.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/RestDriverImpl.java @@ -30,73 +30,69 @@ public class RestDriverImpl implements DriverService { - // private final static Logger logger = LoggerFactory.getLogger(RestDriverImpl.class); - - private final static int timeout = 10000; - - private final static DriverInfo info = new DriverInfo("rest", // id - // description - "Driver to connect this OpenMUC instance with another, remote OpenMUC instance with rest.", - // device address - "https://adress:port or http://adress:port", - // settings - "username:password", - // channel address - "/rest/channels/channelid", - // device scan settings - "N.A."); - - public RestDriverImpl() { - - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - - RestConnection connection; - - String HTTP = "http://"; - String HTTPS = "https://"; - - if (settings == null || settings.isEmpty() || settings.trim().isEmpty() || !settings.contains(":")) { - throw new ArgumentSyntaxException("Invalid User Credentials provided in settings: " + settings - + ". Expected Format: username:password"); - } - if (deviceAddress == null || deviceAddress.isEmpty() || deviceAddress.trim().isEmpty() - || !deviceAddress.contains(":")) { - throw new ArgumentSyntaxException("Invalid address or port: " + deviceAddress - + ". Expected Format: https://adress:port or http://adress:port"); - } - else if (deviceAddress.startsWith(HTTP) || deviceAddress.startsWith(HTTPS)) { - connection = new RestConnection(deviceAddress, settings, timeout); - connection.connect(); - return connection; - } - else { - throw new ConnectionException("Invalid address or port: " + deviceAddress - + ". Expected Format: https://adress:port or http://adress:port"); - } - - } - - @Override - public DriverInfo getInfo() { - - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException { - - throw new UnsupportedOperationException(); - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - - throw new UnsupportedOperationException(); - } + // private final static Logger logger = LoggerFactory.getLogger(RestDriverImpl.class); + + private final static int timeout = 10000; + + private final static DriverInfo info = new DriverInfo("rest", // id + // description + "Driver to connect this OpenMUC instance with another, remote OpenMUC instance " + + "with rest.", + // device address + "https://adress:port or http://adress:port", + // settings + "username:password", + // channel address + "/rest/channels/channelid", + // device scan settings + "N.A."); + + public RestDriverImpl() { + + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + + RestConnection connection; + + String HTTP = "http://"; + String HTTPS = "https://"; + + if (settings == null || settings.isEmpty() || settings.trim().isEmpty() || !settings.contains(":")) { + throw new ArgumentSyntaxException( + "Invalid User Credentials provided in settings: " + settings + ". Expected Format: username:password"); + } + if (deviceAddress == null || deviceAddress.isEmpty() || deviceAddress.trim().isEmpty() || !deviceAddress.contains(":")) { + throw new ArgumentSyntaxException( + "Invalid address or port: " + deviceAddress + ". Expected Format: https://adress:port or http://adress:port"); + } else if (deviceAddress.startsWith(HTTP) || deviceAddress.startsWith(HTTPS)) { + connection = new RestConnection(deviceAddress, settings, timeout); + connection.connect(); + return connection; + } else { + throw new ConnectionException( + "Invalid address or port: " + deviceAddress + ". Expected Format: https://adress:port or http://adress:port"); + } + + } + + @Override + public DriverInfo getInfo() { + + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, ArgumentSyntaxException, ScanException { + + throw new UnsupportedOperationException(); + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/helper/JsonWrapper.java b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/helper/JsonWrapper.java index 7475930c..2f0a59cc 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/helper/JsonWrapper.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/driver/rest/helper/JsonWrapper.java @@ -20,54 +20,54 @@ */ package org.openmuc.framework.driver.rest.helper; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; - import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.lib.json.FromJson; import org.openmuc.framework.lib.json.ToJson; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; + public class JsonWrapper { - public String fromRecord(Record remoteRecord, ValueType valueType) { + public String fromRecord(Record remoteRecord, ValueType valueType) { - ToJson toJson = new ToJson(); - toJson.addRecord(remoteRecord, valueType); + ToJson toJson = new ToJson(); + toJson.addRecord(remoteRecord, valueType); - return toJson.toString(); - } + return toJson.toString(); + } - public List toChannelList(InputStream stream) throws IOException { + public List toChannelList(InputStream stream) throws IOException { - String jsonString = getStringFromInputStream(stream); - FromJson fromJson = new FromJson(jsonString); + String jsonString = getStringFromInputStream(stream); + FromJson fromJson = new FromJson(jsonString); - return fromJson.getChannelScanInfoList(); - } + return fromJson.getChannelScanInfoList(); + } - public Record toRecord(InputStream stream, ValueType valueType) throws IOException { + public Record toRecord(InputStream stream, ValueType valueType) throws IOException { - String jsonString = getStringFromInputStream(stream); - FromJson fromJson = new FromJson(jsonString); + String jsonString = getStringFromInputStream(stream); + FromJson fromJson = new FromJson(jsonString); - return fromJson.getRecord(valueType); - } + return fromJson.getRecord(valueType); + } - private String getStringFromInputStream(InputStream stream) throws IOException { + private String getStringFromInputStream(InputStream stream) throws IOException { - BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); - StringBuilder responseStrBuilder = new StringBuilder(); + BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); + StringBuilder responseStrBuilder = new StringBuilder(); - String inputStr; - while ((inputStr = streamReader.readLine()) != null) { - responseStrBuilder.append(inputStr); - } + String inputStr; + while ((inputStr = streamReader.readLine()) != null) { + responseStrBuilder.append(inputStr); + } - return responseStrBuilder.toString(); - } + return responseStrBuilder.toString(); + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/Const.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/Const.java index a0231e54..f4d1af7d 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/Const.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/Const.java @@ -22,37 +22,37 @@ public class Const { - public final static String REST = "/rest/"; - public final static String CHANNELS = "channels"; - public final static String DEVICES = "devices"; - public final static String DRIVERS = "drivers"; - public final static String AUTHENTICATIONS = "authentications"; - public final static String RECORDS = "records"; + public final static String REST = "/rest/"; + public final static String CHANNELS = "channels"; + public final static String DEVICES = "devices"; + public final static String DRIVERS = "drivers"; + public final static String AUTHENTICATIONS = "authentications"; + public final static String RECORDS = "records"; - public final static String ALIAS_CHANNELS = "/rest/channels"; - public final static String ALIAS_DEVICES = "/rest/devices"; - public final static String ALIAS_DRIVERS = "/rest/drivers"; - public final static String ALIAS_AUTHENTICATIONS = "/rest/authentications"; - public final static String ALIAS_USERS = "/rest/users"; + public final static String ALIAS_CHANNELS = "/rest/channels"; + public final static String ALIAS_DEVICES = "/rest/devices"; + public final static String ALIAS_DRIVERS = "/rest/drivers"; + public final static String ALIAS_AUTHENTICATIONS = "/rest/authentications"; + public final static String ALIAS_USERS = "/rest/users"; - public final static String RUNNING = "running"; - public final static String STATE = "state"; - public final static String RECORD = "record"; - public final static String LATESTRECORD = "latestRecord"; - public final static String ID = "id"; - public final static String FLAG = "flag"; - public final static String CONFIGS = "configs"; - public final static String SCAN = "scan"; - public final static String WRITE = "write"; - public final static String HISTORY = "history"; - public final static String SETTINGS = "settings"; - public final static String TYPE = "type"; - public final static String DEVICEADDRESS = "deviceAddress"; - public final static String DESCRIPTION = "description"; - public final static String CHANNELADDRESS = "channelAddress"; - public final static String VALUETYPE = "valueType"; - public final static String VALUETYPELENGTH = "valuetypeLength"; + public final static String RUNNING = "running"; + public final static String STATE = "state"; + public final static String RECORD = "record"; + public final static String LATESTRECORD = "latestRecord"; + public final static String ID = "id"; + public final static String FLAG = "flag"; + public final static String CONFIGS = "configs"; + public final static String SCAN = "scan"; + public final static String WRITE = "write"; + public final static String HISTORY = "history"; + public final static String SETTINGS = "settings"; + public final static String TYPE = "type"; + public final static String DEVICEADDRESS = "deviceAddress"; + public final static String DESCRIPTION = "description"; + public final static String CHANNELADDRESS = "channelAddress"; + public final static String VALUETYPE = "valueType"; + public final static String VALUETYPELENGTH = "valuetypeLength"; - public final static String DEVICE = "device"; - public final static String DRIVER = "driver"; + public final static String DEVICE = "device"; + public final static String DRIVER = "driver"; } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/FromJson.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/FromJson.java index 2a83b780..215902d2 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/FromJson.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/FromJson.java @@ -20,352 +20,318 @@ */ package org.openmuc.framework.lib.json; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.Value; -import org.openmuc.framework.data.ValueType; +import com.google.gson.*; +import org.openmuc.framework.config.*; +import org.openmuc.framework.data.*; import org.openmuc.framework.dataaccess.DeviceState; import org.openmuc.framework.lib.json.exceptions.MissingJsonObjectException; import org.openmuc.framework.lib.json.exceptions.RestConfigIsNotCorrectException; -import org.openmuc.framework.lib.json.restObjects.RestChannel; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfig; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfig; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfig; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestRecord; -import org.openmuc.framework.lib.json.restObjects.RestValue; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; +import org.openmuc.framework.lib.json.restObjects.*; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class FromJson { - private final Gson gson; - private final JsonObject jsonObject; + private final Gson gson; + private final JsonObject jsonObject; + + public FromJson(String jsonString) { - public FromJson(String jsonString) { + gson = new Gson(); + jsonObject = gson.fromJson(jsonString, JsonObject.class); + } - gson = new Gson(); - jsonObject = gson.fromJson(jsonString, JsonObject.class); - } + public Gson getGson() { - public Gson getGson() { + return gson; + } - return gson; - } + public JsonObject getJsonObject() { - public JsonObject getJsonObject() { + return jsonObject; + } - return jsonObject; - } + public Record getRecord(ValueType valueType) throws ClassCastException { - public Record getRecord(ValueType valueType) throws ClassCastException { + Record record = null; + JsonElement jse = jsonObject.get(Const.RECORD); - Record record = null; - JsonElement jse = jsonObject.get(Const.RECORD); + if (!jse.isJsonNull()) { + record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); + } + return record; + } - if (!jse.isJsonNull()) { - record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); - } - return record; - } + public ArrayList getRecordArrayList(ValueType valueType) throws ClassCastException { - public ArrayList getRecordArrayList(ValueType valueType) throws ClassCastException { + ArrayList recordList = new ArrayList(); - ArrayList recordList = new ArrayList(); + JsonElement jse = jsonObject.get(Const.RECORDS); + if (jse != null && jse.isJsonArray()) { + JsonArray jsa = jse.getAsJsonArray(); - JsonElement jse = jsonObject.get(Const.RECORDS); - if (jse != null && jse.isJsonArray()) { - JsonArray jsa = jse.getAsJsonArray(); + Iterator iteratorJsonArray = jsa.iterator(); + while (iteratorJsonArray.hasNext()) { + recordList.add(getRecord(valueType)); + } + } + if (recordList.size() == 0) { + recordList = null; + } + return recordList; + } - Iterator iteratorJsonArray = jsa.iterator(); - while (iteratorJsonArray.hasNext()) { - recordList.add(getRecord(valueType)); - } - } - if (recordList.size() == 0) { - recordList = null; - } - return recordList; - } + public Value getValue(ValueType valueType) throws ClassCastException { - public Value getValue(ValueType valueType) throws ClassCastException { + Value value = null; + JsonElement jse = jsonObject.get(Const.RECORD); - Value value = null; - JsonElement jse = jsonObject.get(Const.RECORD); + if (!jse.isJsonNull()) { + Record record = getRecord(valueType); + if (record != null) { + value = record.getValue(); + } + } + return value; + } - if (!jse.isJsonNull()) { - Record record = getRecord(valueType); - if (record != null) { - value = record.getValue(); - } - } - return value; - } + public boolean isRunning() { - public boolean isRunning() { + return jsonObject.get(Const.RUNNING).getAsBoolean(); + } - return jsonObject.get(Const.RUNNING).getAsBoolean(); - } + public DeviceState getDeviceState() { - public DeviceState getDeviceState() { + DeviceState ret = null; + JsonElement jse = jsonObject.get(Const.STATE); - DeviceState ret = null; - JsonElement jse = jsonObject.get(Const.STATE); + if (!jse.isJsonNull()) { + ret = gson.fromJson(jse, DeviceState.class); + } + return ret; + } - if (!jse.isJsonNull()) { - ret = gson.fromJson(jse, DeviceState.class); - } - return ret; - } + public void setChannelConfig(ChannelConfig channelConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { - public void setChannelConfig(ChannelConfig channelConfig, String id) throws JsonSyntaxException, - IdCollisionException, RestConfigIsNotCorrectException, MissingJsonObjectException { + JsonElement jse = jsonObject.get(Const.CONFIGS); - JsonElement jse = jsonObject.get(Const.CONFIGS); + if (!jse.isJsonNull()) { + RestChannelConfigMapper.setChannelConfig(channelConfig, gson.fromJson(jse, RestChannelConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } - if (!jse.isJsonNull()) { - RestChannelConfigMapper.setChannelConfig(channelConfig, gson.fromJson(jse, RestChannelConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } + public void setDeviceConfig(DeviceConfig deviceConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { - public void setDeviceConfig(DeviceConfig deviceConfig, String id) throws JsonSyntaxException, IdCollisionException, - RestConfigIsNotCorrectException, MissingJsonObjectException { - - JsonElement jse = jsonObject.get(Const.CONFIGS); - - if (!jse.isJsonNull()) { - RestDeviceConfigMapper.setDeviceConfig(deviceConfig, gson.fromJson(jse, RestDeviceConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } - - public void setDriverConfig(DriverConfig driverConfig, String id) throws JsonSyntaxException, IdCollisionException, - RestConfigIsNotCorrectException, MissingJsonObjectException { - - JsonElement jse = jsonObject.get(Const.CONFIGS); - - if (!jse.isJsonNull()) { - RestDriverConfigMapper.setDriverConfig(driverConfig, gson.fromJson(jse, RestDriverConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } - - public ArrayList getStringArrayList(String listName) { - - ArrayList resultList = new ArrayList(); - - JsonElement jse = jsonObject.get(listName); - if (jse != null && jse.isJsonArray()) { - JsonArray jsa = jse.getAsJsonArray(); - - Iterator iteratorJsonArray = jsa.iterator(); - while (iteratorJsonArray.hasNext()) { - resultList.add(iteratorJsonArray.next().toString()); - } - } - if (resultList.size() == 0) { - resultList = null; - } - return resultList; - } - - public String[] getStringArray(String listName) { - - String stringArray[] = null; - - JsonElement jse = jsonObject.get(listName); - if (!jse.isJsonNull() && jse.isJsonArray()) { - stringArray = gson.fromJson(jse, String[].class); - } - return stringArray; - } - - public ArrayList getRestChannelArrayList() throws ClassCastException { - - ArrayList recordList = new ArrayList(); - JsonElement jse = jsonObject.get("records"); - JsonArray jsa; - - if (!jse.isJsonNull() && jse.isJsonArray()) { - - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - - while (jseIterator.hasNext()) { - RestChannel rc = new RestChannel(); - JsonObject jsoIterated = jseIterator.next().getAsJsonObject(); - rc.setId(jsoIterated.get(Const.ID).getAsString()); - rc.setType(gson.fromJson(jsoIterated.get(Const.TYPE), ValueType.class)); // TODO: need valueType in json - // or something else - // otherwise null pointer - // exception - rc.setRecord(getRecord(jsoIterated, rc.getType())); - - recordList.add(rc); - } - } - if (recordList.size() == 0) { - return null; - } - return recordList; - } - - public List getDeviceScanInfoList() { - - List returnValue = new ArrayList(); - JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? - JsonArray jsa; - - if (jse.isJsonArray()) { - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - while (jseIterator.hasNext()) { - - JsonObject jso = jseIterator.next().getAsJsonObject(); - // String id = jso.get(Const.ID).getAsString(); - String deviceAddress = jso.get(Const.DEVICEADDRESS).getAsString(); - String settings = jso.get(Const.SETTINGS).getAsString(); - String description = jso.get(Const.DESCRIPTION).getAsString(); - returnValue.add(new DeviceScanInfo(deviceAddress, settings, description)); - } - } - else { - returnValue = null; - } - return returnValue; - } - - public List getChannelScanInfoList() { - - List returnValue = new ArrayList(); - JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? - JsonArray jsa; - - if (jse.isJsonArray()) { - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - while (jseIterator.hasNext()) { - - JsonObject jso = jseIterator.next().getAsJsonObject(); - String channelAddress = jso.get(Const.CHANNELADDRESS).getAsString(); - ValueType valueType = ValueType.valueOf(jso.get(Const.VALUETYPE).getAsString()); - int valueTypeLength = jso.get(Const.VALUETYPELENGTH).getAsInt(); - String description = jso.get(Const.DESCRIPTION).getAsString(); - returnValue.add(new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength)); - } - } - else { - returnValue = null; - } - return returnValue; - } - - private Record getRecord(JsonObject jso, ValueType valueType) throws ClassCastException { - - Record record = null; - JsonElement jse = jso.get(Const.RECORD); - - if (jse != null && !jse.isJsonNull()) { - record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); - } - return record; - } - - private Record getRecord(RestRecord rrc, ValueType type) throws ClassCastException { - - Object value = rrc.getValue(); - Value retValue = null; - if (value != null) { - retValue = getValue(type, value); - } - return new Record(retValue, rrc.getTimestamp(), rrc.getFlag()); - } - - private Value getValue(ValueType type, Object value) throws ClassCastException { - // TODO: check all value types, if it is really a float, double, ... - - if (value.getClass().isInstance(new RestValue())) { - value = ((RestValue) value).getValue(); - } - Value retValue = null; - switch (type) { - case FLOAT: - FloatValue fvalue = new FloatValue(((Double) value).floatValue()); - retValue = fvalue; - break; - case DOUBLE: - DoubleValue dValue = new DoubleValue((Double) value); - retValue = dValue; - break; - case SHORT: - ShortValue shValue = new ShortValue(((Double) value).shortValue()); - retValue = shValue; - break; - case INTEGER: - IntValue iValue = new IntValue(((Double) value).intValue()); - retValue = iValue; - break; - case LONG: - LongValue lValue = new LongValue(((Double) value).longValue()); - retValue = lValue; - break; - case BYTE: - ByteValue byValue = new ByteValue(((Double) value).byteValue()); - retValue = byValue; - break; - case BOOLEAN: - BooleanValue boValue = new BooleanValue((Boolean) value); - retValue = boValue; - break; - case BYTE_ARRAY: - @SuppressWarnings("unchecked") - ArrayList arrayList = ((ArrayList) value); - byte[] byteArray = new byte[arrayList.size()]; - for (int i = 0; i < arrayList.size(); ++i) { - byteArray[i] = arrayList.get(i).byteValue(); - } - ByteArrayValue baValue = new ByteArrayValue(byteArray); - retValue = baValue; - break; - case STRING: - StringValue stValue = new StringValue((String) value); - retValue = stValue; - break; - default: - break; - } - return retValue; - } + JsonElement jse = jsonObject.get(Const.CONFIGS); + + if (!jse.isJsonNull()) { + RestDeviceConfigMapper.setDeviceConfig(deviceConfig, gson.fromJson(jse, RestDeviceConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } + + public void setDriverConfig(DriverConfig driverConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { + + JsonElement jse = jsonObject.get(Const.CONFIGS); + + if (!jse.isJsonNull()) { + RestDriverConfigMapper.setDriverConfig(driverConfig, gson.fromJson(jse, RestDriverConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } + + public ArrayList getStringArrayList(String listName) { + + ArrayList resultList = new ArrayList(); + + JsonElement jse = jsonObject.get(listName); + if (jse != null && jse.isJsonArray()) { + JsonArray jsa = jse.getAsJsonArray(); + + Iterator iteratorJsonArray = jsa.iterator(); + while (iteratorJsonArray.hasNext()) { + resultList.add(iteratorJsonArray.next().toString()); + } + } + if (resultList.size() == 0) { + resultList = null; + } + return resultList; + } + + public String[] getStringArray(String listName) { + + String stringArray[] = null; + + JsonElement jse = jsonObject.get(listName); + if (!jse.isJsonNull() && jse.isJsonArray()) { + stringArray = gson.fromJson(jse, String[].class); + } + return stringArray; + } + + public ArrayList getRestChannelArrayList() throws ClassCastException { + + ArrayList recordList = new ArrayList(); + JsonElement jse = jsonObject.get("records"); + JsonArray jsa; + + if (!jse.isJsonNull() && jse.isJsonArray()) { + + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + + while (jseIterator.hasNext()) { + RestChannel rc = new RestChannel(); + JsonObject jsoIterated = jseIterator.next().getAsJsonObject(); + rc.setId(jsoIterated.get(Const.ID).getAsString()); + rc.setType(gson.fromJson(jsoIterated.get(Const.TYPE), ValueType.class)); // TODO: need valueType in json + // or something else + // otherwise null pointer + // exception + rc.setRecord(getRecord(jsoIterated, rc.getType())); + + recordList.add(rc); + } + } + if (recordList.size() == 0) { + return null; + } + return recordList; + } + + public List getDeviceScanInfoList() { + + List returnValue = new ArrayList(); + JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? + JsonArray jsa; + + if (jse.isJsonArray()) { + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + while (jseIterator.hasNext()) { + + JsonObject jso = jseIterator.next().getAsJsonObject(); + // String id = jso.get(Const.ID).getAsString(); + String deviceAddress = jso.get(Const.DEVICEADDRESS).getAsString(); + String settings = jso.get(Const.SETTINGS).getAsString(); + String description = jso.get(Const.DESCRIPTION).getAsString(); + returnValue.add(new DeviceScanInfo(deviceAddress, settings, description)); + } + } else { + returnValue = null; + } + return returnValue; + } + + public List getChannelScanInfoList() { + + List returnValue = new ArrayList(); + JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? + JsonArray jsa; + + if (jse.isJsonArray()) { + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + while (jseIterator.hasNext()) { + + JsonObject jso = jseIterator.next().getAsJsonObject(); + String channelAddress = jso.get(Const.CHANNELADDRESS).getAsString(); + ValueType valueType = ValueType.valueOf(jso.get(Const.VALUETYPE).getAsString()); + int valueTypeLength = jso.get(Const.VALUETYPELENGTH).getAsInt(); + String description = jso.get(Const.DESCRIPTION).getAsString(); + returnValue.add(new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength)); + } + } else { + returnValue = null; + } + return returnValue; + } + + private Record getRecord(JsonObject jso, ValueType valueType) throws ClassCastException { + + Record record = null; + JsonElement jse = jso.get(Const.RECORD); + + if (jse != null && !jse.isJsonNull()) { + record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); + } + return record; + } + + private Record getRecord(RestRecord rrc, ValueType type) throws ClassCastException { + + Object value = rrc.getValue(); + Value retValue = null; + if (value != null) { + retValue = getValue(type, value); + } + return new Record(retValue, rrc.getTimestamp(), rrc.getFlag()); + } + + private Value getValue(ValueType type, Object value) throws ClassCastException { + // TODO: check all value types, if it is really a float, double, ... + + if (value.getClass().isInstance(new RestValue())) { + value = ((RestValue) value).getValue(); + } + Value retValue = null; + switch (type) { + case FLOAT: + FloatValue fvalue = new FloatValue(((Double) value).floatValue()); + retValue = fvalue; + break; + case DOUBLE: + DoubleValue dValue = new DoubleValue((Double) value); + retValue = dValue; + break; + case SHORT: + ShortValue shValue = new ShortValue(((Double) value).shortValue()); + retValue = shValue; + break; + case INTEGER: + IntValue iValue = new IntValue(((Double) value).intValue()); + retValue = iValue; + break; + case LONG: + LongValue lValue = new LongValue(((Double) value).longValue()); + retValue = lValue; + break; + case BYTE: + ByteValue byValue = new ByteValue(((Double) value).byteValue()); + retValue = byValue; + break; + case BOOLEAN: + BooleanValue boValue = new BooleanValue((Boolean) value); + retValue = boValue; + break; + case BYTE_ARRAY: + @SuppressWarnings("unchecked") + ArrayList arrayList = ((ArrayList) value); + byte[] byteArray = new byte[arrayList.size()]; + for (int i = 0; i < arrayList.size(); ++i) { + byteArray[i] = arrayList.get(i).byteValue(); + } + ByteArrayValue baValue = new ByteArrayValue(byteArray); + retValue = baValue; + break; + case STRING: + StringValue stValue = new StringValue((String) value); + retValue = stValue; + break; + default: + break; + } + return retValue; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/ToJson.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/ToJson.java index 8a4d7911..1829ac68 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/ToJson.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/ToJson.java @@ -20,264 +20,251 @@ */ package org.openmuc.framework.lib.json; -import java.util.List; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverConfig; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.dataaccess.Channel; import org.openmuc.framework.dataaccess.DeviceState; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfig; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfig; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfig; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestRecord; +import org.openmuc.framework.lib.json.restObjects.*; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import java.util.List; public class ToJson { - private final Gson gson; - private final JsonObject jsonObject; + private final Gson gson; + private final JsonObject jsonObject; - public ToJson() { + public ToJson() { - gson = new Gson(); - jsonObject = new JsonObject(); - } + gson = new Gson(); + jsonObject = new JsonObject(); + } - public JsonObject getJsonObject() { + public JsonObject getJsonObject() { - return jsonObject; - } + return jsonObject; + } - public void addJsonObject(String propertyName, JsonObject jsonObject) { + public void addJsonObject(String propertyName, JsonObject jsonObject) { - this.jsonObject.add(propertyName, jsonObject); - } + this.jsonObject.add(propertyName, jsonObject); + } - @Override - public String toString() { - return jsonObject.toString(); - } + @Override + public String toString() { + return jsonObject.toString(); + } - public void addRecord(Record record, ValueType valueType) throws ClassCastException { + public void addRecord(Record record, ValueType valueType) throws ClassCastException { - jsonObject.add(Const.RECORD, getRecordAsJsonElement(record, valueType)); - } + jsonObject.add(Const.RECORD, getRecordAsJsonElement(record, valueType)); + } - public void addRecordList(List recordList, ValueType valueType) throws ClassCastException { + public void addRecordList(List recordList, ValueType valueType) throws ClassCastException { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Record record : recordList) { - jsa.add(getRecordAsJsonElement(record, valueType)); - } - jsonObject.add(Const.RECORDS, jsa); - } + for (Record record : recordList) { + jsa.add(getRecordAsJsonElement(record, valueType)); + } + jsonObject.add(Const.RECORDS, jsa); + } - public void addChannelRecordList(List channels) throws ClassCastException { + public void addChannelRecordList(List channels) throws ClassCastException { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Channel channel : channels) { - jsa.add(channelRecordToJson(channel)); - } - jsonObject.add(Const.RECORDS, jsa); - } + for (Channel channel : channels) { + jsa.add(channelRecordToJson(channel)); + } + jsonObject.add(Const.RECORDS, jsa); + } - public void addDeviceState(DeviceState deviceState) { + public void addDeviceState(DeviceState deviceState) { - jsonObject.addProperty(Const.STATE, deviceState.name()); - } + jsonObject.addProperty(Const.STATE, deviceState.name()); + } - public void addBoolean(String propertyName, boolean value) { + public void addBoolean(String propertyName, boolean value) { - jsonObject.addProperty(propertyName, value); - } + jsonObject.addProperty(propertyName, value); + } - public void addStringList(String propertyName, List stringList) { + public void addStringList(String propertyName, List stringList) { - jsonObject.add(propertyName, gson.toJsonTree(stringList).getAsJsonArray()); - } + jsonObject.add(propertyName, gson.toJsonTree(stringList).getAsJsonArray()); + } - public void addDriverList(List driverConfigList) { + public void addDriverList(List driverConfigList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (DriverConfig driverConfig : driverConfigList) { - jsa.add(gson.toJsonTree(driverConfig.getId())); - } - jsonObject.add(Const.DRIVERS, jsa); - } + for (DriverConfig driverConfig : driverConfigList) { + jsa.add(gson.toJsonTree(driverConfig.getId())); + } + jsonObject.add(Const.DRIVERS, jsa); + } - public void addDeviceList(List deviceConfigList) { + public void addDeviceList(List deviceConfigList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (DeviceConfig deviceConfig : deviceConfigList) { - jsa.add(gson.toJsonTree(deviceConfig.getId())); - } - jsonObject.add(Const.DEVICES, jsa); - } + for (DeviceConfig deviceConfig : deviceConfigList) { + jsa.add(gson.toJsonTree(deviceConfig.getId())); + } + jsonObject.add(Const.DEVICES, jsa); + } - public void addChannelList(List channelList) { + public void addChannelList(List channelList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Channel channelConfig : channelList) { - jsa.add(gson.toJsonTree(channelConfig.getId())); - } - jsonObject.add(Const.CHANNELS, jsa); - } + for (Channel channelConfig : channelList) { + jsa.add(gson.toJsonTree(channelConfig.getId())); + } + jsonObject.add(Const.CHANNELS, jsa); + } - public void addDriverConfig(DriverConfig config) { + public void addDriverConfig(DriverConfig config) { - RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject()); - } + RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject()); + } - public void addDeviceConfig(DeviceConfig config) { + public void addDeviceConfig(DeviceConfig config) { - RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject()); - } + RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject()); + } - public void addChannelConfig(ChannelConfig config) { + public void addChannelConfig(ChannelConfig config) { - RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject()); - } + RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject()); + } - public void addDeviceScanInfoList(List deviceScanInfoList) { + public void addDeviceScanInfoList(List deviceScanInfoList) { - JsonArray jsa = new JsonArray(); - for (DeviceScanInfo deviceScanInfo : deviceScanInfoList) { - JsonObject jso = new JsonObject(); - jso.addProperty(Const.ID, deviceScanInfo.getId()); - jso.addProperty(Const.DEVICEADDRESS, deviceScanInfo.getDeviceAddress()); - jso.addProperty(Const.SETTINGS, deviceScanInfo.getSettings()); - jso.addProperty(Const.DESCRIPTION, deviceScanInfo.getDescription()); - jsa.add(jso); - } - jsonObject.add(Const.DEVICES, jsa); - } - - public void addChannelScanInfoList(List channelScanInfoList) { - - JsonArray jsa = new JsonArray(); - for (ChannelScanInfo channelScanInfo : channelScanInfoList) { - JsonObject jso = new JsonObject(); - jso.addProperty(Const.CHANNELADDRESS, channelScanInfo.getChannelAddress()); - jso.addProperty(Const.VALUETYPE, channelScanInfo.getValueType().name()); - jso.addProperty(Const.VALUETYPELENGTH, channelScanInfo.getValueTypeLength()); - jso.addProperty(Const.DESCRIPTION, channelScanInfo.getDescription()); - jsa.add(jso); - } - jsonObject.add(Const.CHANNELS, jsa); - } - - public static JsonObject getDriverConfigAsJsonObject(DriverConfig config) { - - RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject(); - } - - public static JsonObject getDeviceConfigAsJsonObject(DeviceConfig config) { - - RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject(); - } - - public static JsonObject getChannelConfigAsJsonObject(ChannelConfig config) { - - RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject(); - } - - private JsonObject channelRecordToJson(Channel channel) throws ClassCastException { - - JsonObject jso = new JsonObject(); - - jso.addProperty(Const.ID, channel.getId()); - jso.add(Const.RECORD, getRecordAsJsonElement(channel.getLatestRecord(), channel.getValueType())); - return jso; - } - - private JsonElement getRecordAsJsonElement(Record record, ValueType valueType) throws ClassCastException { - - return gson.toJsonTree(getRestRecord(record, valueType), RestRecord.class); - } - - private RestRecord getRestRecord(Record rc, ValueType type) throws ClassCastException { - - RestRecord rrc = new RestRecord(); - rrc.setFlag(rc.getFlag()); - rrc.setTimestamp(rc.getTimestamp()); - Value value = rc.getValue(); - - if (rc.getFlag() != Flag.VALID) { - rrc.setValue(null); - } - else { - setRestRecordValue(type, value, rrc); - } - return rrc; - } - - private void setRestRecordValue(ValueType valueType, Value value, RestRecord rrc) throws ClassCastException { - - if (value == null) { - rrc.setValue(null); - } - else { - switch (valueType) { - case FLOAT: - rrc.setValue(value.asFloat()); - break; - case DOUBLE: - rrc.setValue(value.asDouble()); - break; - case SHORT: - rrc.setValue(value.asShort()); - break; - case INTEGER: - rrc.setValue(value.asInt()); - break; - case LONG: - rrc.setValue(value.asLong()); - break; - case BYTE: - rrc.setValue(value.asByte()); - break; - case BOOLEAN: - rrc.setValue(value.asBoolean()); - break; - case BYTE_ARRAY: - rrc.setValue(value.asByteArray()); - break; - case STRING: - rrc.setValue(value.asString()); - break; - default: - rrc.setValue(null); - break; - } - } - } + JsonArray jsa = new JsonArray(); + for (DeviceScanInfo deviceScanInfo : deviceScanInfoList) { + JsonObject jso = new JsonObject(); + jso.addProperty(Const.ID, deviceScanInfo.getId()); + jso.addProperty(Const.DEVICEADDRESS, deviceScanInfo.getDeviceAddress()); + jso.addProperty(Const.SETTINGS, deviceScanInfo.getSettings()); + jso.addProperty(Const.DESCRIPTION, deviceScanInfo.getDescription()); + jsa.add(jso); + } + jsonObject.add(Const.DEVICES, jsa); + } + + public void addChannelScanInfoList(List channelScanInfoList) { + + JsonArray jsa = new JsonArray(); + for (ChannelScanInfo channelScanInfo : channelScanInfoList) { + JsonObject jso = new JsonObject(); + jso.addProperty(Const.CHANNELADDRESS, channelScanInfo.getChannelAddress()); + jso.addProperty(Const.VALUETYPE, channelScanInfo.getValueType().name()); + jso.addProperty(Const.VALUETYPELENGTH, channelScanInfo.getValueTypeLength()); + jso.addProperty(Const.DESCRIPTION, channelScanInfo.getDescription()); + jsa.add(jso); + } + jsonObject.add(Const.CHANNELS, jsa); + } + + public static JsonObject getDriverConfigAsJsonObject(DriverConfig config) { + + RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject(); + } + + public static JsonObject getDeviceConfigAsJsonObject(DeviceConfig config) { + + RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject(); + } + + public static JsonObject getChannelConfigAsJsonObject(ChannelConfig config) { + + RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject(); + } + + private JsonObject channelRecordToJson(Channel channel) throws ClassCastException { + + JsonObject jso = new JsonObject(); + + jso.addProperty(Const.ID, channel.getId()); + jso.add(Const.RECORD, getRecordAsJsonElement(channel.getLatestRecord(), channel.getValueType())); + return jso; + } + + private JsonElement getRecordAsJsonElement(Record record, ValueType valueType) throws ClassCastException { + + return gson.toJsonTree(getRestRecord(record, valueType), RestRecord.class); + } + + private RestRecord getRestRecord(Record rc, ValueType type) throws ClassCastException { + + RestRecord rrc = new RestRecord(); + rrc.setFlag(rc.getFlag()); + rrc.setTimestamp(rc.getTimestamp()); + Value value = rc.getValue(); + + if (rc.getFlag() != Flag.VALID) { + rrc.setValue(null); + } else { + setRestRecordValue(type, value, rrc); + } + return rrc; + } + + private void setRestRecordValue(ValueType valueType, Value value, RestRecord rrc) throws ClassCastException { + + if (value == null) { + rrc.setValue(null); + } else { + switch (valueType) { + case FLOAT: + rrc.setValue(value.asFloat()); + break; + case DOUBLE: + rrc.setValue(value.asDouble()); + break; + case SHORT: + rrc.setValue(value.asShort()); + break; + case INTEGER: + rrc.setValue(value.asInt()); + break; + case LONG: + rrc.setValue(value.asLong()); + break; + case BYTE: + rrc.setValue(value.asByte()); + break; + case BOOLEAN: + rrc.setValue(value.asBoolean()); + break; + case BYTE_ARRAY: + rrc.setValue(value.asByteArray()); + break; + case STRING: + rrc.setValue(value.asString()); + break; + default: + rrc.setValue(null); + break; + } + } + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java index 1698b073..61edb70c 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java @@ -22,21 +22,21 @@ public class MissingJsonObjectException extends Exception { - /** - * - */ - private static final long serialVersionUID = 3245778161912001429L; - private String message = "Searched JsonObject is missing. "; + /** + * + */ + private static final long serialVersionUID = 3245778161912001429L; + private String message = "Searched JsonObject is missing. "; - public MissingJsonObjectException() { - } + public MissingJsonObjectException() { + } - public MissingJsonObjectException(String message) { - this.message = message; - } + public MissingJsonObjectException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java index 0ae115df..ec8e7d9e 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java @@ -22,23 +22,23 @@ public class RestConfigIsNotCorrectException extends Exception { - /** - * - */ - private static final long serialVersionUID = 8768653196104942337L; + /** + * + */ + private static final long serialVersionUID = 8768653196104942337L; - private String message = "Something was wrong in the json config message. "; + private String message = "Something was wrong in the json config message. "; - public RestConfigIsNotCorrectException() { - } + public RestConfigIsNotCorrectException() { + } - public RestConfigIsNotCorrectException(String message) { - this.message = message; - } + public RestConfigIsNotCorrectException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java index a80e174f..0d9a6a8b 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java @@ -25,32 +25,32 @@ public class RestChannel { - private String id; - private ValueType type; - private Record record; + private String id; + private ValueType type; + private Record record; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public ValueType getType() { - return type; - } + public ValueType getType() { + return type; + } - public void setType(ValueType type) { - this.type = type; - } + public void setType(ValueType type) { + this.type = type; + } - public Record getRecord() { - return record; - } + public Record getRecord() { + return record; + } - public void setRecord(Record record) { - this.record = record; - } + public void setRecord(Record record) { + this.record = record; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java index b2ba5bc3..f4a0fd0d 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java @@ -20,155 +20,155 @@ */ package org.openmuc.framework.lib.json.restObjects; -import java.util.List; - import org.openmuc.framework.config.ServerMapping; import org.openmuc.framework.data.ValueType; +import java.util.List; + public class RestChannelConfig { - private String id = null; - private String channelAddress = null; - private String description = null; - private String unit = null; - private ValueType valueType = null; - private Integer valueTypeLength = null; - private Double scalingFactor = null; - private Double valueOffset = null; - private Boolean listening = null; - private Integer samplingInterval = null; - private Integer samplingTimeOffset = null; - private String samplingGroup = null; - private Integer loggingInterval = null; - private Integer loggingTimeOffset = null; - private Boolean disabled = null; - private List serverMappings = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getChannelAddress() { - return channelAddress; - } - - public void setChannelAddress(String channelAddress) { - this.channelAddress = channelAddress; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public ValueType getValueType() { - return valueType; - } - - public void setValueType(ValueType valueType) { - this.valueType = valueType; - } - - public Integer getValueTypeLength() { - return valueTypeLength; - } - - public void setValueTypeLength(Integer valueTypeLength) { - this.valueTypeLength = valueTypeLength; - } - - public Double getScalingFactor() { - return scalingFactor; - } - - public void setScalingFactor(Double scalingFactor) { - this.scalingFactor = scalingFactor; - } - - public Double getValueOffset() { - return valueOffset; - } - - public void setValueOffset(Double valueOffset) { - this.valueOffset = valueOffset; - } - - public Boolean isListening() { - return listening; - } - - public void setListening(Boolean listening) { - this.listening = listening; - } - - public Integer getSamplingInterval() { - return samplingInterval; - } - - public void setSamplingInterval(Integer samplingInterval) { - this.samplingInterval = samplingInterval; - } - - public Integer getSamplingTimeOffset() { - return samplingTimeOffset; - } - - public void setSamplingTimeOffset(Integer samplingTimeOffset) { - this.samplingTimeOffset = samplingTimeOffset; - } - - public String getSamplingGroup() { - return samplingGroup; - } - - public void setSamplingGroup(String samplingGroup) { - this.samplingGroup = samplingGroup; - } - - public Integer getLoggingInterval() { - return loggingInterval; - } + private String id = null; + private String channelAddress = null; + private String description = null; + private String unit = null; + private ValueType valueType = null; + private Integer valueTypeLength = null; + private Double scalingFactor = null; + private Double valueOffset = null; + private Boolean listening = null; + private Integer samplingInterval = null; + private Integer samplingTimeOffset = null; + private String samplingGroup = null; + private Integer loggingInterval = null; + private Integer loggingTimeOffset = null; + private Boolean disabled = null; + private List serverMappings = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getChannelAddress() { + return channelAddress; + } + + public void setChannelAddress(String channelAddress) { + this.channelAddress = channelAddress; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public ValueType getValueType() { + return valueType; + } + + public void setValueType(ValueType valueType) { + this.valueType = valueType; + } + + public Integer getValueTypeLength() { + return valueTypeLength; + } + + public void setValueTypeLength(Integer valueTypeLength) { + this.valueTypeLength = valueTypeLength; + } + + public Double getScalingFactor() { + return scalingFactor; + } + + public void setScalingFactor(Double scalingFactor) { + this.scalingFactor = scalingFactor; + } + + public Double getValueOffset() { + return valueOffset; + } + + public void setValueOffset(Double valueOffset) { + this.valueOffset = valueOffset; + } + + public Boolean isListening() { + return listening; + } + + public void setListening(Boolean listening) { + this.listening = listening; + } + + public Integer getSamplingInterval() { + return samplingInterval; + } + + public void setSamplingInterval(Integer samplingInterval) { + this.samplingInterval = samplingInterval; + } + + public Integer getSamplingTimeOffset() { + return samplingTimeOffset; + } + + public void setSamplingTimeOffset(Integer samplingTimeOffset) { + this.samplingTimeOffset = samplingTimeOffset; + } + + public String getSamplingGroup() { + return samplingGroup; + } + + public void setSamplingGroup(String samplingGroup) { + this.samplingGroup = samplingGroup; + } + + public Integer getLoggingInterval() { + return loggingInterval; + } - public void setLoggingInterval(Integer loggingInterval) { - this.loggingInterval = loggingInterval; - } + public void setLoggingInterval(Integer loggingInterval) { + this.loggingInterval = loggingInterval; + } - public Integer getLoggingTimeOffset() { - return loggingTimeOffset; - } + public Integer getLoggingTimeOffset() { + return loggingTimeOffset; + } - public void setLoggingTimeOffset(Integer loggingTimeOffset) { - this.loggingTimeOffset = loggingTimeOffset; - } + public void setLoggingTimeOffset(Integer loggingTimeOffset) { + this.loggingTimeOffset = loggingTimeOffset; + } - public Boolean isDisabled() { - return disabled; - } + public Boolean isDisabled() { + return disabled; + } - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } - public List getServerMappings() { - return serverMappings; - } + public List getServerMappings() { + return serverMappings; + } - public void setServerMappings(List serverMappings) { - this.serverMappings = serverMappings; - } + public void setServerMappings(List serverMappings) { + this.serverMappings = serverMappings; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java index 8d698f57..b643ea2a 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java @@ -26,59 +26,57 @@ public class RestChannelConfigMapper { - public static RestChannelConfig getRestChannelConfig(ChannelConfig cc) { + public static RestChannelConfig getRestChannelConfig(ChannelConfig cc) { - RestChannelConfig rcc = new RestChannelConfig(); - rcc.setChannelAddress(cc.getChannelAddress()); - rcc.setDescription(cc.getDescription()); - rcc.setDisabled(cc.isDisabled()); - rcc.setId(cc.getId()); - rcc.setListening(cc.isListening()); - rcc.setLoggingInterval(cc.getLoggingInterval()); - rcc.setLoggingTimeOffset(cc.getLoggingTimeOffset()); - rcc.setSamplingGroup(cc.getSamplingGroup()); - rcc.setSamplingInterval(cc.getSamplingInterval()); - rcc.setSamplingTimeOffset(cc.getSamplingTimeOffset()); - rcc.setScalingFactor(cc.getScalingFactor()); - // rcc.setServerMappings(cc.getServerMappings()); - rcc.setUnit(cc.getUnit()); - rcc.setValueOffset(cc.getValueOffset()); - rcc.setValueType(cc.getValueType()); - rcc.setValueTypeLength(cc.getValueTypeLength()); - return rcc; - } + RestChannelConfig rcc = new RestChannelConfig(); + rcc.setChannelAddress(cc.getChannelAddress()); + rcc.setDescription(cc.getDescription()); + rcc.setDisabled(cc.isDisabled()); + rcc.setId(cc.getId()); + rcc.setListening(cc.isListening()); + rcc.setLoggingInterval(cc.getLoggingInterval()); + rcc.setLoggingTimeOffset(cc.getLoggingTimeOffset()); + rcc.setSamplingGroup(cc.getSamplingGroup()); + rcc.setSamplingInterval(cc.getSamplingInterval()); + rcc.setSamplingTimeOffset(cc.getSamplingTimeOffset()); + rcc.setScalingFactor(cc.getScalingFactor()); + // rcc.setServerMappings(cc.getServerMappings()); + rcc.setUnit(cc.getUnit()); + rcc.setValueOffset(cc.getValueOffset()); + rcc.setValueType(cc.getValueType()); + rcc.setValueTypeLength(cc.getValueTypeLength()); + return rcc; + } - public static void setChannelConfig(ChannelConfig cc, RestChannelConfig rcc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setChannelConfig(ChannelConfig cc, RestChannelConfig rcc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (cc == null) { - throw new RestConfigIsNotCorrectException("ChannelConfig is null!"); - } - else { - if (rcc != null) { - if (rcc.getId() != null && !rcc.getId().equals("") && !idFromUrl.equals(rcc.getId())) { - cc.setId(rcc.getId()); - } - cc.setChannelAddress(rcc.getChannelAddress()); - cc.setDescription(rcc.getDescription()); - cc.setDisabled(rcc.isDisabled()); - cc.setListening(rcc.isListening()); - cc.setLoggingInterval(rcc.getLoggingInterval()); - cc.setLoggingTimeOffset(rcc.getLoggingTimeOffset()); - cc.setSamplingGroup(rcc.getSamplingGroup()); - cc.setSamplingInterval(rcc.getSamplingInterval()); - cc.setSamplingTimeOffset(rcc.getSamplingTimeOffset()); - cc.setScalingFactor(rcc.getScalingFactor()); - // cc.setServerMappings(rcc.getServerMappings()); - cc.setUnit(rcc.getUnit()); - cc.setValueOffset(rcc.getValueOffset()); - cc.setValueType(rcc.getValueType()); - cc.setValueTypeLength(rcc.getValueTypeLength()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } - } + if (cc == null) { + throw new RestConfigIsNotCorrectException("ChannelConfig is null!"); + } else { + if (rcc != null) { + if (rcc.getId() != null && !rcc.getId().equals("") && !idFromUrl.equals(rcc.getId())) { + cc.setId(rcc.getId()); + } + cc.setChannelAddress(rcc.getChannelAddress()); + cc.setDescription(rcc.getDescription()); + cc.setDisabled(rcc.isDisabled()); + cc.setListening(rcc.isListening()); + cc.setLoggingInterval(rcc.getLoggingInterval()); + cc.setLoggingTimeOffset(rcc.getLoggingTimeOffset()); + cc.setSamplingGroup(rcc.getSamplingGroup()); + cc.setSamplingInterval(rcc.getSamplingInterval()); + cc.setSamplingTimeOffset(rcc.getSamplingTimeOffset()); + cc.setScalingFactor(rcc.getScalingFactor()); + // cc.setServerMappings(rcc.getServerMappings()); + cc.setUnit(rcc.getUnit()); + cc.setValueOffset(rcc.getValueOffset()); + cc.setValueType(rcc.getValueType()); + cc.setValueTypeLength(rcc.getValueTypeLength()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java index 65b3e304..14977147 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java @@ -22,70 +22,70 @@ public class RestDeviceConfig { - private String id; - private String description = null; - private String deviceAddress = null; - private String settings = null; - private Integer samplingTimeout = null; - private Integer connectRetryInterval = null; - private Boolean disabled = null; - - // Device device = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDeviceAddress() { - return deviceAddress; - } - - public void setDeviceAddress(String deviceAddress) { - this.deviceAddress = deviceAddress; - } - - public String getSettings() { - return settings; - } - - public void setSettings(String settings) { - this.settings = settings; - } - - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - public void setSamplingTimeout(Integer samplingTimeout) { - this.samplingTimeout = samplingTimeout; - } - - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - public void setConnectRetryInterval(Integer connectRetryInterval) { - this.connectRetryInterval = connectRetryInterval; - } - - public Boolean getDisabled() { - return disabled; - } - - public void isDisabled(Boolean disabled) { - this.disabled = disabled; - } + private String id; + private String description = null; + private String deviceAddress = null; + private String settings = null; + private Integer samplingTimeout = null; + private Integer connectRetryInterval = null; + private Boolean disabled = null; + + // Device device = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDeviceAddress() { + return deviceAddress; + } + + public void setDeviceAddress(String deviceAddress) { + this.deviceAddress = deviceAddress; + } + + public String getSettings() { + return settings; + } + + public void setSettings(String settings) { + this.settings = settings; + } + + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + public void setSamplingTimeout(Integer samplingTimeout) { + this.samplingTimeout = samplingTimeout; + } + + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + public void setConnectRetryInterval(Integer connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + } + + public Boolean getDisabled() { + return disabled; + } + + public void isDisabled(Boolean disabled) { + this.disabled = disabled; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java index e205f00c..d7668f3f 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java @@ -26,42 +26,40 @@ public class RestDeviceConfigMapper { - public static RestDeviceConfig getRestDeviceConfig(DeviceConfig dc) { + public static RestDeviceConfig getRestDeviceConfig(DeviceConfig dc) { - RestDeviceConfig rdc = new RestDeviceConfig(); - rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); - rdc.setDescription(dc.getDescription()); - rdc.setDeviceAddress(dc.getDeviceAddress()); - rdc.isDisabled(dc.isDisabled()); - rdc.setId(dc.getId()); - rdc.setSamplingTimeout(dc.getSamplingTimeout()); - rdc.setSettings(dc.getSettings()); - return rdc; - } + RestDeviceConfig rdc = new RestDeviceConfig(); + rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); + rdc.setDescription(dc.getDescription()); + rdc.setDeviceAddress(dc.getDeviceAddress()); + rdc.isDisabled(dc.isDisabled()); + rdc.setId(dc.getId()); + rdc.setSamplingTimeout(dc.getSamplingTimeout()); + rdc.setSettings(dc.getSettings()); + return rdc; + } - public static void setDeviceConfig(DeviceConfig dc, RestDeviceConfig rdc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setDeviceConfig(DeviceConfig dc, RestDeviceConfig rdc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (dc == null) { - throw new RestConfigIsNotCorrectException("DriverConfig is null!"); - } - else { + if (dc == null) { + throw new RestConfigIsNotCorrectException("DriverConfig is null!"); + } else { - if (rdc != null) { - if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { - dc.setId(rdc.getId()); - } - dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); - dc.setDescription(rdc.getDescription()); - dc.setDeviceAddress(rdc.getDeviceAddress()); - dc.setDisabled(rdc.getDisabled()); - dc.setSamplingTimeout(rdc.getSamplingTimeout()); - dc.setSettings(rdc.getSettings()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } + if (rdc != null) { + if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { + dc.setId(rdc.getId()); + } + dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); + dc.setDescription(rdc.getDescription()); + dc.setDeviceAddress(rdc.getDeviceAddress()); + dc.setDisabled(rdc.getDisabled()); + dc.setSamplingTimeout(rdc.getSamplingTimeout()); + dc.setSettings(rdc.getSettings()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } - } + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java index d2b03ef0..1e77ebe0 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java @@ -22,40 +22,40 @@ public class RestDriverConfig { - private String id = ""; - private Integer samplingTimeout = null; - private Integer connectRetryInterval = null; - private Boolean disabled = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - public void setSamplingTimeout(Integer samplingTimeout) { - this.samplingTimeout = samplingTimeout; - } - - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - public void setConnectRetryInterval(Integer connectRetryInterval) { - this.connectRetryInterval = connectRetryInterval; - } - - public Boolean isDisabled() { - return disabled; - } - - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } + private String id = ""; + private Integer samplingTimeout = null; + private Integer connectRetryInterval = null; + private Boolean disabled = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + public void setSamplingTimeout(Integer samplingTimeout) { + this.samplingTimeout = samplingTimeout; + } + + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + public void setConnectRetryInterval(Integer connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + } + + public Boolean isDisabled() { + return disabled; + } + + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java index 3544d767..fc80fdff 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java @@ -26,35 +26,33 @@ public class RestDriverConfigMapper { - public static RestDriverConfig getRestDriverConfig(DriverConfig dc) { + public static RestDriverConfig getRestDriverConfig(DriverConfig dc) { - RestDriverConfig rdc = new RestDriverConfig(); - rdc.setId(dc.getId()); - rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); - rdc.setDisabled(dc.isDisabled()); - rdc.setSamplingTimeout(dc.getSamplingTimeout()); - return rdc; - } + RestDriverConfig rdc = new RestDriverConfig(); + rdc.setId(dc.getId()); + rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); + rdc.setDisabled(dc.isDisabled()); + rdc.setSamplingTimeout(dc.getSamplingTimeout()); + return rdc; + } - public static void setDriverConfig(DriverConfig dc, RestDriverConfig rdc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setDriverConfig(DriverConfig dc, RestDriverConfig rdc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (dc == null) { - throw new RestConfigIsNotCorrectException("DriverConfig is null!"); - } - else { - if (rdc != null) { - if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { - dc.setId(rdc.getId()); - } - dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); - dc.setDisabled(rdc.isDisabled()); - dc.setSamplingTimeout(rdc.getSamplingTimeout()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } + if (dc == null) { + throw new RestConfigIsNotCorrectException("DriverConfig is null!"); + } else { + if (rdc != null) { + if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { + dc.setId(rdc.getId()); + } + dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); + dc.setDisabled(rdc.isDisabled()); + dc.setSamplingTimeout(rdc.getSamplingTimeout()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } - } + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java index 6d89c92f..4809c46f 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java @@ -24,32 +24,32 @@ public class RestRecord { - private Long timestamp; - private Flag flag; - private Object value; + private Long timestamp; + private Flag flag; + private Object value; - public Long getTimestamp() { - return timestamp; - } + public Long getTimestamp() { + return timestamp; + } - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } - public Flag getFlag() { - return flag; - } + public Flag getFlag() { + return flag; + } - public void setFlag(Flag flag) { - this.flag = flag; - } + public void setFlag(Flag flag) { + this.flag = flag; + } - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } } diff --git a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java index 781b0d85..9c491389 100644 --- a/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java +++ b/projects/driver/rest/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java @@ -22,14 +22,14 @@ public class RestValue { - private Object value; + private Object value; - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } } diff --git a/projects/driver/rest/src/main/resources/OSGI-INF/components.xml b/projects/driver/rest/src/main/resources/OSGI-INF/components.xml index 46c51d01..97865f21 100644 --- a/projects/driver/rest/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/rest/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/s7plc/build.gradle b/projects/driver/s7plc/build.gradle index 2a773261..c072d647 100644 --- a/projects/driver/s7plc/build.gradle +++ b/projects/driver/s7plc/build.gradle @@ -1,13 +1,12 @@ - dependencies { - compile project(':openmuc-core-spi') - compile files('dependencies/libnodave-java-1.0.0.jar') + compile project(':openmuc-core-spi') + compile files('dependencies/libnodave-java-1.0.0.jar') } jar { - manifest { - name = "OpenMUC Driver - S7PLC" - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - S7PLC" + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } diff --git a/projects/driver/s7plc/devdoc/meterconfig.xml b/projects/driver/s7plc/devdoc/meterconfig.xml index 6a43eca9..a7005f0c 100644 --- a/projects/driver/s7plc/devdoc/meterconfig.xml +++ b/projects/driver/s7plc/devdoc/meterconfig.xml @@ -1,2685 +1,2678 @@ - - 00000001 - 4e18 - 2 - mbus:usb0:p1 - - - 1m - 09-01-01 00:00:00 - 1-1:1.8.0*255 - - instantaneous - 0.0 - 0.0 - - - - - 00000002 - 4e18 - 2 - mbus:usb0:p2 - - - 1m - 09-01-01 00:00:00 - 1-1:1.8.0*255 - - instantaneous - 0.0 - 0.0 - - - - - 52730060 - 4e18 - 2 - mbus:usb0:p123 - - - 1m - 09-01-01 00:00:00 - 6-1:8.0.0*255 - - mean value - 0.0 - 0.0 - - - - 1m - 09-01-01 00:00:00 - 6-1:9.0.0*255 - - mean value - 0.0 - 0.0 - - - - 1m - 09-01-01 00:00:00 - 6-1:10.0.0*255 - - mean value - 0.0 - 0.0 - - - - 1m - 09-01-01 00:00:00 - 6-1:11.0.0*255 - - mean value - 0.0 - 0.0 - - - - 1m - 09-01-01 00:00:00 - 6-1:12.0.0*255 - - mean value - 0.0 - 0.0 - - - - 1m - 09-01-01 00:00:00 - 6-1:1.0.0*255 - - instantaneous - 0.0 - 0.0 - - - - - 12345678 - CP-343-1 - SIEMENS - 1 - plcs7:10.0.0.7:102 - - - - 1m - - 09-01-01 00:00:00 - DB16.0:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.0:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.0:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(3) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(4) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.1:bit(7) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(3) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(4) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB16.2:bit(5) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.0:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.0:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.0:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(3) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(4) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.1:bit(7) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(3) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(4) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB19.2:bit(5) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.0:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.4:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.6:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.8:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.10:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.12:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.16:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.20:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.24:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.28:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.32:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.36:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.40:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.44:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.48:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.52:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.56:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.60:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.64:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.68:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.72:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.76:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.80:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.84:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.88:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.92:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.96:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.100:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.104:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.108:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.112:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.116:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.120:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB18.124:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.0:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.4:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.6:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.8:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.10:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.12:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.16:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.20:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.24:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.28:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.32:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.36:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.40:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.44:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.48:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.52:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.56:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.60:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.64:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.68:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.72:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.76:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.80:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.84:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.88:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.92:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.96:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.100:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.104:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.108:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.112:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.116:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.120:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB21.124:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.0:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.4:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.8:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.12:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.16:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.20:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.24:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.28:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.32:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.36:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.40:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.44:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.48:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.52:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.56:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB3.60:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB17.0:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB17.2:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB17.4:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB17.6:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB20.0:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB20.2:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB20.4:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB20.6:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(0) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(2) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(3) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(4) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(5) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(6) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.0:bit(7) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(0) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(1) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(2) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(3) - - - mean value - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(4) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(5) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(6) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.1:bit(7) - - - mean value - 0.0 - 0.0 - - - - - - - 1m - - 09-01-01 00:00:00 - DB150.10:float - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.14:float - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.18:bit(0) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.18:bit(1) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.20:uint8 - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.21:uint8 - - - mean value - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB150.22:uint8 - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.23:uint8 - - - mean value - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB31.16:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.20:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.24:float - - - instantaneous - 0.0 - 0.0 - - - - 1m - - 09-01-01 00:00:00 - DB31.28:float - - - instantaneous - 0.0 - 0.0 - - - - 1m - - 09-01-01 00:00:00 - DB31.32:float - - - instantaneous - 0.0 - 0.0 - - - - - - - 1m - - 09-01-01 00:00:00 - DB31.36:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.40:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.44:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.66:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB31.70:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB31.90:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB31.94:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB31.98:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB31.102:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB70.4:float - - - instantaneous - 0.0 - 0.0 - - - - - - - - 1m - - 09-01-01 00:00:00 - DB70.8:float - - - instantaneous - 0.0 - 0.0 - - - - - - - 1m - - 09-01-01 00:00:00 - DB70.12:uint16 - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB70.14:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB70.18:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB106.0:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB106.4:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB106.8:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB106.12:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB101.16:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.0:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.4:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.8:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.12:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.30:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB101.36:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB102.16:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB102.0:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB102.4:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB102.8:float - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB102.12:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.24:uint8 - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB150.19:bit(0) - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB150.19:bit(1) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.19:bit(2) - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.2:float - - - instantaneous - 0.0 - 0.0 - - - - - - - 1m - - 09-01-01 00:00:00 - DB152.24:uint8 - - - mean value - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB152.19:bit(0) - - - mean value - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB152.19:bit(1) - - - mean value - 0.0 - 0.0 - - - - 1m - - 09-01-01 00:00:00 - DB152.19:bit(2) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB152.2:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB152.6:float - - - instantaneous - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.19:bit(7) - - - instantaneous - 0.0 - 0.0 - - - - - - 1m - - 09-01-01 00:00:00 - DB150.18:bit(0) - - - mean value - 0.0 - 0.0 - - - - - 1m - - 09-01-01 00:00:00 - DB150.18:bit(1) - - - mean value - 0.0 - 0.0 - - - - - - - - - - 15m - 09-01-01 00:00:00 - - mean - 0.0 - 0.0 - - + + 00000001 + 4e18 + 2 + mbus:usb0:p1 + + + 1m + 09-01-01 00:00:00 + 1-1:1.8.0*255 + + instantaneous + 0.0 + 0.0 + + + + + 00000002 + 4e18 + 2 + mbus:usb0:p2 + + + 1m + 09-01-01 00:00:00 + 1-1:1.8.0*255 + + instantaneous + 0.0 + 0.0 + + + + + 52730060 + 4e18 + 2 + mbus:usb0:p123 + + + 1m + 09-01-01 00:00:00 + 6-1:8.0.0*255 + + mean value + 0.0 + 0.0 + + + + 1m + 09-01-01 00:00:00 + 6-1:9.0.0*255 + + mean value + 0.0 + 0.0 + + + + 1m + 09-01-01 00:00:00 + 6-1:10.0.0*255 + + mean value + 0.0 + 0.0 + + + + 1m + 09-01-01 00:00:00 + 6-1:11.0.0*255 + + mean value + 0.0 + 0.0 + + + + 1m + 09-01-01 00:00:00 + 6-1:12.0.0*255 + + mean value + 0.0 + 0.0 + + + + 1m + 09-01-01 00:00:00 + 6-1:1.0.0*255 + + instantaneous + 0.0 + 0.0 + + + + + 12345678 + CP-343-1 + SIEMENS + 1 + plcs7:10.0.0.7:102 + + + + 1m + + 09-01-01 00:00:00 + DB16.0:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.0:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.0:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(3) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(4) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.1:bit(7) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(3) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(4) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB16.2:bit(5) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.0:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.0:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.0:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(3) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(4) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.1:bit(7) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(3) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(4) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB19.2:bit(5) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.0:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.4:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.6:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.8:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.10:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.12:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.16:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.20:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.24:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.28:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.32:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.36:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.40:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.44:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.48:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.52:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.56:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.60:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.64:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.68:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.72:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.76:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.80:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.84:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.88:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.92:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.96:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.100:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.104:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.108:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.112:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.116:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.120:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB18.124:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.0:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.4:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.6:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.8:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.10:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.12:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.16:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.20:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.24:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.28:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.32:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.36:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.40:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.44:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.48:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.52:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.56:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.60:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.64:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.68:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.72:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.76:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.80:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.84:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.88:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.92:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.96:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.100:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.104:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.108:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.112:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.116:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.120:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB21.124:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.0:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.4:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.8:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.12:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.16:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.20:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.24:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.28:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.32:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.36:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.40:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.44:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.48:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.52:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.56:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB3.60:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB17.0:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB17.2:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB17.4:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB17.6:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB20.0:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB20.2:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB20.4:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB20.6:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(0) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(2) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(3) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(4) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(5) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(6) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.0:bit(7) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(0) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(1) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(2) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(3) + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(4) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(5) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(6) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.1:bit(7) + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.10:float + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.14:float + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.18:bit(0) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.18:bit(1) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.20:uint8 + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.21:uint8 + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.22:uint8 + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.23:uint8 + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.16:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.20:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.24:float + + + instantaneous + 0.0 + 0.0 + + + + 1m + + 09-01-01 00:00:00 + DB31.28:float + + + instantaneous + 0.0 + 0.0 + + + + 1m + + 09-01-01 00:00:00 + DB31.32:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.36:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.40:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.44:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.66:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.70:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB31.90:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.94:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.98:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB31.102:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB70.4:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB70.8:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB70.12:uint16 + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB70.14:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB70.18:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB106.0:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB106.4:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB106.8:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB106.12:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB101.16:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.0:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.4:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.8:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.12:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.30:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB101.36:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB102.16:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB102.0:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB102.4:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB102.8:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB102.12:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.24:uint8 + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.19:bit(0) + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.19:bit(1) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.19:bit(2) + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.2:float + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB152.24:uint8 + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB152.19:bit(0) + + + mean value + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB152.19:bit(1) + + + mean value + 0.0 + 0.0 + + + + 1m + + 09-01-01 00:00:00 + DB152.19:bit(2) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB152.2:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB152.6:float + + + instantaneous + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.19:bit(7) + + + instantaneous + 0.0 + 0.0 + + + + + + 1m + + 09-01-01 00:00:00 + DB150.18:bit(0) + + + mean value + 0.0 + 0.0 + + + + + 1m + + 09-01-01 00:00:00 + DB150.18:bit(1) + + + mean value + 0.0 + 0.0 + + + + + + + + + 15m + 09-01-01 00:00:00 + + mean + 0.0 + 0.0 + + diff --git a/projects/driver/s7plc/libnodave-java/build.gradle b/projects/driver/s7plc/libnodave-java/build.gradle index 1f6eeb1d..fa27436c 100644 --- a/projects/driver/s7plc/libnodave-java/build.gradle +++ b/projects/driver/s7plc/libnodave-java/build.gradle @@ -16,8 +16,8 @@ String javaInclude = "(none)"; println javaHome; if (javaHome.contains("openjdk")) { - println "OPENJDK detected!" - javaInclude = javaHome.replace("jre", "include"); + println "OPENJDK detected!" + javaInclude = javaHome.replace("jre", "include"); } @@ -28,31 +28,31 @@ println javaInclude; repositories { mavenCentral() } jar { - manifest { - version = project.version - instruction 'Bundle-NativeCode', 'lib/x86/libnodave-native.dll;osname=WindowsXP;osname=WindowsVista;osname=Windows7;processor=x86,lib/x86/liblibnodave-native.so;osname=Linux;processor=x86,lib/arm/liblibnodave-native.so;osname=Linux;processor=arm' - // instruction 'Bundle-NativeCode', 'lib/x86/liblibnodave-native.so' - } + manifest { + version = project.version + instruction 'Bundle-NativeCode', 'lib/x86/libnodave-native.dll;osname=WindowsXP;osname=WindowsVista;osname=Windows7;processor=x86,lib/x86/liblibnodave-native.so;osname=Linux;processor=x86,lib/arm/liblibnodave-native.so;osname=Linux;processor=arm' + // instruction 'Bundle-NativeCode', 'lib/x86/liblibnodave-native.so' + } } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.10' + testCompile group: 'junit', name: 'junit', version: '4.10' } -eclipse.pathVariables([GRADLE_USER_HOME:file(gradle.gradleUserHomeDir)]) +eclipse.pathVariables([GRADLE_USER_HOME: file(gradle.gradleUserHomeDir)]) tasks.eclipse.dependsOn(cleanEclipse) -task compileWrapper(type:Exec) { - // dependsOn(javah) +task compileWrapper(type: Exec) { + // dependsOn(javah) - args '-c', 'native/wrapper/src/main/cpp/libnodave-jni.c', javaInclude, '-Inative/libnodave/', '-Ibuild/classes/main' + args '-c', 'native/wrapper/src/main/cpp/libnodave-jni.c', javaInclude, '-Inative/libnodave/', '-Ibuild/classes/main' - executable 'i586-mingw32msvc-gcc' + executable 'i586-mingw32msvc-gcc' } -task javah(type:Exec) { - workingDir 'build/classes/main' - args '-jni', 'com.libnodave.Interface' - executable 'javah' +task javah(type: Exec) { + workingDir 'build/classes/main' + args '-jni', 'com.libnodave.Interface' + executable 'javah' } diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Demo/NoDaveDemo.ini b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Demo/NoDaveDemo.ini index 741e1d88..67745f1c 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Demo/NoDaveDemo.ini +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Demo/NoDaveDemo.ini @@ -1,14 +1,14 @@ [Connections] -Demo=Demo connection configuration +Demo = Demo connection configuration [Demo] -Protocol=0 -CPURack=0 -CPUSlot=2 -COMPort=COM1 -IPAddress= -Timeout=100000 -Interval=1000 -MPISpeed=2 -MPILocal=0 -MPIRemote=2 +Protocol = 0 +CPURack = 0 +CPUSlot = 2 +COMPort = COM1 +IPAddress = +Timeout = 100000 +Interval = 1000 +MPISpeed = 2 +MPILocal = 0 +MPIRemote = 2 diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ClassList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ClassList.html index 4a2beb97..f04bc183 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ClassList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ClassList.html @@ -1,39 +1,41 @@ - - - List of Classes - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Classes - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +


    diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDave.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDave.html index f9453960..eb19cb26 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDave.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDave.html @@ -1,438 +1,996 @@ - - - Class TNoDave - TNoDave - JADD - Just Another DelphiDoc - - - + + + Class TNoDave - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

    Class TNoDave

    -TObject <-- ... <-- TComponent <-- TNoDave
    +TObject <-- ... <-- TComponent <-- TNoDave
    Declared in Unit NoDaveComponent
    +

    No known Subclasses

    +

    Used by Classes:

    -TNoDaveConnectThread, TNoDaveReadThread
    +TNoDaveConnectThread, TNoDaveReadThread +

    Description:

    The Class TNoDave encapsulates the access to the libnodave.dll of Thomas Hergenhahn. All the settings for the communication are available in the properties of TNoDave. -
    Used in
    Register, TNoDaveConnectThread, TNoDaveReadThread
    +
    +
    Used in
    +
    Register, TNoDaveConnectThread, TNoDaveReadThread

    List of Constructors:

    -
    public constructor Create
    -
    Initialize a new instance of the TNoDave component.
    +
    public constructor Create
    +
    Initialize a new instance of the TNoDave component.

    List of Destructors:

    -
    public destructor Destroy
    -
    Close an active connection and call the inherited Destroy method.
    +
    public destructor Destroy
    +
    Close an active connection and call the inherited Destroy method.

    List of Methods:

    -
    protected function AreaCode
    -
    Determine the S7-ID of an Area.
    -
    protected function BufferAt
    -
    Return a Pointer to the requested PLC-data point within the buffer.
    -
    public procedure Connect
    -
    Open the connection to the PLC.
    -
    public procedure Disconnect
    -
    Close the connection to the PLC.
    -
    protected procedure DoConnect
    -
    Open the connection to the PLC specified by the properties Protocol, CPURack, CPUSlot, -COMPort, IPAddress, IPPort, MPILocal, MPIRemote - and/or MPISpeed
    -
    protected procedure DoOnConnect
    -
    Create the worker-thread for cyclic reading if neccessary and call the OnConnect-eventhandler if specified.
    -
    protected procedure DoOnDisconnect
    -
    Stop and Destroy the worker-thread for cyclic reading if neccessary and call the OnDisconnect-eventhandler if specified.
    -
    protected procedure DoOnError
    -
    Call the OnError-eventhandler if specified.
    -
    protected procedure DoOnRead
    -
    Call the OnRead-eventhandler if specified.
    -
    protected procedure DoOnWrite
    -
    Call the OnWrite-eventhandler if specified.
    -
    protected procedure DoReadBytes
    -
    Read the PLC-data into the buffer.
    -
    public procedure DoSetDebug
    -
    Set the debug-options of the libnodave.dll
    -
    protected procedure DoWriteBytes
    -
    Write the Buffer-data into the PLC.
    -
    protected procedure DoWriteValue
    -
    Write a single value into the specified address of the PLC without changing the properties of the TNoDave-instance.
    -
    public function GetBit
    -
    Return the Bit-value read last from the PLC at the specified address.
    -
    public function GetByte
    -
    Return the Byte-value read last from the PLC at the specified address.
    -
    public function GetDInt
    -
    Return the LongInt-value read last from the PLC at the specified address.
    -
    public function GetDWord
    -
    Return the LongWord-value read last from the PLC at the specified address.
    -
    public function GetErrorMsg
    -
    Return the text message for an error code.
    -
    public function GetFloat
    -
    Return the Float-value read last from the PLC at the specified address.
    -
    public function GetInt
    -
    Return the SmallInt-value read last from the PLC at the specified address.
    -
    public function GetWord
    -
    Return the Word-value read last from the PLC at the specified address.
    -
    public function ListReachablePartners
    -
    Scan the MPI-bus for all reachable partners
    -
    protected procedure Loaded
    -
    Open the connection to the PLC after the instance is completely loaded from the stream and if Active is True.
    -
    public procedure Lock
    -
    Lock the communication-routines for the current tread.
    -
    protected function ProtCode
    -
    Determine the libnodave.dll-code of a protocol
    -
    public procedure ReadBytes
    -
    Read the specified Data from the PLC into the buffer.
    -
    public procedure ReadBytes
    -
    Read the Data specified by the properties Area, DBNumber, BufOffs -and BufLen from the PLC into the buffer.
    -
    public function ReadSZL
    -
    Read a SZL-list from the connected PLC.
    -
    public procedure ResetInterface
    -
    Reset the NetLink-adapter via network-command
    -
    public function Swap16
    -
    Swap the byte-order in a 16-bit value.
    -
    public function Swap32
    -
    Swap the byte-order in a 32-bit value.
    -
    public procedure Unlock
    -
    Unlock the communication-routines for other threads.
    -
    protected procedure WriteBit
    -
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteBit
    -
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteByte
    -
    Write a Byte-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteBytes
    -
    Write the buffer into the PLC at the address specified by the properties Area, DBNumber, -BufOffs and BufLen.
    -
    public procedure WriteBytes
    -
    Write the buffer into the PLC at the specified address after setting up the properties with the given values.
    -
    public procedure WriteDInt
    -
    Write a LongInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteDWord
    -
    Write a LongWord-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteFloat
    -
    Write a Float-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteInt
    -
    Write a SmallInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    -
    public procedure WriteWord
    -
    Write a Word-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    protected function AreaCode
    +
    Determine the S7-ID of an Area.
    +
    protected function BufferAt
    +
    Return a Pointer to the requested PLC-data point within the buffer.
    +
    public procedure Connect
    +
    Open the connection to the PLC.
    +
    public procedure Disconnect
    +
    Close the connection to the PLC.
    +
    protected procedure DoConnect
    +
    Open the connection to the PLC specified by the properties Protocol, CPURack, CPUSlot, + COMPort, IPAddress, IPPort, MPILocal, + MPIRemote + and/or MPISpeed
    +
    protected procedure DoOnConnect
    +
    Create the worker-thread for cyclic reading if neccessary and call the OnConnect-eventhandler if specified.
    +
    protected procedure DoOnDisconnect
    +
    Stop and Destroy the worker-thread for cyclic reading if neccessary and call the OnDisconnect-eventhandler if specified.
    +
    protected procedure DoOnError
    +
    Call the OnError-eventhandler if specified.
    +
    protected procedure DoOnRead
    +
    Call the OnRead-eventhandler if specified.
    +
    protected procedure DoOnWrite
    +
    Call the OnWrite-eventhandler if specified.
    +
    protected procedure DoReadBytes
    +
    Read the PLC-data into the buffer.
    +
    public procedure DoSetDebug
    +
    Set the debug-options of the libnodave.dll
    +
    protected procedure DoWriteBytes
    +
    Write the Buffer-data into the PLC.
    +
    protected procedure DoWriteValue
    +
    Write a single value into the specified address of the PLC without changing the properties of the TNoDave-instance.
    +
    public function GetBit
    +
    Return the Bit-value read last from the PLC at the specified address.
    +
    public function GetByte
    +
    Return the Byte-value read last from the PLC at the specified address.
    +
    public function GetDInt
    +
    Return the LongInt-value read last from the PLC at the specified address.
    +
    public function GetDWord
    +
    Return the LongWord-value read last from the PLC at the specified address.
    +
    public function GetErrorMsg
    +
    Return the text message for an error code.
    +
    public function GetFloat
    +
    Return the Float-value read last from the PLC at the specified address.
    +
    public function GetInt
    +
    Return the SmallInt-value read last from the PLC at the specified address.
    +
    public function GetWord
    +
    Return the Word-value read last from the PLC at the specified address.
    +
    public function ListReachablePartners
    +
    Scan the MPI-bus for all reachable partners
    +
    protected procedure Loaded
    +
    Open the connection to the PLC after the instance is completely loaded from the stream and if Active is True.
    +
    public procedure Lock
    +
    Lock the communication-routines for the current tread.
    +
    protected function ProtCode
    +
    Determine the libnodave.dll-code of a protocol
    +
    public procedure ReadBytes
    +
    Read the specified Data from the PLC into the buffer.
    +
    public procedure ReadBytes
    +
    Read the Data specified by the properties Area, DBNumber, BufOffs + and BufLen from the PLC into the buffer. +
    +
    public function ReadSZL
    +
    Read a SZL-list from the connected PLC.
    +
    public procedure ResetInterface
    +
    Reset the NetLink-adapter via network-command
    +
    public function Swap16
    +
    Swap the byte-order in a 16-bit value.
    +
    public function Swap32
    +
    Swap the byte-order in a 32-bit value.
    +
    public procedure Unlock
    +
    Unlock the communication-routines for other threads.
    +
    protected procedure WriteBit
    +
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteBit
    +
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteByte
    +
    Write a Byte-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteBytes
    +
    Write the buffer into the PLC at the address specified by the properties Area, DBNumber, + BufOffs and BufLen. +
    +
    public procedure WriteBytes
    +
    Write the buffer into the PLC at the specified address after setting up the properties with the given values.
    +
    public procedure WriteDInt
    +
    Write a LongInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteDWord
    +
    Write a LongWord-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteFloat
    +
    Write a Float-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteInt
    +
    Write a SmallInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance.
    +
    public procedure WriteWord
    +
    Write a Word-value into the PLC at the specified address without changing the properties of the TNoDave-instance.

    Properties:

    -
    published property Active: Boolean read GetActive write SetActive
    Property for the connection-status. -
    Used in
    Connect, Disconnect, DoConnect, ListReachablePartners, ReadBytes, ReadSZL, ResetInterface, WriteBytes, TNoDaveConnectThread.Execute, TNoDaveReadThread.Execute
    -

    -
    published property Area: TNoDaveArea read FArea write SetArea
    Property for the PLC-area -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published read-only property Buffer: String read GetBuffer
    Property for the pointer to the internal buffer memory.
    -
    published property BufLen: Integer read FBufLen write SetBufLen
    Property for the length of the buffer. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published property BufOffs: Integer read FBufOffs write SetBufOffs
    Property for the offset of the buffer within the address-range of the PLC. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published property COMPort: String read FComPort write SetComPort
    Property for the name of the COM-Port used for the serial-to-MPI adapter.
    -
    published property COMSpeed: TNoDaveComSpeed read FComSpeed write SetComSpeed
    Property for the speed of the COM-Port used for the serial-to-MPI adapter. -
    Used in
    DoConnect
    -

    -
    published property CPURack: Integer read FCpuRack write SetCpuRack
    Property for the number of the rack containing the CPU of the PLC.
    -
    published property CPUSlot: Integer read FCpuSlot write SetCpuSlot
    Property for the number of the slot containing the CPU of the PLC.
    -
    published read-only property CycleTime: Cardinal read FCycleTime
    Property for the duration in ms of the last communication cycle.
    -
    published property DBNumber: Integer read FDBNumber write SetDBNumber
    Property for the number of the datablock in the PLC. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published property DebugOptions: TNoDaveDebugOptions read GetDebugOptions write SetDebugOptions
    Property for the debug-options.
    -
    published property Interval: Cardinal read FInterval write SetInterval
    Property for the minimal round-trip cycle time for the background-communication with the PLC in milliseconds. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published property IntfName: String read FIntfName write SetIntfName
    Property for the symbolic name of the interface.
    -
    published property IntfTimeout: Integer read FIntfTimeout write SetIntfTimeout
    Property for the timeout of the interface in milliseconds.
    -
    published property IPAddress: String read FIPAddress write SetIPAddress
    Property for the IP-address or name of the TCP/IP partner station.
    -
    published property IPPort: Integer read FIPPort write SetIPPort
    Property for the IP-port of the TCP/IP partner station.
    -
    published read-only property LastErrMsg: String read GetLastErrMsg
    Property for the text describing the code in LastError. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    published read-only property LastError: Integer read FLastError
    Property for the return-code of the last call of a communication-method. -
    Used in
    TNoDaveReadThread.Execute
    -

    -
    public read-only property MaxPDUData: Integer read GetMaxPDUData
    Property for the maximum datasize of one read-request -
    Used in
    DoReadBytes, DoWriteBytes
    -

    -
    published property MPILocal: Integer read FMPILocal write SetMPILocal
    Property for the local MPI-address used for the MPI-communication.
    -
    published property MPIRemote: Integer read FMPIRemote write SetMPIRemote
    Property for the remote MPI-address used for the MPI-communication.
    -
    published property MPISpeed: TNoDaveSpeed read FMPISpeed write SetMPISpeed
    Property for the MPI-speed used for the MPI-communication.
    -
    published property OnConnect: TNotifyEvent read FOnConnect write FOnConnect
    Property for the OnConnect-eventhandler -
    Used in
    DoOnConnect
    -

    -
    published property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect
    Property for the OnDisconnect-eventhandler -
    Used in
    DoOnDisconnect
    -

    -
    published property OnError: TNoDaveOnErrorEvent read FOnError write FOnError
    Property for the OnError-eventhandler -
    Used in
    DoOnError
    -

    -
    published property OnRead: TNotifyEvent read FOnRead write FOnRead
    Property for the OnRead-eventhandler -
    Used in
    DoOnRead
    -

    -
    published property OnWrite: TNotifyEvent read FOnWrite write FOnWrite
    Property for the OnWrite-eventhandler -
    Used in
    DoOnWrite
    -

    -
    published property Protocol: TNoDaveProtocol read FProtocol write SetProtocol
    Property for the Protocol used for the communication with the PLC. -
    Used in
    ResetInterface
    -

    -
    public read-only property SZLCount: Integer read GetSZLCount
    Property for the number of items in the internal SZL-Buffer
    -
    public read-only property SZLItem [Index: Integer]: Pointer read GetSZLItem
    Property for the items in the internal SZL-Buffer
    -
    public read-only property SZLItemSize: Integer read GetSZLItemSize
    Property for the size of one item in the internal SZL-Buffer
    +
    published property Active: Boolean read GetActive + write SetActive +
    +
    Property for the connection-status. +
    +
    Used in
    +
    Connect, Disconnect, DoConnect, ListReachablePartners, ReadBytes, ReadSZL, ResetInterface, WriteBytes, TNoDaveConnectThread.Execute, + TNoDaveReadThread.Execute
    +
    +
    +
    published property Area: TNoDaveArea read FArea write SetArea +
    +
    Property for the PLC-area +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published read-only property + Buffer: String read GetBuffer +
    +
    Property for the pointer to the internal buffer memory.
    +
    published property BufLen: Integer read FBufLen write + SetBufLen +
    +
    Property for the length of the buffer. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published property BufOffs: Integer read FBufOffs write + SetBufOffs +
    +
    Property for the offset of the buffer within the address-range of the PLC. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published property COMPort: String read FComPort write + SetComPort +
    +
    Property for the name of the COM-Port used for the serial-to-MPI adapter.
    +
    published property COMSpeed: TNoDaveComSpeed read FComSpeed write SetComSpeed +
    +
    Property for the speed of the COM-Port used for the serial-to-MPI adapter. +
    +
    Used in
    +
    DoConnect
    +

    +
    published property CPURack: Integer read FCpuRack write + SetCpuRack +
    +
    Property for the number of the rack containing the CPU of the PLC.
    +
    published property CPUSlot: Integer read FCpuSlot write + SetCpuSlot +
    +
    Property for the number of the slot containing the CPU of the PLC.
    +
    published read-only + property CycleTime: Cardinal read FCycleTime +
    +
    Property for the duration in ms of the last communication cycle.
    +
    published property DBNumber: Integer read FDBNumber + write SetDBNumber +
    +
    Property for the number of the datablock in the PLC. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published property DebugOptions: TNoDaveDebugOptions read GetDebugOptions write + SetDebugOptions +
    +
    Property for the debug-options.
    +
    published property Interval: Cardinal read FInterval + write SetInterval +
    +
    Property for the minimal round-trip cycle time for the background-communication with the PLC in milliseconds. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published property IntfName: String read FIntfName + write SetIntfName +
    +
    Property for the symbolic name of the interface.
    +
    published property IntfTimeout: Integer read + FIntfTimeout write SetIntfTimeout +
    +
    Property for the timeout of the interface in milliseconds.
    +
    published property IPAddress: String read + FIPAddress write SetIPAddress +
    +
    Property for the IP-address or name of the TCP/IP partner station.
    +
    published property IPPort: Integer read FIPPort write + SetIPPort +
    +
    Property for the IP-port of the TCP/IP partner station.
    +
    published read-only + property LastErrMsg: String read GetLastErrMsg +
    +
    Property for the text describing the code in LastError. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    published read-only + property LastError: Integer read FLastError +
    +
    Property for the return-code of the last call of a communication-method. +
    +
    Used in
    +
    TNoDaveReadThread.Execute +
    +

    +
    public read-only property + MaxPDUData: Integer read GetMaxPDUData +
    +
    Property for the maximum datasize of one read-request +
    +
    Used in
    +
    DoReadBytes, DoWriteBytes
    +

    +
    published property MPILocal: Integer read FMPILocal + write SetMPILocal +
    +
    Property for the local MPI-address used for the MPI-communication.
    +
    published property MPIRemote: Integer read + FMPIRemote write SetMPIRemote +
    +
    Property for the remote MPI-address used for the MPI-communication.
    +
    published property MPISpeed: TNoDaveSpeed read FMPISpeed write SetMPISpeed +
    +
    Property for the MPI-speed used for the MPI-communication.
    +
    published property OnConnect: TNotifyEvent read + FOnConnect write FOnConnect +
    +
    Property for the OnConnect-eventhandler +
    +
    Used in
    +
    DoOnConnect
    +

    +
    published property OnDisconnect: TNotifyEvent + read FOnDisconnect write FOnDisconnect +
    +
    Property for the OnDisconnect-eventhandler +
    +
    Used in
    +
    DoOnDisconnect
    +

    +
    published property OnError: TNoDaveOnErrorEvent read FOnError write FOnError +
    +
    Property for the OnError-eventhandler +
    +
    Used in
    +
    DoOnError
    +

    +
    published property OnRead: TNotifyEvent read FOnRead + write FOnRead +
    +
    Property for the OnRead-eventhandler +
    +
    Used in
    +
    DoOnRead
    +

    +
    published property OnWrite: TNotifyEvent read + FOnWrite write FOnWrite +
    +
    Property for the OnWrite-eventhandler +
    +
    Used in
    +
    DoOnWrite
    +

    +
    published property Protocol: TNoDaveProtocol read FProtocol write SetProtocol +
    +
    Property for the Protocol used for the communication with the PLC. +
    +
    Used in
    +
    ResetInterface
    +

    +
    public read-only property + SZLCount: Integer read GetSZLCount +
    +
    Property for the number of items in the internal SZL-Buffer
    +
    public read-only property + SZLItem [Index: Integer]: Pointer read GetSZLItem +
    +
    Property for the items in the internal SZL-Buffer
    +
    public read-only property + SZLItemSize: Integer read GetSZLItemSize +
    +
    Property for the size of one item in the internal SZL-Buffer

    Constructors:

    -
    public constructor Create(aOwner: TComponent); override
    Initialize a new instance of the TNoDave component. -
    Parameters
    aOwner
    Owner of the created instance.
    -
    Overrides
    Create
    +
    public constructor Create(aOwner: TComponent); + override
    +
    Initialize a new instance of the TNoDave component. +
    +
    Parameters
    +
    +
    +
    aOwner
    +
    Owner of the created instance.
    +
    +
    +
    Overrides
    +
    Create


    Destructors:

    -
    public destructor Destroy; override
    Close an active connection and call the inherited Destroy method. -
    Overrides
    Destroy
    -

    +
    public destructor Destroy; override
    +
    Close an active connection and call the inherited Destroy method. +
    +
    Overrides
    +
    Destroy
    +
    +

    Methods:

    -
    protected function AreaCode(Area: TNoDaveArea): Integer
    Determine the S7-ID of an Area. -
    Parameters
    Area
    Requested Area.
    -
    Result
    S7-ID of the Area.
    -
    Called by
    DoReadBytes, DoWriteBytes, DoWriteValue, WriteBit
    -

    -
    protected function BufferAt(Address: Integer; Size: Integer = 1; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Pointer
    Return a Pointer to the requested PLC-data point within the buffer. -
    Parameters
    Address
    PLC-Address of the datapoint.
    -
    Size
    Size of the datapoint in bytes.
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    Pointer to the requested data point if the address is located in the buffer, else Nil.
    -
    Called by
    GetBit, GetByte, GetDInt, GetDWord, GetFloat, GetInt, GetWord
    -

    -
    public procedure Connect(Wait: Boolean = True)
    Open the connection to the PLC. -
    Parameters
    Wait
    If False the connection is opened asyncronous in a separate thread. Default is True.
    -
    Called by
    Loaded
    -

    -
    public procedure Disconnect
    Close the connection to the PLC. -
    Called by
    Destroy, TNoDaveReadThread.Execute
    -

    -
    protected procedure DoConnect(OnlyIntf: Boolean = False)
    Open the connection to the PLC specified by the properties Protocol, CPURack, CPUSlot, -COMPort, IPAddress, IPPort, MPILocal, MPIRemote - and/or MPISpeed -
    Parameters
    OnlyIntf
    Open only the interface, don't connect to the PLC
    -
    Called by
    Connect, ResetInterface, TNoDaveConnectThread.Execute
    -

    -
    protected procedure DoOnConnect
    Create the worker-thread for cyclic reading if neccessary and call the OnConnect-eventhandler if specified. -
    Called by
    Connect, TNoDaveConnectThread.DoOnConnect
    -

    -
    protected procedure DoOnDisconnect
    Stop and Destroy the worker-thread for cyclic reading if neccessary and call the OnDisconnect-eventhandler if specified. -
    Called by
    Disconnect
    -

    -
    protected procedure DoOnError(ErrorMsg: String)
    Call the OnError-eventhandler if specified. -
    Parameters
    ErrorMsg
    The text-message for the OnError-event
    -
    Called by
    BufferAt, Connect, Disconnect, DoConnect, DoReadBytes, DoWriteBytes, DoWriteValue, WriteBit, TNoDaveConnectThread.DoOnError, TNoDaveReadThread.DoOnError
    -

    -
    protected procedure DoOnRead
    Call the OnRead-eventhandler if specified. -
    Called by
    ReadBytes, TNoDaveReadThread.DoOnRead
    -

    -
    protected procedure DoOnWrite
    Call the OnWrite-eventhandler if specified. -
    Called by
    WriteBytes
    -

    -
    protected procedure DoReadBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil)
    Read the PLC-data into the buffer. -
    Parameters
    Area
    Requested PLC-area.
    -
    DB
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    -
    Start
    Start-address of the requested data within the address-range of the PLC.
    -
    Size
    Length of the requested PLC-data in bytes.
    -
    Buffer
    Pointer to the buffer. The internal buffer of the instance is used, if Nil (default).
    -
    Called by
    ReadBytes, ReadBytes, TNoDaveReadThread.Execute
    -

    -
    public procedure DoSetDebug(Options: Integer)
    Set the debug-options of the libnodave.dll -
    Parameters
    Options
    Value of the debug-options.
    +
    protected function AreaCode(Area: TNoDaveArea): Integer +
    +
    Determine the S7-ID of an Area. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested Area.
    +
    +
    +
    Result
    +
    S7-ID of the Area.
    +
    Called by
    +
    DoReadBytes, DoWriteBytes, DoWriteValue, + WriteBit
    +

    +
    protected function BufferAt(Address: Integer; Size: Integer + = 1; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Pointer +
    +
    Return a Pointer to the requested PLC-data point within the buffer. +
    +
    Parameters
    +
    +
    +
    Address
    +
    PLC-Address of the datapoint.
    +
    Size
    +
    Size of the datapoint in bytes.
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    Pointer to the requested data point if the address is located in the buffer, else Nil.
    +
    Called by
    +
    GetBit, GetByte, GetDInt, GetDWord, + GetFloat, GetInt, GetWord
    +

    +
    public procedure Connect(Wait: Boolean = True)
    +
    Open the connection to the PLC. +
    +
    Parameters
    +
    +
    +
    Wait
    +
    If False the connection is opened asyncronous in a separate thread. Default is True.
    +
    +
    Called by
    +
    Loaded
    +

    +
    public procedure Disconnect
    +
    Close the connection to the PLC. +
    +
    Called by
    +
    Destroy, TNoDaveReadThread.Execute
    +

    +
    protected procedure DoConnect(OnlyIntf: Boolean = False) +
    +
    Open the connection to the PLC specified by the properties Protocol, CPURack, CPUSlot, + COMPort, IPAddress, IPPort, MPILocal, MPIRemote + and/or MPISpeed +
    +
    Parameters
    +
    +
    +
    OnlyIntf
    +
    Open only the interface, don't connect to the PLC
    +
    +
    Called by
    +
    Connect, ResetInterface, TNoDaveConnectThread.Execute
    +

    +
    protected procedure DoOnConnect
    +
    Create the worker-thread for cyclic reading if neccessary and call the OnConnect-eventhandler if specified. +
    +
    Called by
    +
    Connect, TNoDaveConnectThread.DoOnConnect
    +

    +
    protected procedure DoOnDisconnect
    +
    Stop and Destroy the worker-thread for cyclic reading if neccessary and call the OnDisconnect-eventhandler if specified. +
    +
    Called by
    +
    Disconnect
    +

    +
    protected procedure DoOnError(ErrorMsg: String)
    +
    Call the OnError-eventhandler if specified. +
    +
    Parameters
    +
    +
    +
    ErrorMsg
    +
    The text-message for the OnError-event
    +
    +
    Called by
    +
    BufferAt, Connect, Disconnect, DoConnect, DoReadBytes, DoWriteBytes, DoWriteValue, WriteBit, TNoDaveConnectThread.DoOnError, TNoDaveReadThread.DoOnError
    +

    +
    protected procedure DoOnRead
    +
    Call the OnRead-eventhandler if specified. +
    +
    Called by
    +
    ReadBytes, TNoDaveReadThread.DoOnRead
    +

    +
    protected procedure DoOnWrite
    +
    Call the OnWrite-eventhandler if specified. +
    +
    Called by
    +
    WriteBytes
    +

    +
    protected procedure DoReadBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil) +
    +
    Read the PLC-data into the buffer. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested PLC-area.
    +
    DB
    +
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    +
    Start
    +
    Start-address of the requested data within the address-range of the PLC.
    +
    Size
    +
    Length of the requested PLC-data in bytes.
    +
    Buffer
    +
    Pointer to the buffer. The internal buffer of the instance is used, if Nil (default).
    +
    +
    Called by
    +
    ReadBytes, ReadBytes, TNoDaveReadThread.Execute
    +

    +
    public procedure DoSetDebug(Options: Integer)
    +
    Set the debug-options of the libnodave.dll +
    +
    Parameters
    +
    +
    +
    Options
    +
    Value of the debug-options.

    -
    protected procedure DoWriteBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil)
    Write the Buffer-data into the PLC. -
    Parameters
    Area
    Requested PLC-area.
    -
    DB
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    -
    Start
    Start-address of the requested data within the address-range of the PLC.
    -
    Size
    Length of the requested PLC-data in bytes.
    -
    Buffer
    Pointer to the buffer. The internal buffer of the instance is used, if Nil (default).
    -
    Called by
    WriteBytes, WriteBytes
    -

    -
    protected procedure DoWriteValue(Address, Size: Integer; Value: Pointer)
    Write a single value into the specified address of the PLC without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    PLC-Address of the data point.
    -
    Size
    Size in bytes of the value.
    -
    Value
    The value to be written.
    -
    Called by
    WriteByte, WriteDInt, WriteDWord, WriteFloat, WriteInt, WriteWord
    -

    -
    public function GetBit(Address, Bit: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Boolean
    Return the Bit-value read last from the PLC at the specified address. -
    Parameters
    Address
    Byte-address of the requested value
    -
    Bit
    Bit-address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or False, if the requested address was not found within the buffer.
    -

    -
    public function GetByte(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Byte
    Return the Byte-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -

    -
    public function GetDInt(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): LongInt
    Return the LongInt-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -

    -
    public function GetDWord(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): LongWord
    Return the LongWord-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -

    -
    public function GetErrorMsg(Error: Integer): String
    Return the text message for an error code. -
    Parameters
    Error
    The error code.
    -
    Result
    Text message correspondig to the error code.
    -

    -
    public function GetFloat(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Double
    Return the Float-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -

    -
    public function GetInt(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): SmallInt
    Return the SmallInt-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -

    -
    public function GetWord(Address: Integer; Buffer: Pointer = Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Word
    Return the Word-value read last from the PLC at the specified address. -
    Parameters
    Address
    Address of the requested value
    -
    Buffer
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    -
    BufOffs
    Offset-address of the buffer within the address-range of the PLC.
    -
    BufLen
    Length of the buffer in bytes.
    -
    Result
    The requested value or 0, if the requested address was not found within the buffer.
    -
    Called by
    ReadSZL
    -

    -
    public function ListReachablePartners: TNoDaveReachablePartnersMPI
    Scan the MPI-bus for all reachable partners -
    Result
    List with True for available partners and False for unavailable partners.
    -

    -
    protected procedure Loaded; override
    Open the connection to the PLC after the instance is completely loaded from the stream and if Active is True. -
    Overrides
    Loaded
    -

    -
    public procedure Lock
    Lock the communication-routines for the current tread.
    -
    protected function ProtCode(Prot: TNoDaveProtocol): Integer
    Determine the libnodave.dll-code of a protocol -
    Parameters
    Prot
    The requested protocol
    -
    Result
    The libnodave.dll code for the protocol
    -
    Called by
    DoConnect
    -

    -
    public procedure ReadBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil); overload
    Read the specified Data from the PLC into the buffer. -
    Parameters
    Area
    Requested PLC-area.
    -
    DB
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    -
    Start
    Start-address of the requested data within the address-range of the PLC.
    -
    Size
    Length of the requested PLC-data in bytes.
    -
    Buffer
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    +
    protected procedure DoWriteBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil) +
    +
    Write the Buffer-data into the PLC. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested PLC-area.
    +
    DB
    +
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    +
    Start
    +
    Start-address of the requested data within the address-range of the PLC.
    +
    Size
    +
    Length of the requested PLC-data in bytes.
    +
    Buffer
    +
    Pointer to the buffer. The internal buffer of the instance is used, if Nil (default).
    +
    +
    Called by
    +
    WriteBytes, WriteBytes
    +

    +
    protected procedure DoWriteValue(Address, Size: + Integer; Value: Pointer) +
    +
    Write a single value into the specified address of the PLC without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    PLC-Address of the data point.
    +
    Size
    +
    Size in bytes of the value.
    +
    Value
    +
    The value to be written.
    +
    +
    Called by
    +
    WriteByte, WriteDInt, WriteDWord, WriteFloat, WriteInt, WriteWord
    +

    +
    public function GetBit(Address, Bit: Integer; Buffer: Pointer = + Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Boolean +
    +
    Return the Bit-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the requested value
    +
    Bit
    +
    Bit-address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or False, if the requested address was not found within the buffer.
    +

    +
    public function GetByte(Address: Integer; Buffer: Pointer = Nil; + BufOffs: Integer = 0; BufLen: Integer = 0): Byte +
    +
    Return the Byte-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +

    +
    public function GetDInt(Address: Integer; Buffer: Pointer = Nil; + BufOffs: Integer = 0; BufLen: Integer = 0): LongInt +
    +
    Return the LongInt-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +

    +
    public function GetDWord(Address: Integer; Buffer: Pointer = + Nil; BufOffs: Integer = 0; BufLen: Integer = 0): LongWord +
    +
    Return the LongWord-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +

    +
    public function GetErrorMsg(Error: Integer): String
    +
    Return the text message for an error code. +
    +
    Parameters
    +
    +
    +
    Error
    +
    The error code.
    +
    +
    Result
    +
    Text message correspondig to the error code.
    +

    +
    public function GetFloat(Address: Integer; Buffer: Pointer = + Nil; BufOffs: Integer = 0; BufLen: Integer = 0): Double +
    +
    Return the Float-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +

    +
    public function GetInt(Address: Integer; Buffer: Pointer = Nil; + BufOffs: Integer = 0; BufLen: Integer = 0): SmallInt +
    +
    Return the SmallInt-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +

    +
    public function GetWord(Address: Integer; Buffer: Pointer = Nil; + BufOffs: Integer = 0; BufLen: Integer = 0): Word +
    +
    Return the Word-value read last from the PLC at the specified address. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Address of the requested value
    +
    Buffer
    +
    Pointer to the buffer holding the PLC-data. The internal buffer is used, if Nil (default).
    +
    BufOffs
    +
    Offset-address of the buffer within the address-range of the PLC.
    +
    BufLen
    +
    Length of the buffer in bytes.
    +
    +
    Result
    +
    The requested value or 0, if the requested address was not found within the buffer.
    +
    Called by
    +
    ReadSZL
    +

    +
    public function ListReachablePartners: TNoDaveReachablePartnersMPI
    +
    Scan the MPI-bus for all reachable partners +
    +
    Result
    +
    List with True for available partners and False for unavailable partners.
    +

    +
    protected procedure Loaded; override
    +
    Open the connection to the PLC after the instance is completely loaded from the stream and if Active is True. +
    +
    Overrides
    +
    Loaded
    +

    +
    public procedure Lock
    +
    Lock the communication-routines for the current tread.
    +
    protected function ProtCode(Prot: TNoDaveProtocol): Integer +
    +
    Determine the libnodave.dll-code of a protocol +
    +
    Parameters
    +
    +
    +
    Prot
    +
    The requested protocol
    +
    +
    Result
    +
    The libnodave.dll code for the protocol
    +
    Called by
    +
    DoConnect
    +

    +
    public procedure ReadBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil); + overload
    +
    Read the specified Data from the PLC into the buffer. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested PLC-area.
    +
    DB
    +
    Number of requested datablock. Only used, if reading from Datablocks in the PLC.
    +
    Start
    +
    Start-address of the requested data within the address-range of the PLC.
    +
    Size
    +
    Length of the requested PLC-data in bytes.
    +
    Buffer
    +
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).

    -
    public procedure ReadBytes(Buffer: Pointer = Nil); overload
    Read the Data specified by the properties Area, DBNumber, BufOffs -and BufLen from the PLC into the buffer. -
    Parameters
    Buffer
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    -
    Called by
    DoConnect, ReadBytes
    -

    -
    public function ReadSZL(ID, Index: Integer): Integer
    Read a SZL-list from the connected PLC. -
    Parameters
    ID
    The SZL-ID of the list.
    -
    Index
    The SZL-Index of the list.
    -
    Result
    Error code for the function result, 0 if OK.
    -

    -
    public procedure ResetInterface
    Reset the NetLink-adapter via network-command
    -
    public function Swap16(Value: SmallInt): SmallInt
    Swap the byte-order in a 16-bit value. -
    Parameters
    Value
    The value for the conversion.
    -
    Result
    The converted value.
    -

    -
    public function Swap32(Value: Integer): Integer
    Swap the byte-order in a 32-bit value. -
    Parameters
    Value
    The value for the conversion.
    -
    Result
    The converted value.
    -

    -
    public procedure Unlock
    Unlock the communication-routines for other threads.
    -
    protected procedure WriteBit(Area: TNoDaveArea; DB, Address, Bit: Integer; Value: Boolean); overload
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Area
    Requested PLC-area.
    -
    DB
    Number of requested datablock. Only used, if writing into datablocks of the PLC.
    -
    Address
    Byte-address of the value
    -
    Bit
    Bit-address of the value
    -
    Value
    Value to write into the PLC.
    -
    Called by
    WriteBit
    -

    -
    public procedure WriteBit(Address, Bit: Integer; Value: Boolean); overload
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Bit
    Bit-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure ReadBytes(Buffer: Pointer = Nil); overload +
    +
    Read the Data specified by the properties Area, DBNumber, BufOffs + and BufLen from the PLC into the buffer. +
    +
    Parameters
    +
    +
    +
    Buffer
    +
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    +
    +
    Called by
    +
    DoConnect, ReadBytes
    +

    +
    public function ReadSZL(ID, Index: Integer): Integer
    +
    Read a SZL-list from the connected PLC. +
    +
    Parameters
    +
    +
    +
    ID
    +
    The SZL-ID of the list.
    +
    Index
    +
    The SZL-Index of the list.
    +
    +
    Result
    +
    Error code for the function result, 0 if OK.
    +

    +
    public procedure ResetInterface
    +
    Reset the NetLink-adapter via network-command
    +
    public function Swap16(Value: SmallInt): SmallInt
    +
    Swap the byte-order in a 16-bit value. +
    +
    Parameters
    +
    +
    +
    Value
    +
    The value for the conversion.
    +
    +
    Result
    +
    The converted value.
    +

    +
    public function Swap32(Value: Integer): Integer
    +
    Swap the byte-order in a 32-bit value. +
    +
    Parameters
    +
    +
    +
    Value
    +
    The value for the conversion.
    +
    +
    Result
    +
    The converted value.
    +

    +
    public procedure Unlock
    +
    Unlock the communication-routines for other threads.
    +
    protected procedure WriteBit(Area: TNoDaveArea; DB, Address, Bit: Integer; Value: Boolean); overload
    +
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested PLC-area.
    +
    DB
    +
    Number of requested datablock. Only used, if writing into datablocks of the PLC.
    +
    Address
    +
    Byte-address of the value
    +
    Bit
    +
    Bit-address of the value
    +
    Value
    +
    Value to write into the PLC.
    +
    +
    Called by
    +
    WriteBit
    +

    +
    public procedure WriteBit(Address, Bit: Integer; Value: + Boolean); overload
    +
    Write a Bit-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Bit
    +
    Bit-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteByte(Address: Integer; Value: Byte)
    Write a Byte-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteByte(Address: Integer; Value: Byte) +
    +
    Write a Byte-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteBytes(Buffer: Pointer = Nil); overload
    Write the buffer into the PLC at the address specified by the properties Area, DBNumber, -BufOffs and BufLen. -
    Parameters
    Buffer
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    -
    Called by
    WriteBytes
    -

    -
    public procedure WriteBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil); overload
    Write the buffer into the PLC at the specified address after setting up the properties with the given values. -
    Parameters
    Area
    Requested PLC-area. Changes the property Area.
    -
    DB
    Number of requested datablock. Changes the property DBNumber. Only used, if writing into datablocks of the PLC.
    -
    Start
    Start-address of the buffer within the address-range of the PLC. Changes the property BufOffs.
    -
    Size
    Length of the buffer in bytes. Changes the property BufLen.
    -
    Buffer
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    +
    public procedure WriteBytes(Buffer: Pointer = Nil); + overload
    +
    Write the buffer into the PLC at the address specified by the properties Area, DBNumber, + BufOffs and BufLen. +
    +
    Parameters
    +
    +
    +
    Buffer
    +
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).
    +
    +
    Called by
    +
    WriteBytes
    +

    +
    public procedure WriteBytes(Area: TNoDaveArea; DB, Start, Size: Integer; Buffer: Pointer = Nil); + overload
    +
    Write the buffer into the PLC at the specified address after setting up the properties with the given values. +
    +
    Parameters
    +
    +
    +
    Area
    +
    Requested PLC-area. Changes the property Area.
    +
    DB
    +
    Number of requested datablock. Changes the property DBNumber. Only used, if writing into + datablocks of the PLC. +
    +
    Start
    +
    Start-address of the buffer within the address-range of the PLC. Changes the property BufOffs.
    +
    Size
    +
    Length of the buffer in bytes. Changes the property BufLen.
    +
    Buffer
    +
    Pointer to the buffer for PLC-data. The internal buffer is used, if Nil (default).

    -
    public procedure WriteDInt(Address: Integer; Value: LongInt)
    Write a LongInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteDInt(Address: Integer; Value: LongInt) +
    +
    Write a LongInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteDWord(Address: Integer; Value: LongWord)
    Write a LongWord-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteDWord(Address: Integer; Value: + LongWord) +
    +
    Write a LongWord-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteFloat(Address: Integer; Value: Single)
    Write a Float-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteFloat(Address: Integer; Value: Single) +
    +
    Write a Float-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteInt(Address: Integer; Value: SmallInt)
    Write a SmallInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteInt(Address: Integer; Value: SmallInt) +
    +
    Write a SmallInt-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.

    -
    public procedure WriteWord(Address: Integer; Value: Word)
    Write a Word-value into the PLC at the specified address without changing the properties of the TNoDave-instance. -
    Parameters
    Address
    Byte-address of the value
    -
    Value
    Value to write into the PLC.
    +
    public procedure WriteWord(Address: Integer; Value: Word) +
    +
    Write a Word-value into the PLC at the specified address without changing the properties of the TNoDave-instance. +
    +
    Parameters
    +
    +
    +
    Address
    +
    Byte-address of the value
    +
    Value
    +
    Value to write into the PLC.


    diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveConnectThread.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveConnectThread.html index 5d4569c9..a022904a 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveConnectThread.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveConnectThread.html @@ -1,70 +1,98 @@ - - - Class TNoDaveConnectThread - TNoDave - JADD - Just Another DelphiDoc - - - + + + Class TNoDaveConnectThread - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

    Class TNoDaveConnectThread

    -TObject <-- ... <-- TThread <-- TNoDaveConnectThread
    +TObject <-- ... <-- TThread <-- TNoDaveConnectThread
    Declared in Unit NoDaveComponent
    +

    No known Subclasses

    +

    Not used by any known Class


    Description:

    Worker-thread for asynchronous connecting with the PLC. -
    Used in
    TNoDave.Connect
    +
    +
    Used in
    +
    TNoDave.Connect

    List of Constructors:

    -
    public constructor Create
    -
    Create the worker-thread for asynchronous connecting with the PLC.
    +
    public constructor Create
    +
    Create the worker-thread for asynchronous connecting with the PLC.

    List of Methods:

    -
    protected procedure DoOnConnect
    -
    Synchronization-method for calling the OnConnect-Event of the TNoDave-instance.
    -
    protected procedure DoOnError
    -
    Synchronization-method for calling the OnError-Event of the TNoDave-instance.
    -
    protected procedure Execute
    -
    Open the connection to the PLC.
    +
    protected procedure DoOnConnect
    +
    Synchronization-method for calling the OnConnect-Event of the TNoDave-instance.
    +
    protected procedure DoOnError
    +
    Synchronization-method for calling the OnError-Event of the TNoDave-instance.
    +
    protected procedure Execute
    +
    Open the connection to the PLC.

    Constructors:

    -
    public constructor Create(Target: TNoDave)
    Create the worker-thread for asynchronous connecting with the PLC. -
    Parameters
    Target
    The TNoDave-instance to connect with the PLC.
    -
    Called by
    TNoDave.Connect
    +
    public constructor Create(Target: TNoDave) +
    +
    Create the worker-thread for asynchronous connecting with the PLC. +
    +
    Parameters
    +
    +
    +
    Target
    +
    The TNoDave-instance to connect with the PLC.
    +
    +
    +
    Called by
    +
    TNoDave.Connect


    Methods:

    -
    protected procedure DoOnConnect
    Synchronization-method for calling the OnConnect-Event of the TNoDave-instance. -
    Called by
    Execute
    -

    -
    protected procedure DoOnError
    Synchronization-method for calling the OnError-Event of the TNoDave-instance. -
    Called by
    Execute
    +
    protected procedure DoOnConnect
    +
    Synchronization-method for calling the OnConnect-Event of the TNoDave-instance. +
    +
    Called by
    +
    Execute
    +
    +
    +
    protected procedure DoOnError
    +
    Synchronization-method for calling the OnError-Event of the TNoDave-instance. +
    +
    Called by
    +
    Execute

    -
    protected procedure Execute; override
    Open the connection to the PLC. If successfull then call the OnConnect-Event else call the OnError-Event of the TNoDave-instance. -
    Overrides
    Execute
    +
    protected procedure Execute; override
    +
    Open the connection to the PLC. If successfull then call the OnConnect-Event else call the OnError-Event of the + TNoDave-instance. +
    +
    Overrides
    +
    Execute


    diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveReadThread.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveReadThread.html index 4c924608..c5859f15 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveReadThread.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Class_TNoDaveReadThread.html @@ -1,73 +1,102 @@ - - - Class TNoDaveReadThread - TNoDave - JADD - Just Another DelphiDoc - - - + + + Class TNoDaveReadThread - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

    Class TNoDaveReadThread

    -TObject <-- ... <-- TThread <-- TNoDaveReadThread
    +TObject <-- ... <-- TThread <-- TNoDaveReadThread
    Declared in Unit NoDaveComponent
    +

    No known Subclasses

    +

    Not used by any known Class


    Description:

    Worker-thread for the background-communication with the PLC. -
    Used in
    TNoDave.DoOnConnect
    +
    +
    Used in
    +
    TNoDave.DoOnConnect

    List of Constructors:

    -
    public constructor Create
    -
    Create the worker-thread for the background-communication with the PLC.
    +
    public constructor Create
    +
    Create the worker-thread for the background-communication with the PLC.

    List of Methods:

    -
    protected procedure DoOnError
    -
    Synchronization-method for calling the OnError-Event of the TNoDave-instance.
    -
    protected procedure DoOnRead
    -
    Synchronization-method for calling the OnRead-Event of the TNoDave-instance.
    -
    protected procedure Execute
    -
    Read the data from the PLC, call the OnRead-Event of the TNoDave-instance, wait until the round-trip cycle time is reached and -then start again from the beginning until the Connection of the TNoDave-instance is active.
    +
    protected procedure DoOnError
    +
    Synchronization-method for calling the OnError-Event of the TNoDave-instance.
    +
    protected procedure DoOnRead
    +
    Synchronization-method for calling the OnRead-Event of the TNoDave-instance.
    +
    protected procedure Execute
    +
    Read the data from the PLC, call the OnRead-Event of the TNoDave-instance, wait until the round-trip cycle time is reached and + then start again from the beginning until the Connection of the TNoDave-instance is active. +

    Constructors:

    -
    public constructor Create(Target: TNoDave)
    Create the worker-thread for the background-communication with the PLC. -
    Parameters
    Target
    The TNoDave-instance for the communication with the PLC.
    -
    Called by
    TNoDave.DoOnConnect
    +
    public constructor Create(Target: TNoDave) +
    +
    Create the worker-thread for the background-communication with the PLC. +
    +
    Parameters
    +
    +
    +
    Target
    +
    The TNoDave-instance for the communication with the PLC.
    +
    +
    +
    Called by
    +
    TNoDave.DoOnConnect


    Methods:

    -
    protected procedure DoOnError
    Synchronization-method for calling the OnError-Event of the TNoDave-instance. -
    Called by
    Execute
    -

    -
    protected procedure DoOnRead
    Synchronization-method for calling the OnRead-Event of the TNoDave-instance. -
    Called by
    Execute
    +
    protected procedure DoOnError
    +
    Synchronization-method for calling the OnError-Event of the TNoDave-instance. +
    +
    Called by
    +
    Execute
    +
    +
    +
    protected procedure DoOnRead
    +
    Synchronization-method for calling the OnRead-Event of the TNoDave-instance. +
    +
    Called by
    +
    Execute

    -
    protected procedure Execute; override
    Read the data from the PLC, call the OnRead-Event of the TNoDave-instance, wait until the round-trip cycle time is reached and -then start again from the beginning until the Connection of the TNoDave-instance is active. Disconnect the TNoDave-instance if -the connection is not longer valid. -
    Overrides
    Execute
    +
    protected procedure Execute; override
    +
    Read the data from the PLC, call the OnRead-Event of the TNoDave-instance, wait until the round-trip cycle time is reached + and + then start again from the beginning until the Connection of the TNoDave-instance is active. Disconnect the TNoDave-instance if + the connection is not longer valid. +
    +
    Overrides
    +
    Execute


    diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DelphiDoc.css b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DelphiDoc.css index e73b1cbc..2cfa1ed3 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DelphiDoc.css +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DelphiDoc.css @@ -1,5 +1,6 @@ -span.string { color:#FF0000; } - +span.string { + color: #FF0000; +} /* diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DispInterfaceList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DispInterfaceList.html index bad4f5cd..3fcb0648 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DispInterfaceList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/DispInterfaceList.html @@ -1,25 +1,27 @@ - - - List of Dispatch-Interfaces - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Dispatch-Interfaces - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
      -No types of this kind! + No types of this kind! diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/FileList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/FileList.html index 7bd45166..0f780960 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/FileList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/FileList.html @@ -1,28 +1,32 @@ - - - List of Files - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Files - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/File_NoDaveComponent.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/File_NoDaveComponent.html index ed692a1b..75bc8128 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/File_NoDaveComponent.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/File_NoDaveComponent.html @@ -1,359 +1,649 @@ - - - Unit NoDaveComponent - TNoDave - JADD - Just Another DelphiDoc - - - + + + Unit NoDaveComponent - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Unit NoDaveComponent

      +

      Used Units:

      - Used in interface: System, SysInit, SysUtils, Classes, NoDave, SyncObjs, Windows +Used in interface: System, SysInit, SysUtils, Classes, NoDave, SyncObjs, Windows
      - Used in implementation: None +Used in implementation: None

      Description:

      -
      TODO
      -
      Before Installation:
      +
      +
      TODO
      +
      Before Installation:
      -Please copy the file \pascal\nodave.pas into the directory, where the file nodavecomponent.pas is located !
      -
      + Please copy the file \pascal\nodave.pas into the directory, where the file nodavecomponent.pas is located !
      +
      -Delphi-Installation:
      + Delphi-Installation:
      -1. Select Component - Install in the Delphi-menu
      + 1. Select Component - Install in the Delphi-menu
      -2. Select Add... button
      + 2. Select Add... button
      -3. Select Browse
      + 3. Select Browse
      -4. Select NoDaveComponent.pas
      + 4. Select NoDaveComponent.pas
      -5. Select OK
      -
      + 5. Select OK
      +
      -Lazarus-Installation:
      + Lazarus-Installation:
      -1. Select Components - Open package file
      + 1. Select Components - Open package file
      -2. Select nodavepackage.lpk
      + 2. Select nodavepackage.lpk
      -3. Select Open
      + 3. Select Open
      -4. Select Compile
      + 4. Select Compile
      -5. Select Install
      + 5. Select Install
      -6. Select Yes
      -
      -
      The Unit NoDaveComponent implements the class TNoDave, which encapsulates the access to the libnodave.dll.
      + 6. Select Yes
      +
      +
      +The Unit NoDaveComponent implements the class TNoDave, which encapsulates the access to the libnodave.dll.
      With TNoDave and libnodave.dll it is very easy to read and write data from and to a S7 PLC.

      Simatic, Simatic S5, Simatic S7, S7-200, S7-300, S7-400 are registered Trademarks of Siemens Aktiengesellschaft, Berlin und Muenchen. -
      Author:
      -
      • Axel Kinting - Gebr. Schmid GmbH + Co.
      • -
      +
      +
      Author:
      +
      +
        +
      • Axel Kinting - Gebr. Schmid GmbH + Co.
      • +
      +
      +

      List of Constants:

      - Global Constants: BAF, BUS1F, BUS2F, CRST, daveAnaIn, daveAnaOut, daveComSpeed115_2k, daveComSpeed19_2k, daveComSpeed38_4k, daveComSpeed57_6k, daveComSpeed9_6k, daveCounter, daveDB, daveDebugByte, daveDebugCompare, daveDebugConnect, daveDebugExchange, daveDebugInitAdapter, daveDebugListReachables, daveDebugMPI, daveDebugPacket, daveDebugPassive, daveDebugPDU, daveDebugPrintErrors, daveDebugRawRead, daveDebugRawWrite, daveDebugSpecialChars, daveDebugUpload, daveDI, daveFlags, daveInputs, daveLocal, daveOutputs, daveP, daveProtoAS511, daveProtoIBH, daveProtoIBH_PPI, daveProtoISOTCP, daveProtoISOTCP243, daveProtoMPI, daveProtoMPI2, daveProtoMPI3, daveProtoMPI4, daveProtoNLPro, daveProtoPPI, daveProtoS7Online, daveSpeed1500k, daveSpeed187k, daveSpeed19k, daveSpeed45k, daveSpeed500k, daveSpeed93k, daveSpeed9k, daveSysFlags, daveSysInfo, daveTimer, daveV, EXTF, FRCE, IFM1F, IFM2F, INTF, MSTR, NONE, RACK0, RACK1, RACK2, REDF, RUN, SF, STOP, USR, USR1
      - File-Local Constants: None
      +Global Constants: BAF, BUS1F, BUS2F, CRST, daveAnaIn, daveAnaOut, daveComSpeed115_2k, daveComSpeed19_2k, daveComSpeed38_4k, daveComSpeed57_6k, daveComSpeed9_6k, daveCounter, daveDB, daveDebugByte, daveDebugCompare, daveDebugConnect, +daveDebugExchange, daveDebugInitAdapter, daveDebugListReachables, daveDebugMPI, daveDebugPacket, daveDebugPassive, daveDebugPDU, +daveDebugPrintErrors, daveDebugRawRead, daveDebugRawWrite, daveDebugSpecialChars, daveDebugUpload, daveDI, daveFlags, daveInputs, daveLocal, daveOutputs, daveP, daveProtoAS511, daveProtoIBH, daveProtoIBH_PPI, daveProtoISOTCP, daveProtoISOTCP243, +daveProtoMPI, daveProtoMPI2, daveProtoMPI3, daveProtoMPI4, daveProtoNLPro, daveProtoPPI, daveProtoS7Online, daveSpeed1500k, +daveSpeed187k, daveSpeed19k, daveSpeed45k, daveSpeed500k, daveSpeed93k, daveSpeed9k, daveSysFlags, daveSysInfo, daveTimer, daveV, EXTF, FRCE, IFM1F, IFM2F, +INTF, MSTR, NONE, RACK0, RACK1, RACK2, REDF, RUN, SF, STOP, USR, USR1
      +File-Local Constants: None

      List of Simple Types:

      - Global Simple Types: PSzlBGDiagInfo, PSzlBGIdent, PSzlBGState, PSzlBlockType, PSzlDiagMessage, PSzlLedState, PSzlStationState, PSzlSystemMemory, PSzlUserMemory, TNoDaveArea, TNoDaveComSpeed, TNoDaveDebugOption, TNoDaveDebugOptions, TNoDaveOnErrorEvent, TNoDaveProtocol, TNoDaveReachablePartnersMPI, TNoDaveSpeed, TSzlLed
      - File-Local Simple Types: None
      +Global Simple Types: PSzlBGDiagInfo, PSzlBGIdent, PSzlBGState, PSzlBlockType, PSzlDiagMessage, PSzlLedState, PSzlStationState, +PSzlSystemMemory, PSzlUserMemory, TNoDaveArea, +TNoDaveComSpeed, TNoDaveDebugOption, TNoDaveDebugOptions, +TNoDaveOnErrorEvent, TNoDaveProtocol, TNoDaveReachablePartnersMPI, TNoDaveSpeed, TSzlLed
      +File-Local Simple Types: None

      List of Records:

      - Global Records: TSzlBGDiagInfo, TSzlBGIdent, TSzlBGState, TSzlBlockType, TSzlDiagMessage, TSzlLedState, TSzlStationState, TSzlSystemMemory, TSzlUserMemory
      - File-Local Records: None
      +Global Records: TSzlBGDiagInfo, TSzlBGIdent, +TSzlBGState, TSzlBlockType, TSzlDiagMessage, TSzlLedState, TSzlStationState, TSzlSystemMemory, TSzlUserMemory
      +File-Local Records: None

      List of Classes:

      - Global Classes: TNoDave
      - File-Local Classes: TNoDaveConnectThread, TNoDaveReadThread
      +Global Classes: TNoDave
      +File-Local Classes: TNoDaveConnectThread, TNoDaveReadThread

      List of Functions:

      - Global Functions:
      -
      unit interface procedure Register
      -
      Installation of TNoDave in the component palette
      +Global Functions: +
      +
      unit interface procedure Register
      +
      Installation of TNoDave in the component palette
      - File-Local Functions: None
      +File-Local Functions: None

      Constants:

      -
      unit interface BAF = TSzlLed( 8)
      -
      -
      unit interface BUS1F = TSzlLed( 11)
      -
      -
      unit interface BUS2F = TSzlLed( 12)
      -
      -
      unit interface CRST = TSzlLed( 7)
      -
      -
      unit interface daveAnaIn = TNoDaveArea( 2)
      -
      Analog input words of 200 family -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveAnaOut = TNoDaveArea( 3)
      -
      Analog output words of 200 family -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveComSpeed115_2k = TNoDaveComSpeed( 4)
      -
      -
      Used in
      TNoDave.DoConnect
      -
      -
      unit interface daveComSpeed19_2k = TNoDaveComSpeed( 1)
      -
      -
      Used in
      TNoDave.DoConnect
      -
      -
      unit interface daveComSpeed38_4k = TNoDaveComSpeed( 2)
      -
      -
      Used in
      TNoDave.Create, TNoDave.DoConnect
      -
      -
      unit interface daveComSpeed57_6k = TNoDaveComSpeed( 3)
      -
      -
      Used in
      TNoDave.DoConnect
      -
      -
      unit interface daveComSpeed9_6k = TNoDaveComSpeed( 0)
      -
      -
      Used in
      TNoDave.DoConnect
      -
      -
      unit interface daveCounter = TNoDaveArea( 11)
      -
      Counter -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveDB = TNoDaveArea( 7)
      -
      Data Blocks (global data) -
      Used in
      TNoDave.AreaCode, TNoDave.Create
      -
      -
      unit interface daveDebugByte = TNoDaveDebugOption( 7)
      -
      -
      unit interface daveDebugCompare = TNoDaveDebugOption( 8)
      -
      -
      unit interface daveDebugConnect = TNoDaveDebugOption( 5)
      -
      -
      unit interface daveDebugExchange = TNoDaveDebugOption( 9)
      -
      -
      unit interface daveDebugInitAdapter = TNoDaveDebugOption( 4)
      -
      -
      unit interface daveDebugListReachables = TNoDaveDebugOption( 3)
      -
      -
      unit interface daveDebugMPI = TNoDaveDebugOption( 12)
      -
      -
      unit interface daveDebugPacket = TNoDaveDebugOption( 6)
      -
      -
      unit interface daveDebugPassive = TNoDaveDebugOption( 14)
      -
      -
      unit interface daveDebugPDU = TNoDaveDebugOption( 10)
      -
      -
      unit interface daveDebugPrintErrors = TNoDaveDebugOption( 13)
      -
      -
      unit interface daveDebugRawRead = TNoDaveDebugOption( 0)
      -
      -
      unit interface daveDebugRawWrite = TNoDaveDebugOption( 2)
      -
      -
      unit interface daveDebugSpecialChars = TNoDaveDebugOption( 1)
      -
      -
      unit interface daveDebugUpload = TNoDaveDebugOption( 11)
      -
      -
      unit interface daveDI = TNoDaveArea( 8)
      -
      Data Blocks (instance data) ? -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveFlags = TNoDaveArea( 6)
      -
      Flags/Markers -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveInputs = TNoDaveArea( 4)
      -
      Input memory image -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveLocal = TNoDaveArea( 9)
      -
      Data Blocks (local data) ? -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveOutputs = TNoDaveArea( 5)
      -
      Output memory image -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveP = TNoDaveArea( 13)
      -
      Peripherie Input/Output -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveProtoAS511 = TNoDaveProtocol( 10)
      -
      S5 via programmer-port -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoIBH = TNoDaveProtocol( 7)
      -
      IBH-Link TCP/MPI-Adapter -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode, TNoDave.ResetInterface
      -
      -
      unit interface daveProtoIBH_PPI = TNoDaveProtocol( 8)
      -
      IBH-Link TCP/MPI-Adapter with PPI-Protocol -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode, TNoDave.ResetInterface
      -
      -
      unit interface daveProtoISOTCP = TNoDaveProtocol( 5)
      -
      ISO over TCP -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoISOTCP243 = TNoDaveProtocol( 6)
      -
      ISO over TCP (for CP243) -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoMPI = TNoDaveProtocol( 0)
      -
      MPI-Protocol -
      Used in
      TNoDave.Create, TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoMPI2 = TNoDaveProtocol( 1)
      -
      MPI-Protocol (Andrew's version without STX) -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoMPI3 = TNoDaveProtocol( 2)
      -
      MPI-Protocol (Step 7 Version version) -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoMPI4 = TNoDaveProtocol( 3)
      -
      MPI-Protocol (Andrew's version with STX) -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoNLPro = TNoDaveProtocol( 11)
      -
      Deltalogic NetLink-PRO TCP/MPI-Adapter -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoPPI = TNoDaveProtocol( 4)
      -
      PPI-Protocol -
      Used in
      TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveProtoS7Online = TNoDaveProtocol( 9)
      -
      use S7Onlinx.dll for transport via Siemens CP -
      Used in
      TNoDave.Disconnect, TNoDave.DoConnect, TNoDave.ProtCode
      -
      -
      unit interface daveSpeed1500k = TNoDaveSpeed( 4)
      -
      -
      unit interface daveSpeed187k = TNoDaveSpeed( 2)
      -
      -
      Used in
      TNoDave.Create
      -
      -
      unit interface daveSpeed19k = TNoDaveSpeed( 1)
      -
      -
      unit interface daveSpeed45k = TNoDaveSpeed( 5)
      -
      -
      unit interface daveSpeed500k = TNoDaveSpeed( 3)
      -
      -
      unit interface daveSpeed93k = TNoDaveSpeed( 6)
      -
      -
      unit interface daveSpeed9k = TNoDaveSpeed( 0)
      -
      -
      unit interface daveSysFlags = TNoDaveArea( 1)
      -
      System flag area of 200 family -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveSysInfo = TNoDaveArea( 0)
      -
      System information of 200 family -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveTimer = TNoDaveArea( 12)
      -
      Timer -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface daveV = TNoDaveArea( 10)
      -
      unknown Area -
      Used in
      TNoDave.AreaCode
      -
      -
      unit interface EXTF = TSzlLed( 3)
      -
      -
      unit interface FRCE = TSzlLed( 6)
      -
      -
      unit interface IFM1F = TSzlLed( 18)
      -
      -
      unit interface IFM2F = TSzlLed( 19)
      -
      -
      unit interface INTF = TSzlLed( 2)
      -
      -
      unit interface MSTR = TSzlLed( 14)
      -
      -
      unit interface NONE = TSzlLed( 0)
      -
      -
      unit interface RACK0 = TSzlLed( 15)
      -
      -
      unit interface RACK1 = TSzlLed( 16)
      -
      -
      unit interface RACK2 = TSzlLed( 17)
      -
      -
      unit interface REDF = TSzlLed( 13)
      -
      -
      unit interface RUN = TSzlLed( 4)
      -
      -
      unit interface SF = TSzlLed( 1)
      -
      -
      unit interface STOP = TSzlLed( 5)
      -
      -
      unit interface USR = TSzlLed( 9)
      -
      -
      unit interface USR1 = TSzlLed( 10)
      -
      +
      unit interface BAF = TSzlLed( 8)
      +
      +
      unit interface BUS1F = TSzlLed( 11) +
      +
      +
      unit interface BUS2F = TSzlLed( 12) +
      +
      +
      unit interface CRST = TSzlLed( 7)
      +
      +
      unit interface daveAnaIn = TNoDaveArea( + 2) +
      +
      Analog input words of 200 family +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      +
      unit interface daveAnaOut = TNoDaveArea( + 3) +
      +
      Analog output words of 200 family +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveComSpeed115_2k = TNoDaveComSpeed( 4) +
      +
      +
      +
      Used in
      +
      TNoDave.DoConnect
      +
      +
      unit interface daveComSpeed19_2k = TNoDaveComSpeed( 1) +
      +
      +
      +
      Used in
      +
      TNoDave.DoConnect
      +
      +
      unit interface daveComSpeed38_4k = TNoDaveComSpeed( 2) +
      +
      +
      +
      Used in
      +
      TNoDave.Create, TNoDave.DoConnect
      +
      +
      unit interface daveComSpeed57_6k = TNoDaveComSpeed( 3) +
      +
      +
      +
      Used in
      +
      TNoDave.DoConnect
      +
      +
      unit interface daveComSpeed9_6k = TNoDaveComSpeed( 0) +
      +
      +
      +
      Used in
      +
      TNoDave.DoConnect
      +
      +
      unit interface daveCounter = TNoDaveArea( + 11) +
      +
      Counter +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveDB = TNoDaveArea( + 7) +
      +
      Data Blocks (global data) +
      +
      Used in
      +
      TNoDave.AreaCode, TNoDave.Create
      +
      +
      unit interface daveDebugByte = TNoDaveDebugOption( 7) +
      +
      +
      unit interface daveDebugCompare = TNoDaveDebugOption( 8) +
      +
      +
      unit interface daveDebugConnect = TNoDaveDebugOption( 5) +
      +
      +
      unit interface daveDebugExchange = TNoDaveDebugOption( 9) +
      +
      +
      unit interface daveDebugInitAdapter = TNoDaveDebugOption( 4) +
      +
      +
      unit interface daveDebugListReachables = TNoDaveDebugOption( 3) +
      +
      +
      unit interface daveDebugMPI = TNoDaveDebugOption( 12) +
      +
      +
      unit interface daveDebugPacket = TNoDaveDebugOption( 6) +
      +
      +
      unit interface daveDebugPassive = TNoDaveDebugOption( 14) +
      +
      +
      unit interface daveDebugPDU = TNoDaveDebugOption( 10) +
      +
      +
      unit interface daveDebugPrintErrors = TNoDaveDebugOption( 13) +
      +
      +
      unit interface daveDebugRawRead = TNoDaveDebugOption( 0) +
      +
      +
      unit interface daveDebugRawWrite = TNoDaveDebugOption( 2) +
      +
      +
      unit interface daveDebugSpecialChars = TNoDaveDebugOption( 1) +
      +
      +
      unit interface daveDebugUpload = TNoDaveDebugOption( 11) +
      +
      +
      unit interface daveDI = TNoDaveArea( + 8) +
      +
      Data Blocks (instance data) ? +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveFlags = TNoDaveArea( + 6) +
      +
      Flags/Markers +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveInputs = TNoDaveArea( + 4) +
      +
      Input memory image +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveLocal = TNoDaveArea( + 9) +
      +
      Data Blocks (local data) ? +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveOutputs = TNoDaveArea( + 5) +
      +
      Output memory image +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveP = TNoDaveArea( + 13) +
      +
      Peripherie Input/Output +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveProtoAS511 = TNoDaveProtocol( 10) +
      +
      S5 via programmer-port +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoIBH = TNoDaveProtocol( + 7) +
      +
      IBH-Link TCP/MPI-Adapter +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode, TNoDave.ResetInterface
      +
      +
      unit interface daveProtoIBH_PPI = TNoDaveProtocol( 8) +
      +
      IBH-Link TCP/MPI-Adapter with PPI-Protocol +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode, TNoDave.ResetInterface
      +
      +
      unit interface daveProtoISOTCP = TNoDaveProtocol( 5) +
      +
      ISO over TCP +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoISOTCP243 = TNoDaveProtocol( 6) +
      +
      ISO over TCP (for CP243) +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoMPI = TNoDaveProtocol( + 0) +
      +
      MPI-Protocol +
      +
      Used in
      +
      TNoDave.Create, TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoMPI2 = TNoDaveProtocol( 1) +
      +
      MPI-Protocol (Andrew's version without STX) +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoMPI3 = TNoDaveProtocol( 2) +
      +
      MPI-Protocol (Step 7 Version version) +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoMPI4 = TNoDaveProtocol( 3) +
      +
      MPI-Protocol (Andrew's version with STX) +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoNLPro = TNoDaveProtocol( 11) +
      +
      Deltalogic NetLink-PRO TCP/MPI-Adapter +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoPPI = TNoDaveProtocol( + 4) +
      +
      PPI-Protocol +
      +
      Used in
      +
      TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveProtoS7Online = TNoDaveProtocol( 9) +
      +
      use S7Onlinx.dll for transport via Siemens CP +
      +
      Used in
      +
      TNoDave.Disconnect, TNoDave.DoConnect, TNoDave.ProtCode
      +
      +
      unit interface daveSpeed1500k = TNoDaveSpeed( 4) +
      +
      +
      unit interface daveSpeed187k = TNoDaveSpeed( + 2) +
      +
      +
      +
      Used in
      +
      TNoDave.Create
      +
      +
      unit interface daveSpeed19k = TNoDaveSpeed( + 1) +
      +
      +
      unit interface daveSpeed45k = TNoDaveSpeed( + 5) +
      +
      +
      unit interface daveSpeed500k = TNoDaveSpeed( + 3) +
      +
      +
      unit interface daveSpeed93k = TNoDaveSpeed( + 6) +
      +
      +
      unit interface daveSpeed9k = TNoDaveSpeed( + 0) +
      +
      +
      unit interface daveSysFlags = TNoDaveArea( + 1) +
      +
      System flag area of 200 family +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveSysInfo = TNoDaveArea( + 0) +
      +
      System information of 200 family +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveTimer = TNoDaveArea( + 12) +
      +
      Timer +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface daveV = TNoDaveArea( + 10) +
      +
      unknown Area +
      +
      Used in
      +
      TNoDave.AreaCode
      +
      +
      unit interface EXTF = TSzlLed( 3)
      +
      +
      unit interface FRCE = TSzlLed( 6)
      +
      +
      unit interface IFM1F = TSzlLed( 18)
      +
      +
      unit interface IFM2F = TSzlLed( 19)
      +
      +
      unit interface INTF = TSzlLed( 2)
      +
      +
      unit interface MSTR = TSzlLed( 14)
      +
      +
      unit interface NONE = TSzlLed( 0)
      +
      +
      unit interface RACK0 = TSzlLed( 15)
      +
      +
      unit interface RACK1 = TSzlLed( 16)
      +
      +
      unit interface RACK2 = TSzlLed( 17)
      +
      +
      unit interface REDF = TSzlLed( 13)
      +
      +
      unit interface RUN = TSzlLed( 4)
      +
      +
      unit interface SF = TSzlLed( 1)
      +
      +
      unit interface STOP = TSzlLed( 5)
      +
      +
      unit interface USR = TSzlLed( 9)
      +
      +
      unit interface USR1 = TSzlLed( 10)
      +

      Simple Types:

      -
      unit interface PSzlBGDiagInfo = ^TSzlBGDiagInfo
      -
      -
      unit interface PSzlBGIdent = ^TSzlBGIdent
      -
      -
      unit interface PSzlBGState = ^TSzlBGState
      -
      -
      unit interface PSzlBlockType = TSzlBlockType
      -
      -
      unit interface PSzlDiagMessage = ^TSzlDiagMessage
      -
      -
      unit interface PSzlLedState = ^TSzlLedState
      -
      -
      unit interface PSzlStationState = ^TSzlStationState
      -
      -
      unit interface PSzlSystemMemory = ^TSzlSystemMemory
      -
      -
      unit interface PSzlUserMemory = ^TSzlUserMemory
      -
      -
      unit interface TNoDaveArea = ( daveSysInfo, daveSysFlags, daveAnaIn, daveAnaOut, daveInputs, daveOutputs, daveFlags, daveDB, daveDI, daveLocal, daveV, daveCounter, daveTimer, daveP)
      -
      The area of the PLC-Data for the TNoDave-Component.
      -
      unit interface TNoDaveComSpeed = ( daveComSpeed9_6k, daveComSpeed19_2k, daveComSpeed38_4k, daveComSpeed57_6k, daveComSpeed115_2k)
      -
      The speed of the COM-Port for the TNoDave-Component.
      -
      unit interface TNoDaveDebugOption = ( daveDebugRawRead, daveDebugSpecialChars, daveDebugRawWrite, daveDebugListReachables, daveDebugInitAdapter, daveDebugConnect, daveDebugPacket, daveDebugByte, daveDebugCompare, daveDebugExchange, daveDebugPDU, daveDebugUpload, daveDebugMPI, daveDebugPrintErrors, daveDebugPassive)
      -
      The debug-options for the libnodave.dll
      -
      unit interface TNoDaveDebugOptions = set of TNoDaveDebugOption
      -
      -
      unit interface TNoDaveOnErrorEvent = procedure (Sender: TComponent; ErrorMsg: String) of object
      -
      This is the type of the Event-Handler for the OnError-Event of the TNoDave component. -
      Parameters
      Sender
      The TNoDave-instance which is the source of the event.
      -
      ErrorMsg
      A clear text message describing the error.
      -
      -
      unit interface TNoDaveProtocol = ( daveProtoMPI, daveProtoMPI2, daveProtoMPI3, daveProtoMPI4, daveProtoPPI, daveProtoISOTCP, daveProtoISOTCP243, daveProtoIBH, daveProtoIBH_PPI, daveProtoS7Online, daveProtoAS511, daveProtoNLPro)
      -
      The type of the communication-protocol for the TNoDave-Component.
      -
      unit interface TNoDaveReachablePartnersMPI = array [ 0 .. 126] of Boolean
      -
      List of reachable Partners in the MPI-Network, True = Station is available at this address.
      -
      unit interface TNoDaveSpeed = ( daveSpeed9k, daveSpeed19k, daveSpeed187k, daveSpeed500k, daveSpeed1500k, daveSpeed45k, daveSpeed93k)
      -
      The speed of the MPI-protocol for the TNoDave-Component.
      -
      unit interface TSzlLed = ( NONE, SF, INTF, EXTF, RUN, STOP, FRCE, CRST, BAF, USR, USR1, BUS1F, BUS2F, REDF, MSTR, RACK0, RACK1, RACK2, IFM1F, IFM2F)
      -
      +
      unit interface PSzlBGDiagInfo = ^TSzlBGDiagInfo
      +
      +
      unit interface PSzlBGIdent = ^TSzlBGIdent
      +
      +
      unit interface PSzlBGState = ^TSzlBGState
      +
      +
      unit interface PSzlBlockType = TSzlBlockType
      +
      +
      unit interface PSzlDiagMessage = ^TSzlDiagMessage
      +
      +
      unit interface PSzlLedState = ^TSzlLedState
      +
      +
      unit interface PSzlStationState = ^TSzlStationState
      +
      +
      unit interface PSzlSystemMemory = ^TSzlSystemMemory
      +
      +
      unit interface PSzlUserMemory = ^TSzlUserMemory
      +
      +
      unit interface TNoDaveArea = ( daveSysInfo, + daveSysFlags, daveAnaIn, daveAnaOut, daveInputs, daveOutputs, daveFlags, daveDB, daveDI, daveLocal, daveV, daveCounter, daveTimer, daveP) +
      +
      The area of the PLC-Data for the TNoDave-Component.
      +
      unit interface TNoDaveComSpeed = ( daveComSpeed9_6k, daveComSpeed19_2k, daveComSpeed38_4k, daveComSpeed57_6k, daveComSpeed115_2k) +
      +
      The speed of the COM-Port for the TNoDave-Component.
      +
      unit interface TNoDaveDebugOption = ( daveDebugRawRead, daveDebugSpecialChars, daveDebugRawWrite, daveDebugListReachables, daveDebugInitAdapter, daveDebugConnect, daveDebugPacket, daveDebugByte, daveDebugCompare, + daveDebugExchange, daveDebugPDU, daveDebugUpload, + daveDebugMPI, daveDebugPrintErrors, daveDebugPassive) +
      +
      The debug-options for the libnodave.dll
      +
      unit interface TNoDaveDebugOptions = set + of TNoDaveDebugOption
      +
      +
      unit interface TNoDaveOnErrorEvent = procedure + (Sender: TComponent; ErrorMsg: String) of object
      +
      This is the type of the Event-Handler for the OnError-Event of the TNoDave component. +
      +
      Parameters
      +
      +
      +
      Sender
      +
      The TNoDave-instance which is the source of the event.
      +
      ErrorMsg
      +
      A clear text message describing the error.
      +
      +
      +
      unit interface TNoDaveProtocol = ( daveProtoMPI, daveProtoMPI2, daveProtoMPI3, + daveProtoMPI4, daveProtoPPI, daveProtoISOTCP, daveProtoISOTCP243, daveProtoIBH, daveProtoIBH_PPI, daveProtoS7Online, + daveProtoAS511, daveProtoNLPro) +
      +
      The type of the communication-protocol for the TNoDave-Component.
      +
      unit interface TNoDaveReachablePartnersMPI = + array [ 0 .. 126] of Boolean +
      +
      List of reachable Partners in the MPI-Network, True = Station is available at this address.
      +
      unit interface TNoDaveSpeed = ( daveSpeed9k, + daveSpeed19k, daveSpeed187k, daveSpeed500k, + daveSpeed1500k, daveSpeed45k, daveSpeed93k) +
      +
      The speed of the MPI-protocol for the TNoDave-Component.
      +
      unit interface TSzlLed = ( NONE, SF, INTF, EXTF, RUN, STOP, + FRCE, CRST, BAF, USR, USR1, + BUS1F, BUS2F, REDF, MSTR, RACK0, + RACK1, RACK2, IFM1F, IFM2F) +
      +

      Functions:

      -
      unit interface procedure Register
      -
      Installation of TNoDave in the component palette
      +
      unit interface procedure Register
      +
      Installation of TNoDave in the component palette

      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_A.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_A.html index ead2e748..f4f281b6 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_A.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_A.html @@ -1,31 +1,57 @@ - - - Index of Identifiers and Files starting with "A" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "A" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "A"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      A

      - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveActive
      NoDaveComponentTNoDaveArea
      NoDaveComponentTNoDaveAreaCode
      + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveActive
      NoDaveComponentTNoDaveArea
      NoDaveComponentTNoDaveAreaCode
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_B.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_B.html index 9c60eebf..1b9ccb7a 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_B.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_B.html @@ -1,35 +1,77 @@ - - - Index of Identifiers and Files starting with "B" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "B" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "B"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      B

      - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentBAF
      NoDaveComponentTNoDaveBuffer
      NoDaveComponentTNoDaveBufferAt
      NoDaveComponentTNoDaveBufLen
      NoDaveComponentTNoDaveBufOffs
      NoDaveComponentBUS1F
      NoDaveComponentBUS2F
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentBAF
      NoDaveComponentTNoDaveBuffer
      NoDaveComponentTNoDaveBufferAt
      NoDaveComponentTNoDaveBufLen
      NoDaveComponentTNoDaveBufOffs
      NoDaveComponentBUS1F
      NoDaveComponentBUS2F
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_C.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_C.html index 9eb85092..a6de93e0 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_C.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_C.html @@ -1,38 +1,92 @@ - - - Index of Identifiers and Files starting with "C" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "C" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "C"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      C

      - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveCOMPort
      NoDaveComponentTNoDaveCOMSpeed
      NoDaveComponentTNoDaveConnect
      NoDaveComponentTNoDaveCPURack
      NoDaveComponentTNoDaveCPUSlot
      NoDaveComponentTNoDaveCreate
      NoDaveComponentTNoDaveConnectThreadCreate
      NoDaveComponentTNoDaveReadThreadCreate
      NoDaveComponentCRST
      NoDaveComponentTNoDaveCycleTime
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveCOMPort
      NoDaveComponentTNoDaveCOMSpeed
      NoDaveComponentTNoDaveConnect
      NoDaveComponentTNoDaveCPURack
      NoDaveComponentTNoDaveCPUSlot
      NoDaveComponentTNoDaveCreate
      NoDaveComponentTNoDaveConnectThreadCreate
      NoDaveComponentTNoDaveReadThreadCreate
      NoDaveComponentCRST
      NoDaveComponentTNoDaveCycleTime
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_D.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_D.html index a405241d..86ed9d48 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_D.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_D.html @@ -1,99 +1,397 @@ - - - Index of Identifiers and Files starting with "D" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "D" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "D"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      D

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentdaveAnaIn
      NoDaveComponentdaveAnaOut
      NoDaveComponentdaveComSpeed115_2k
      NoDaveComponentdaveComSpeed19_2k
      NoDaveComponentdaveComSpeed38_4k
      NoDaveComponentdaveComSpeed57_6k
      NoDaveComponentdaveComSpeed9_6k
      NoDaveComponentdaveCounter
      NoDaveComponentdaveDB
      NoDaveComponentdaveDebugByte
      NoDaveComponentdaveDebugCompare
      NoDaveComponentdaveDebugConnect
      NoDaveComponentdaveDebugExchange
      NoDaveComponentdaveDebugInitAdapter
      NoDaveComponentdaveDebugListReachables
      NoDaveComponentdaveDebugMPI
      NoDaveComponentdaveDebugPacket
      NoDaveComponentdaveDebugPassive
      NoDaveComponentdaveDebugPDU
      NoDaveComponentdaveDebugPrintErrors
      NoDaveComponentdaveDebugRawRead
      NoDaveComponentdaveDebugRawWrite
      NoDaveComponentdaveDebugSpecialChars
      NoDaveComponentdaveDebugUpload
      NoDaveComponentdaveDI
      NoDaveComponentdaveFlags
      NoDaveComponentdaveInputs
      NoDaveComponentdaveLocal
      NoDaveComponentdaveOutputs
      NoDaveComponentdaveP
      NoDaveComponentdaveProtoAS511
      NoDaveComponentdaveProtoIBH
      NoDaveComponentdaveProtoIBH_PPI
      NoDaveComponentdaveProtoISOTCP
      NoDaveComponentdaveProtoISOTCP243
      NoDaveComponentdaveProtoMPI
      NoDaveComponentdaveProtoMPI2
      NoDaveComponentdaveProtoMPI3
      NoDaveComponentdaveProtoMPI4
      NoDaveComponentdaveProtoNLPro
      NoDaveComponentdaveProtoPPI
      NoDaveComponentdaveProtoS7Online
      NoDaveComponentdaveSpeed1500k
      NoDaveComponentdaveSpeed187k
      NoDaveComponentdaveSpeed19k
      NoDaveComponentdaveSpeed45k
      NoDaveComponentdaveSpeed500k
      NoDaveComponentdaveSpeed93k
      NoDaveComponentdaveSpeed9k
      NoDaveComponentdaveSysFlags
      NoDaveComponentdaveSysInfo
      NoDaveComponentdaveTimer
      NoDaveComponentdaveV
      NoDaveComponentTNoDaveDBNumber
      NoDaveComponentTNoDaveDebugOptions
      NoDaveComponentTNoDaveDestroy
      NoDaveComponentTNoDaveDisconnect
      NoDaveComponentTNoDaveDoConnect
      NoDaveComponentTNoDaveDoOnConnect
      NoDaveComponentTNoDaveConnectThreadDoOnConnect
      NoDaveComponentTNoDaveDoOnDisconnect
      NoDaveComponentTNoDaveDoOnError
      NoDaveComponentTNoDaveConnectThreadDoOnError
      NoDaveComponentTNoDaveReadThreadDoOnError
      NoDaveComponentTNoDaveDoOnRead
      NoDaveComponentTNoDaveReadThreadDoOnRead
      NoDaveComponentTNoDaveDoOnWrite
      NoDaveComponentTNoDaveDoReadBytes
      NoDaveComponentTNoDaveDoSetDebug
      NoDaveComponentTNoDaveDoWriteBytes
      NoDaveComponentTNoDaveDoWriteValue
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentdaveAnaIn
      NoDaveComponentdaveAnaOut
      NoDaveComponentdaveComSpeed115_2k
      NoDaveComponentdaveComSpeed19_2k
      NoDaveComponentdaveComSpeed38_4k
      NoDaveComponentdaveComSpeed57_6k
      NoDaveComponentdaveComSpeed9_6k
      NoDaveComponentdaveCounter
      NoDaveComponentdaveDB
      NoDaveComponentdaveDebugByte
      NoDaveComponentdaveDebugCompare
      NoDaveComponentdaveDebugConnect
      NoDaveComponentdaveDebugExchange
      NoDaveComponentdaveDebugInitAdapter
      NoDaveComponentdaveDebugListReachables
      NoDaveComponentdaveDebugMPI
      NoDaveComponentdaveDebugPacket
      NoDaveComponentdaveDebugPassive
      NoDaveComponentdaveDebugPDU
      NoDaveComponentdaveDebugPrintErrors
      NoDaveComponentdaveDebugRawRead
      NoDaveComponentdaveDebugRawWrite
      NoDaveComponentdaveDebugSpecialChars
      NoDaveComponentdaveDebugUpload
      NoDaveComponentdaveDI
      NoDaveComponentdaveFlags
      NoDaveComponentdaveInputs
      NoDaveComponentdaveLocal
      NoDaveComponentdaveOutputs
      NoDaveComponentdaveP
      NoDaveComponentdaveProtoAS511
      NoDaveComponentdaveProtoIBH
      NoDaveComponentdaveProtoIBH_PPI
      NoDaveComponentdaveProtoISOTCP
      NoDaveComponentdaveProtoISOTCP243
      NoDaveComponentdaveProtoMPI
      NoDaveComponentdaveProtoMPI2
      NoDaveComponentdaveProtoMPI3
      NoDaveComponentdaveProtoMPI4
      NoDaveComponentdaveProtoNLPro
      NoDaveComponentdaveProtoPPI
      NoDaveComponentdaveProtoS7Online
      NoDaveComponentdaveSpeed1500k
      NoDaveComponentdaveSpeed187k
      NoDaveComponentdaveSpeed19k
      NoDaveComponentdaveSpeed45k
      NoDaveComponentdaveSpeed500k
      NoDaveComponentdaveSpeed93k
      NoDaveComponentdaveSpeed9k
      NoDaveComponentdaveSysFlags
      NoDaveComponentdaveSysInfo
      NoDaveComponentdaveTimer
      NoDaveComponentdaveV
      NoDaveComponentTNoDaveDBNumber
      NoDaveComponentTNoDaveDebugOptions
      NoDaveComponentTNoDaveDestroy
      NoDaveComponentTNoDaveDisconnect
      NoDaveComponentTNoDaveDoConnect
      NoDaveComponentTNoDaveDoOnConnect
      NoDaveComponentTNoDaveConnectThreadDoOnConnect
      NoDaveComponentTNoDaveDoOnDisconnect
      NoDaveComponentTNoDaveDoOnError
      NoDaveComponentTNoDaveConnectThreadDoOnError
      NoDaveComponentTNoDaveReadThreadDoOnError
      NoDaveComponentTNoDaveDoOnRead
      NoDaveComponentTNoDaveReadThreadDoOnRead
      NoDaveComponentTNoDaveDoOnWrite
      NoDaveComponentTNoDaveDoReadBytes
      NoDaveComponentTNoDaveDoSetDebug
      NoDaveComponentTNoDaveDoWriteBytes
      NoDaveComponentTNoDaveDoWriteValue
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_E.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_E.html index db9c10a8..6dda9ebc 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_E.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_E.html @@ -1,31 +1,57 @@ - - - Index of Identifiers and Files starting with "E" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "E" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "E"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      E

      - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveConnectThreadExecute
      NoDaveComponentTNoDaveReadThreadExecute
      NoDaveComponentEXTF
      + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveConnectThreadExecute
      NoDaveComponentTNoDaveReadThreadExecute
      NoDaveComponentEXTF
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_F.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_F.html index 9e336bd6..0a4a0a0a 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_F.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_F.html @@ -1,29 +1,47 @@ - - - Index of Identifiers and Files starting with "F" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "F" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "F"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      F

      - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentFRCE
      + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentFRCE
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_G.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_G.html index 14d5b0d4..4dcaedde 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_G.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_G.html @@ -1,36 +1,82 @@ - - - Index of Identifiers and Files starting with "G" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "G" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "G"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      G

      - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveGetBit
      NoDaveComponentTNoDaveGetByte
      NoDaveComponentTNoDaveGetDInt
      NoDaveComponentTNoDaveGetDWord
      NoDaveComponentTNoDaveGetErrorMsg
      NoDaveComponentTNoDaveGetFloat
      NoDaveComponentTNoDaveGetInt
      NoDaveComponentTNoDaveGetWord
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveGetBit
      NoDaveComponentTNoDaveGetByte
      NoDaveComponentTNoDaveGetDInt
      NoDaveComponentTNoDaveGetDWord
      NoDaveComponentTNoDaveGetErrorMsg
      NoDaveComponentTNoDaveGetFloat
      NoDaveComponentTNoDaveGetInt
      NoDaveComponentTNoDaveGetWord
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_H.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_H.html index 6de3f2d5..bc335f8f 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_H.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_H.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "H" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "H" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "H"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      H

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_I.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_I.html index 772c7046..0fb2258d 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_I.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_I.html @@ -1,36 +1,82 @@ - - - Index of Identifiers and Files starting with "I" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "I" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "I"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      I

      - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentIFM1F
      NoDaveComponentIFM2F
      NoDaveComponentTNoDaveInterval
      NoDaveComponentINTF
      NoDaveComponentTNoDaveIntfName
      NoDaveComponentTNoDaveIntfTimeout
      NoDaveComponentTNoDaveIPAddress
      NoDaveComponentTNoDaveIPPort
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentIFM1F
      NoDaveComponentIFM2F
      NoDaveComponentTNoDaveInterval
      NoDaveComponentINTF
      NoDaveComponentTNoDaveIntfName
      NoDaveComponentTNoDaveIntfTimeout
      NoDaveComponentTNoDaveIPAddress
      NoDaveComponentTNoDaveIPPort
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_J.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_J.html index 07b047b3..31e7f738 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_J.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_J.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "J" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "J" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "J"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      J

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_K.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_K.html index 3f1d8dad..ea94bbb8 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_K.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_K.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "K" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "K" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "K"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      K

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_L.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_L.html index 9831e1b7..f0fc123c 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_L.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_L.html @@ -1,33 +1,67 @@ - - - Index of Identifiers and Files starting with "L" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "L" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "L"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      L

      - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveLastErrMsg
      NoDaveComponentTNoDaveLastError
      NoDaveComponentTNoDaveListReachablePartners
      NoDaveComponentTNoDaveLoaded
      NoDaveComponentTNoDaveLock
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveLastErrMsg
      NoDaveComponentTNoDaveLastError
      NoDaveComponentTNoDaveListReachablePartners
      NoDaveComponentTNoDaveLoaded
      NoDaveComponentTNoDaveLock
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_M.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_M.html index 8a96d761..5ac5ff04 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_M.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_M.html @@ -1,33 +1,67 @@ - - - Index of Identifiers and Files starting with "M" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "M" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "M"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      M

      - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveMaxPDUData
      NoDaveComponentTNoDaveMPILocal
      NoDaveComponentTNoDaveMPIRemote
      NoDaveComponentTNoDaveMPISpeed
      NoDaveComponentMSTR
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveMaxPDUData
      NoDaveComponentTNoDaveMPILocal
      NoDaveComponentTNoDaveMPIRemote
      NoDaveComponentTNoDaveMPISpeed
      NoDaveComponentMSTR
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_N.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_N.html index 0e812a12..8dee17b0 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_N.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_N.html @@ -1,30 +1,52 @@ - - - Index of Identifiers and Files starting with "N" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "N" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "N"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      N

      - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponent
      NoDaveComponentNONE
      + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponent
      NoDaveComponentNONE
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_O.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_O.html index bcd3f617..0a30ce3b 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_O.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_O.html @@ -1,33 +1,67 @@ - - - Index of Identifiers and Files starting with "O" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "O" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "O"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      O

      - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveOnConnect
      NoDaveComponentTNoDaveOnDisconnect
      NoDaveComponentTNoDaveOnError
      NoDaveComponentTNoDaveOnRead
      NoDaveComponentTNoDaveOnWrite
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveOnConnect
      NoDaveComponentTNoDaveOnDisconnect
      NoDaveComponentTNoDaveOnError
      NoDaveComponentTNoDaveOnRead
      NoDaveComponentTNoDaveOnWrite
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_P.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_P.html index 98a7ec58..f6b25e6e 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_P.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_P.html @@ -1,39 +1,97 @@ - - - Index of Identifiers and Files starting with "P" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "P" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "P"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      P

      - - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveProtCode
      NoDaveComponentTNoDaveProtocol
      NoDaveComponentPSzlBGDiagInfo
      NoDaveComponentPSzlBGIdent
      NoDaveComponentPSzlBGState
      NoDaveComponentPSzlBlockType
      NoDaveComponentPSzlDiagMessage
      NoDaveComponentPSzlLedState
      NoDaveComponentPSzlStationState
      NoDaveComponentPSzlSystemMemory
      NoDaveComponentPSzlUserMemory
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveProtCode
      NoDaveComponentTNoDaveProtocol
      NoDaveComponentPSzlBGDiagInfo
      NoDaveComponentPSzlBGIdent
      NoDaveComponentPSzlBGState
      NoDaveComponentPSzlBlockType
      NoDaveComponentPSzlDiagMessage
      NoDaveComponentPSzlLedState
      NoDaveComponentPSzlStationState
      NoDaveComponentPSzlSystemMemory
      NoDaveComponentPSzlUserMemory
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Q.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Q.html index 9f83b1dd..9fdfdb42 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Q.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Q.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "Q" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "Q" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "Q"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      Q

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_R.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_R.html index e6635b2c..04887b97 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_R.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_R.html @@ -1,38 +1,92 @@ - - - Index of Identifiers and Files starting with "R" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "R" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "R"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      R

      - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentRACK0
      NoDaveComponentRACK1
      NoDaveComponentRACK2
      NoDaveComponentTNoDaveReadBytes
      NoDaveComponentTNoDaveReadBytes
      NoDaveComponentTNoDaveReadSZL
      NoDaveComponentREDF
      NoDaveComponentRegister
      NoDaveComponentTNoDaveResetInterface
      NoDaveComponentRUN
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentRACK0
      NoDaveComponentRACK1
      NoDaveComponentRACK2
      NoDaveComponentTNoDaveReadBytes
      NoDaveComponentTNoDaveReadBytes
      NoDaveComponentTNoDaveReadSZL
      NoDaveComponentREDF
      NoDaveComponentRegister
      NoDaveComponentTNoDaveResetInterface
      NoDaveComponentRUN
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_S.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_S.html index ba6530a3..a61dd494 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_S.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_S.html @@ -1,35 +1,77 @@ - - - Index of Identifiers and Files starting with "S" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "S" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "S"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      S

      - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentSF
      NoDaveComponentSTOP
      NoDaveComponentTNoDaveSwap16
      NoDaveComponentTNoDaveSwap32
      NoDaveComponentTNoDaveSZLCount
      NoDaveComponentTNoDaveSZLItem
      NoDaveComponentTNoDaveSZLItemSize
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentSF
      NoDaveComponentSTOP
      NoDaveComponentTNoDaveSwap16
      NoDaveComponentTNoDaveSwap32
      NoDaveComponentTNoDaveSZLCount
      NoDaveComponentTNoDaveSZLItem
      NoDaveComponentTNoDaveSZLItemSize
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_T.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_T.html index 8573bda0..cace3d8d 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_T.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_T.html @@ -1,49 +1,147 @@ - - - Index of Identifiers and Files starting with "T" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "T" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "T"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      T

      - - - - - - - - - - - - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDave
      NoDaveComponentTNoDaveArea
      NoDaveComponentTNoDaveComSpeed
      NoDaveComponentTNoDaveConnectThread
      NoDaveComponentTNoDaveDebugOption
      NoDaveComponentTNoDaveDebugOptions
      NoDaveComponentTNoDaveOnErrorEvent
      NoDaveComponentTNoDaveProtocol
      NoDaveComponentTNoDaveReachablePartnersMPI
      NoDaveComponentTNoDaveReadThread
      NoDaveComponentTNoDaveSpeed
      NoDaveComponentTSzlBGDiagInfo
      NoDaveComponentTSzlBGIdent
      NoDaveComponentTSzlBGState
      NoDaveComponentTSzlBlockType
      NoDaveComponentTSzlDiagMessage
      NoDaveComponentTSzlLed
      NoDaveComponentTSzlLedState
      NoDaveComponentTSzlStationState
      NoDaveComponentTSzlSystemMemory
      NoDaveComponentTSzlUserMemory
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDave
      NoDaveComponentTNoDaveArea
      NoDaveComponentTNoDaveComSpeed
      NoDaveComponentTNoDaveConnectThread
      NoDaveComponentTNoDaveDebugOption
      NoDaveComponentTNoDaveDebugOptions
      NoDaveComponentTNoDaveOnErrorEvent
      NoDaveComponentTNoDaveProtocol
      NoDaveComponentTNoDaveReachablePartnersMPI
      NoDaveComponentTNoDaveReadThread
      NoDaveComponentTNoDaveSpeed
      NoDaveComponentTSzlBGDiagInfo
      NoDaveComponentTSzlBGIdent
      NoDaveComponentTSzlBGState
      NoDaveComponentTSzlBlockType
      NoDaveComponentTSzlDiagMessage
      NoDaveComponentTSzlLed
      NoDaveComponentTSzlLedState
      NoDaveComponentTSzlStationState
      NoDaveComponentTSzlSystemMemory
      NoDaveComponentTSzlUserMemory
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_U.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_U.html index 6b8c1eab..c67f7e4a 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_U.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_U.html @@ -1,31 +1,57 @@ - - - Index of Identifiers and Files starting with "U" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "U" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "U"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      U

      - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveUnlock
      NoDaveComponentUSR
      NoDaveComponentUSR1
      + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveUnlock
      NoDaveComponentUSR
      NoDaveComponentUSR1
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_V.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_V.html index 6bc1fcbd..43587cc0 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_V.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_V.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "V" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "V" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "V"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      V

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_W.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_W.html index b5d1c059..7650967e 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_W.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_W.html @@ -1,38 +1,92 @@ - - - Index of Identifiers and Files starting with "W" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "W" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "W"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      W

      - - - - - - - - - - - +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveWriteBit
      NoDaveComponentTNoDaveWriteBit
      NoDaveComponentTNoDaveWriteByte
      NoDaveComponentTNoDaveWriteBytes
      NoDaveComponentTNoDaveWriteBytes
      NoDaveComponentTNoDaveWriteDInt
      NoDaveComponentTNoDaveWriteDWord
      NoDaveComponentTNoDaveWriteFloat
      NoDaveComponentTNoDaveWriteInt
      NoDaveComponentTNoDaveWriteWord
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FileRecord-Like TypeIdentifier
      NoDaveComponentTNoDaveWriteBit
      NoDaveComponentTNoDaveWriteBit
      NoDaveComponentTNoDaveWriteByte
      NoDaveComponentTNoDaveWriteBytes
      NoDaveComponentTNoDaveWriteBytes
      NoDaveComponentTNoDaveWriteDInt
      NoDaveComponentTNoDaveWriteDWord
      NoDaveComponentTNoDaveWriteFloat
      NoDaveComponentTNoDaveWriteInt
      NoDaveComponentTNoDaveWriteWord
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_X.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_X.html index 1ec0f0a6..99dca6e8 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_X.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_X.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "X" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "X" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "X"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      X

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Y.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Y.html index 8cf4a857..c52b2dac 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Y.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Y.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "Y" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "Y" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "Y"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      Y

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Z.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Z.html index 29aa1ac9..4fed5a19 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Z.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index_Z.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "Z" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "Z" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "Z"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      Z

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index__.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index__.html index 5c5829fd..e1c4f2a3 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index__.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/Index__.html @@ -1,28 +1,42 @@ - - - Index of Identifiers and Files starting with "_" - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Identifiers and Files starting with "_" - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

      Index of Identifiers and Files starting with "_"

      -A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +

      _

      - +
      FileRecord-Like TypeIdentifier
      + + + + +
      FileRecord-Like TypeIdentifier
      diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/InterfaceList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/InterfaceList.html index 53af8a06..540e1fdf 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/InterfaceList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/InterfaceList.html @@ -1,25 +1,27 @@ - - - List of Interfaces - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Interfaces - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
        -No types of this kind! + No types of this kind! diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ObjectList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ObjectList.html index a8daed1c..d581bf4e 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ObjectList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/ObjectList.html @@ -1,25 +1,27 @@ - - - List of Objects - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Objects - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
          -No types of this kind! + No types of this kind! diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/RecordList.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/RecordList.html index 5051a74f..980a4c5a 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/RecordList.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/RecordList.html @@ -1,47 +1,49 @@ - - - List of Records - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of Records - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/TODO.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/TODO.html index 640b03c7..763294b3 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/TODO.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/TODO.html @@ -1,28 +1,32 @@ - - - List of unfinished Identifiers - TNoDave - JADD - Just Another DelphiDoc - - - + + + List of unfinished Identifiers - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +

          List of unfinished Identifiers

          List of unfinished files.

          -

          List of unfinished files

          + + +

          List of unfinished files

          NoDaveComponent

          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/index.html b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/index.html index b0b8d184..ca96dc65 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/index.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/DelphiComponent/Html/index.html @@ -1,23 +1,25 @@ - - - Index of Documentation - TNoDave - JADD - Just Another DelphiDoc - - - + + + Index of Documentation - TNoDave - JADD - Just Another DelphiDoc + + + - - - - - - - - - + + + + + + + + + + +
          This is the index of the documentation generated by JADD - Just Another DelphiDoc.
          Documentation has been generated at 10:53:29 on Mittwoch, 8. März 2006.
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/ARMprocessors.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/ARMprocessors.html index f5f4d0d3..a07ce2f7 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/ARMprocessors.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/ARMprocessors.html @@ -3,7 +3,7 @@

          Compiling Libnodave for ARM processors

          non word boundary (odd address). The following code did not work:
               ((PDUHeader*)p->header)->plen=daveSwapIed_16(len);
          -
          + Here the pointer p->header has been set two an odd address. The offset of plen in the structure PDUHeader is even, hence the resulting pointer points at an odd address. The ARM seems to take the previous lower word boundary instead of the calculated address. diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/FAQ.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/FAQ.html index 87b30eb8..ccb1351b 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/FAQ.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/FAQ.html @@ -1,30 +1,37 @@ - + - - -

          LIBNODAVE FAQ

          + + +

          LIBNODAVE FAQ

          Q: Can you give me a documentation about MPI protocol?

          A: Here's what I know

          Q: That warning on LIBNODAVE home page, does it mean the software is so dangerous/unreliable?

          -A: No, it's just there to prevent anybody from holding me responsible for whatever he might do with it. I trust my software. But I heard, in USA a manufacturer of ladders had to put a label on them saying: "Use on firm ground only" and another one: "Do not use on frozen dung." +A: No, it's just there to prevent anybody from holding me responsible for whatever he might do with it. I trust my software. But I heard, in +USA a manufacturer of ladders had to put a label on them saying: "Use on firm ground only" and another one: "Do not use on frozen dung."

          Q: Why doesn't LIBNODAVE work with my MPI adapter?

          -A: Haven't heard this for quite while. If you have difficulties, first send me the output from testMPI, once started with and once without the option -2. Also include the exact order code of the adapter. I probably can help if I can provide such an adapter. If not, you may think about giving me access to your computer or sending me the adapter. +A: Haven't heard this for quite while. If you have difficulties, first send me the output from testMPI, once started with and once without +the option -2. Also include the exact order code of the adapter. I probably can help if I can provide such an adapter. If not, you may think +about giving me access to your computer or sending me the adapter.

          Q: Can LIBNODAVE work with CP 5x1x?

          -A: No, it can't. The reason is that there is no documentation for this hardware that would allow to write drivers for it. There are commercial products that use the drivers that are installed with Step7 or other Siemens software. But they are for Windows only.
          +A: No, it can't. The reason is that there is no documentation for this hardware that would allow to write drivers for it. There are +commercial products that use the drivers that are installed with Step7 or other Siemens software. But they are for Windows only.
          I guess a speedy USB to MPI adapter could make this hardware obsolete.

          Q: How can I support the development of LIBNODAVE?

          A: Give feedback. I should like to be able to put as many order codes of supported hard ware on the list as possible.
          Donations in hardware or money are allways very welcome.

          Q: I want to use LIBNODAVE for my project, but will it support future hardware?

          -A: It does what it does and it is absolutely unlikely that it could fail with future members of S7 family or compatibles. Naturally, I cannot speak about an immaginary S9... +A: It does what it does and it is absolutely unlikely that it could fail with future members of S7 family or compatibles. Naturally, I +cannot speak about an immaginary S9...

          Q: What is the largest block of bytes LIBNODAVE can read/write to a PLC?

          -A: This is limited by the maximum length of a PDU, which in turn depends on your CPU type.For 240 byte PDU length, you can read 222 bytes and write 218 bytes in a single transaction. +A: This is limited by the maximum length of a PDU, which in turn depends on your CPU type.For 240 byte PDU length, +you can read 222 bytes and write 218 bytes in a single transaction.

          Q: The xy software can write larger blocks, or?

          A: No,whichever software hides that limit from you has to split larger blocks into multiple requests.

          Q: Why don't you do that automatically also in LIBNODAVE?

          -A: LIBNODAVE is for programmers. They will be easily available to do it themselves. On the other hand, automatic splitting would hide a limit that costs performance... +A: LIBNODAVE is for programmers. They will be easily available to do it themselves. On the other hand, automatic splitting would hide +a limit that costs performance... \ No newline at end of file diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/MPI.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/MPI.html index 6e3adb22..22435487 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/MPI.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/MPI.html @@ -5,7 +5,8 @@

          Physical Layer

          Want to "sniff" MPI? Set your PLC's MPI speed to 19.2, because this is the only baudrate also supported by PC UARTs. Prepare a ribbon cable with one male and to female Sub-D connectors. Plug it into the PLCs MPI connector, an MPI adapter or CP5x1x into one female and an RS485/RS232 converter or PPI cable into the other one. Now your PC can listen!

          Media Arbitration

          MPI is basically a variety of Profibus, using the FDL profile.
          -Profibus is a token ring. One master at a time is in posession of the "token", which entitles it to send requests to other devices. It may hold the token for a limited time. Either when that time expires or when it has sent all its requests and has got the answers, it passes the token on to the next known master. From time to time, it asks for the presence of masters with numbers between its own number and the number of the next known master. Thus, new masters are "invited" to participate in the ring.
          +Profibus is a token ring. One master at a time is in posession of the "token", which entitles it to send requests to other devices. It may hold the token for a limited time. Either when that time expires or when it has sent all its requests and has got the answers, it passes the token on to the next known master. From time to time, it asks for the presence of masters with numbers between its own number and the number of the next known master. Thus, new masters are "invited" to participate in the ring. +
          In case of MPI, the PLC in absence of a partner sends the token to itself:

          Example

          DC 02 02
          @@ -32,8 +33,11 @@

          Example

          	    E5,		// short ackknowledge from adapter
          DC,00,02,		//CPU passes token to adapter

          Payload

          -The payload messages are something I want to call "S7 communication". They are common for all sorts of transport (MPI,PPI, ISO over TCP). Payload messages are sent to an MPI adapter either through 3964R (which is used by LIBNODAVE and all 3rd party software I know) or through another protocol used by Step7. The protocol used by Step7 has a more complicated checksum(CRC?). It also sends a kind of "keep alive message" when the connection is idle. This keep alive message changes after packets with payload, so the partner will know if a packet with payload got lost.
          -The S7 communication over MPI introduces additional ackknowledges for each "payload" message generated by PLC or PC and passed over Profibus FDL by the adapter. These are neither present in PPI nor ISO/TCP. +The payload messages are something I want to call "S7 + communication". They are common for all sorts of transport (MPI,PPI, ISO over TCP). Payload messages are sent to an MPI adapter either through 3964R (which is used by LIBNODAVE and all 3rd party software I know) or through another protocol used by Step7. The protocol used by Step7 has a more complicated checksum(CRC?). It also sends a kind of "keep alive message" when the connection is idle. This keep alive message changes after packets with payload, so the partner will know if a packet with payload got lost. +
          +The S7 + communication over MPI introduces additional ackknowledges for each "payload" message generated by PLC or PC and passed over Profibus FDL by the adapter. These are neither present in PPI nor ISO/TCP.

          Homemade MPI Adapters

        • Find a uC with 2 UARTs of which one can handle 12MBaud.
        • Implement Profibus token passing.
        • diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/PDUerrorcodes.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/PDUerrorcodes.html index 1aae37ae..884d0c70 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/PDUerrorcodes.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/PDUerrorcodes.html @@ -1,26 +1,92 @@

          Error codes

          Error codes reported in 12 byte headers of type 2 and 3 PDUs

          - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          0ok
          0x8000function already occupied.
          0x8001not allowed in current operating status.
          0x8101hardware fault
          0x8103object access not allowed.
          0x8104context is not supported.
          0x8105invalid address.
          0x8106data type not supported.
          0x8107data type not consistent.
          0x810Aobject does not exist.
          0x8500incorrect PDU size.
          0x8702address invalid."
          0xd201block name syntax error.
          0xd202syntax error function parameter.
          0xd203syntax error block type.
          0xd204no linked block in storage medium.
          0xd205object already exists.
          0xd206object already exists.
          0xd207block exists in EPROM.
          0xd209block does not exist.
          0xd20eno block does not exist.
          0xd210block number too big.
          0ok
          0x8000function already occupied.
          0x8001not allowed in current operating status.
          0x8101hardware fault
          0x8103object access not allowed.
          0x8104context is not supported.
          0x8105invalid address.
          0x8106data type not supported.
          0x8107data type not consistent.
          0x810Aobject does not exist.
          0x8500incorrect PDU size.
          0x8702address invalid."
          0xd201block name syntax error.
          0xd202syntax error function parameter.
          0xd203syntax error block type.
          0xd204no linked block in storage medium.
          0xd205object already exists.
          0xd206object already exists.
          0xd207block exists in EPROM.
          0xd209block does not exist.
          0xd20eno block does not exist.
          0xd210block number too big.
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/SZL.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/SZL.html index 50136494..380faadf 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/SZL.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/SZL.html @@ -1,12 +1,14 @@

          Reading SZL lists

          -The CPUs of the 300 and 400 family provide lists of their internal states and properties. German Siemens terminology calls them SZL (System-ZustandsListen). These lists are what your programming Software reads when showing the diagnostic buffer, the state of run/stop, the amount of memory and much more. LIBNODAVE provides the function: +The CPUs of the 300 and 400 family provide lists of their internal states and properties. German Siemens terminology calls them SZL ( +System-Zustands +Listen). These lists are what your programming Software reads when showing the diagnostic buffer, the state of run/stop, the amount of memory and much more. LIBNODAVE provides the function:
           	daveReadSZL(daveConnection * dc, int ID, int index, void * buf);
           
          to read these lists.
          -ID 0, index 0 retrieves a list of available SZL-IDs on your PLC. I don't know how to find out -the available or meaningful indices. In most cases, index 0 is the whole list, while other +ID 0, index 0 retrieves a list of available SZL-IDs on your PLC. I don't know how to find out +the available or meaningful indices. In most cases, index 0 is the whole list, while other indices retrieve parts of it.
          -Use testMPI -z for some examples and testMPI -a for the complete contents of your PLCs SZL-lists +Use testMPI -z for some examples and testMPI -a for the complete contents of your PLCs SZL-lists (with index 0, so there may exist lists that do not have an index 0).
          Refer do Siemens documentation for the meaning of IDs and indices. \ No newline at end of file diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/area.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/area.html index 0a76ca67..a9c6063e 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/area.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/area.html @@ -1,18 +1,105 @@

          PLC memory areas

          - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameconstantExample item(German)Example item(English)Example read call
          Data blocksdaveDBDB3.DBD4DB3.DBD4daveReadBytes(dc,daveDB,3,4,4,NULL)
          Flags/MarkersdaveFlagsMW4FW4daveReadBytes(dc,daveFlags,0,4,2,NULL)
          Input memory imagedaveInputsEB2IB2daveReadBytes(dc,daveInputs,0,2,1,NULL)
          Output memory imagedaveOutputsAD8QD8daveReadBytes(dc,daveOutputs,0,8,4,NULL)
          TimersdaveTimerT2T2daveReadBytes(dc,daveTimer,0,2,2,NULL)
          CountersdaveCounterZ2C2daveReadBytes(dc,daveCounter,0,2,2,NULL)
          Direct I/OdavePPEW4PIW4daveReadBytes(dc,daveP,0,4,2,NULL)
          System information of 200 familydaveSysInfodaveReadBytes(dc,daveSysInfo,0,0,20,NULL)
          Data (V-memory) in S7-200daveDBVW1234VW1234daveReadBytes(dc,daveDB,1,1234,2,NULL)
          System flag area of 200 familydaveSysFlagsSMB0SFB0?
          Analog input words of 200 familydaveAnaInAEW0AIW0?
          Analog output words of 200 familydaveAnaOutAAW0AQW0?
          IEC TimersdaveTimer200T2T2daveReadBytes(dc,daveTimer200,0,2,2,NULL)
          IEC CountersdaveCounter200Z2C2daveReadBytes(dc,daveCounter200,0,2,2,NULL)
          NameconstantExample item(German)Example item(English)Example read call
          Data blocksdaveDBDB3.DBD4DB3.DBD4daveReadBytes(dc,daveDB,3,4,4,NULL)
          Flags/MarkersdaveFlagsMW4FW4daveReadBytes(dc,daveFlags,0,4,2,NULL)
          Input memory imagedaveInputsEB2IB2daveReadBytes(dc,daveInputs,0,2,1,NULL)
          Output memory imagedaveOutputsAD8QD8daveReadBytes(dc,daveOutputs,0,8,4,NULL)
          TimersdaveTimerT2T2daveReadBytes(dc,daveTimer,0,2,2,NULL)
          CountersdaveCounterZ2C2daveReadBytes(dc,daveCounter,0,2,2,NULL)
          Direct I/OdavePPEW4PIW4daveReadBytes(dc,daveP,0,4,2,NULL)
          System information of 200 familydaveSysInfodaveReadBytes(dc,daveSysInfo,0,0,20,NULL)
          Data (V-memory) in S7-200daveDBVW1234VW1234daveReadBytes(dc,daveDB,1,1234,2,NULL)
          System flag area of 200 familydaveSysFlagsSMB0SFB0?
          Analog input words of 200 familydaveAnaInAEW0AIW0?
          Analog output words of 200 familydaveAnaOutAAW0AQW0?
          IEC TimersdaveTimer200T2T2daveReadBytes(dc,daveTimer200,0,2,2,NULL)
          IEC CountersdaveCounter200Z2C2daveReadBytes(dc,daveCounter200,0,2,2,NULL)
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/conversions.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/conversions.html index 9827f008..7bb8a432 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/conversions.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/conversions.html @@ -1,73 +1,198 @@

          Conversion routines

          -The buffers used by daveReadBytes() and daveWriteBytes() will contain a copy of the PLC memory area. This means: If you read from the beginning of DB2, the buffer will contain a byte for byte copy of DB2. The values are the same and in the same order, as what you get when you observe byte variables in Step7. Example:
          +The buffers used by daveReadBytes() and daveWriteBytes() will contain a copy of the PLC memory area. This means: If you read from the beginning of DB2, the buffer will contain a byte for byte copy of DB2. The values are the same and in the same order, as what you get when you observe byte variables in Step7. Example: +
          - - - - - -
          DB20.DBB026
          DB20.DBB137
          DB20.DBB248
          DB20.DBB315
          DB20.DBB416
          -You are free to interpret these values as single bytes or multibyte values,the same way as you can do this in Step7 AWL.:
          -Also it is unusual, you can load a real value from DB20.DBD1:
          + + + + + + + + + + + + + + + + + + + + +
          DB20.DBB026
          DB20.DBB137
          DB20.DBB248
          DB20.DBB315
          DB20.DBB416
          + You are free to interpret these values as single bytes or multibyte values,the same way as you can do this in Step7 AWL.:
          + Also it is unusual, you can load a real value from DB20.DBD1:
           L DB20.DBD1
           L 2.0
           *R
           
          -A further complication results from the fact that Siemens PLCs store multibyte values beginning with the most significant byte (big endian) while Intel based PCs store the least significant byte first (little endian).
          -It is not possible to convert the byte order in the daveReadBytes() or daveWriteBytes() fuctions -because the start position of each multibyte value is not known then.
          -You are free to place such values at arbitrary byte addresses in your PLC program. -The same adresses must in turn be used to retrieve values from the copy of PLC memory. -If you have a data block DB2 with the following layout:
          -
          - - - -
          DBB 0BYTE
          DBD 1DWORD
          DBD 5REAL
          -You can retrieve the single values in three ways:
          -1. From the intenal buffer. After a successful call, an internal pointer points to the 1st byte. -Now use daveGetU8(dc) to get the value of the first byte as an unsigned value. The internal buffer pointer -is incremented by 1, now pointing to the copy of DBD1. Use daveGetS32(dc) to get the value of the -of the next 4 bytes as a signed value. The internal pointer is incremented by 4, now pointing to -the copy of DBD5. Use daveGetFloat(dc) to get the value of the next 4 bytes as a single precision -float.
          -2. From the internal buffer, specifying a position. Use daveGetU8at(dc,0) to get the value of the -first byte as an unsigned value. Next use daveGetS32at(dc,1) to get the value of the 4 bytes -starting at 1 as a signed value. Finally, use daveGetFloatat(dc,5) to get the value of the 4 bytes -starting at 5 as a single precision float. You may perform these operation in any order and also -repeat them.
          -3. From a user buffer. Use daveGetU8from(buffer) to get the value of the first byte as an -unsigned value. Use daveGetS32from(buffer+1) to get the value of the 4 bytes at buffer+1, i.e. -DBD 1, as a signed value. Use daveGetFloatat(buffer+5) to get the value of the 4 bytes starting -at buffer+5 as a single precision float, i.e. DBD5.
          -The conversion functions are named after the bit length and signedness they assume: - - - - - - - - - -
          int bufferint buffer+posbuffer pointersizesignedC-return typePascal ret type
          daveGetU8daveGetU8atdaveGetU8from8 bit=1 bytenointlongint
          daveGetS8daveGetS8atdaveGetS8from8 bit=1 byteyesintlongint
          daveGetU16daveGetU16atdaveGetU16from16 bit=2 bytenointlongint
          daveGetS16daveGetS16atdaveGetS16from16 bit=2 byteyesintlongint
          daveGetU32daveGetU32atdaveGetU32from32 bit=4 bytenounsigned intlongint
          daveGetS32daveGetS32atdaveGetS32from32 bit=4 byteyesintlongint
          daveGetFloatdaveGetFloatatdaveGetFloatfrom32 bit=4 byteyesfloatsingle
          + A further complication results from the fact that Siemens PLCs store multibyte values beginning with the most significant byte (big + endian) while Intel based PCs store the least significant byte first (little endian).
          + It is not possible to convert the byte order in the daveReadBytes() or daveWriteBytes() fuctions + because the start position of each multibyte value is not known then.
          + You are free to place such values at arbitrary byte addresses in your PLC program. + The same adresses must in turn be used to retrieve values from the copy of PLC memory. + If you have a data block DB2 with the following layout:
          + + + + + + + + + + + + + +
          DBB 0BYTE
          DBD 1DWORD
          DBD 5REAL
          + You can retrieve the single values in three ways:
          + 1. From the intenal buffer. After a successful call, an internal pointer points to the 1st byte. + Now use daveGetU8(dc) to get the value of the first byte as an unsigned value. The internal buffer pointer + is incremented by 1, now pointing to the copy of DBD1. Use daveGetS32(dc) to get the value of the + of the next 4 bytes as a signed value. The internal pointer is incremented by 4, now pointing to + the copy of DBD5. Use daveGetFloat(dc) to get the value of the next 4 bytes as a single precision + float.
          + 2. From the internal buffer, specifying a position. Use daveGetU8at(dc,0) to get the value of the + first byte as an unsigned value. Next use daveGetS32at(dc,1) to get the value of the 4 bytes + starting at 1 as a signed value. Finally, use daveGetFloatat(dc,5) to get the value of the 4 bytes + starting at 5 as a single precision float. You may perform these operation in any order and also + repeat them.
          + 3. From a user buffer. Use daveGetU8from(buffer) to get the value of the first byte as an + unsigned value. Use daveGetS32from(buffer+1) to get the value of the 4 bytes at buffer+1, i.e. + DBD 1, as a signed value. Use daveGetFloatat(buffer+5) to get the value of the 4 bytes starting + at buffer+5 as a single precision float, i.e. DBD5.
          + The conversion functions are named after the bit length and signedness they assume: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          int bufferint buffer+posbuffer pointersizesignedC-return typePascal ret type
          daveGetU8daveGetU8atdaveGetU8from8 bit=1 bytenointlongint
          daveGetS8daveGetS8atdaveGetS8from8 bit=1 byteyesintlongint
          daveGetU16daveGetU16atdaveGetU16from16 bit=2 bytenointlongint
          daveGetS16daveGetS16atdaveGetS16from16 bit=2 byteyesintlongint
          daveGetU32daveGetU32atdaveGetU32from32 bit=4 bytenounsigned intlongint
          daveGetS32daveGetS32atdaveGetS32from32 bit=4 byteyesintlongint
          daveGetFloatdaveGetFloatatdaveGetFloatfrom32 bit=4 byteyesfloatsingle
          -There had been an older set of those functions named after data types, e.g. -daveGetDWORD(). Those functions should not be used any more, as there names might be -misunderstandable between PLC and C or other programming languages. They are still supported -for compatibility with older versions. These functions had been inlined in earlier versions -but are now not inlined by default, because other languages than C cannot make use of inline -definitions in a C header file. -

          Notes:

          -Most commercial libraries handle the conversion issue differently: They provide functions to read one or a set of words, one or a set of long words, one or a set of reals. On the first glance, this might seem more convenient and it is as long as it can be applied to PLC memory areas containing only elements of the same type and size. But when you have to deal with data of mixed type and size, you would have to use another call to daveReadBytes() each time the type or size differs from the former. And each call contributes the overhead of the protocol and the response time of the PLC. Other libraries provide a way to read multiple items with a single call. So does Libnodave. You could also use it to retrieve data located on different boundaries. But this is limited to 20 items by the PLC. And it introduces some overhead as an address has to be transmitted for each item in the request. Use read multiple items to access data from different DBs or other memory areas when the combined results will fit in a single response. - - - - - - - - -
          When you want to readdoremark
          DB20.DBD0..DBD20read 24 bytes starting at DBB0
          DB20.DBD0..DBD8 and DBD20read 24 bytes starting at DBB0just do not evaluate bytes 11 to 19 of result.
          DB20.DBD0..DBD8 and DBD120either read 124 bytes starting at DBB0just do not evaluate bytes 11 to 119 of result.
          or use multiple read on: item1:DB20.DBD0..DBD8, item2:DB20.DBD120 you have to deal with the result set.
          DB20.DBD0..DBD8 and DB21.DBD120use multiple read on: item1:DB20.DBD0..DBD8, item2:DB21.DBD120 this is the only way to read from different DBs with a single request/reponse.
          DB20.DBD0..DBD118 and DB21.DBD4..DBD80use two calls to daveReadBytesthis is the only way if the two combined results will not fit into a single PDU.
          + There had been an older set of those functions named after data types, e.g. + daveGetDWORD(). Those functions should not be used any more, as there names might be + misunderstandable between PLC and C or other programming languages. They are still supported + for compatibility with older versions. These functions had been inlined in earlier versions + but are now not inlined by default, because other languages than C cannot make use of inline + definitions in a C header file. +

          Notes:

          + Most commercial libraries handle the conversion issue differently: They provide functions to read one or a set of words, one or a + set of long words, one or a set of reals. On the first glance, this might seem more convenient and it is as long as it can be + applied to PLC memory areas containing only elements of the same type and size. But when you have to deal with data of mixed type + and size, you would have to use another call to daveReadBytes() each time the type or size differs from the former. And each call + contributes the overhead of the protocol and the response time of the PLC. Other libraries provide a way to read multiple items with + a single call. So does Libnodave. You could also use it to retrieve data located on different boundaries. But this is limited + to 20 items by the PLC. And it introduces some overhead as an address has to be transmitted for each item in the request. Use read + multiple items to access data from different DBs or other memory areas when the combined results will fit in a single response. +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          When you want to read + + doremark
          DB20.DBD0..DBD20read 24 bytes starting at DBB0
          DB20.DBD0..DBD8 and DBD20read 24 bytes starting at DBB0just do not evaluate bytes 11 to 19 of result.
          DB20.DBD0..DBD8 and DBD120either read 124 bytes starting at DBB0just do not evaluate bytes 11 to 119 of result.
          or use multiple read on: item1:DB20.DBD0..DBD8, item2:DB20.DBD120you have to deal with the result set.
          DB20.DBD0..DBD8 and DB21.DBD120use multiple read on: item1:DB20.DBD0..DBD8, item2:DB21.DBD120this is the only way to read from different DBs with a single request/reponse.
          DB20.DBD0..DBD118 and DB21.DBD4..DBD80use two calls to daveReadBytesthis is the only way if the two combined results will not fit into a single PDU.
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveConnection.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveConnection.html index 3edd742c..01b7b73f 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveConnection.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveConnection.html @@ -1,5 +1,5 @@

          daveConnection

          -A structure representing the physical connection to a single PLC. +A structure representing the physical connection to a single PLC. daveConnection stores all properties that are unique to a single PLC:
        • The MPI address of this PLC.
        • The rack the PLC is in.
        • @@ -15,4 +15,5 @@

          daveConnection

        • rack: The rack the CPU is mounted in (normally 0, only meaningful for ISO over TCP).
        • slot: The slot number the CPU is mounted in (normally 2, only meaningful for ISO over TCP)
        • Notes:

          -In case of PPI communication, the PPI address of the partner PLC must be put into the MPI address parameter. The local PPI address must be put into the local MPI address parameter when calling daveNewInterface(). \ No newline at end of file +In case of PPI communication, the PPI address of the partner PLC must be put into the MPI address parameter. The local PPI address must be put into the local MPI address parameter when calling + daveNewInterface(). \ No newline at end of file diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveInterface.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveInterface.html index fbb68676..f50e490c 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveInterface.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveInterface.html @@ -1,5 +1,5 @@

          daveInterface

          -A structure representing the physical connection to a PLC or a network of PLCs (e.g. like MPI). +A structure representing the physical connection to a PLC or a network of PLCs (e.g. like MPI). daveInterface stores all those properties that are common to a network of PLCs:
        • - The local address used by your computer.
        • - The speed used in this network.
        • @@ -18,23 +18,58 @@

          daveInterface

        • daveSpeedYYY: a constant specifying the speed to be used on this interface. (only meaningful for MPI and Profibus)
        • Protocol types to be used with newInterface:

          - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameMeaning
          daveProtoMPIMPI for S7 300/400
          daveProtoMPI2MPI for S7 300/400, "Andrew's version"
          daveProtoPPIPPI for S7 200
          daveProtoISOTCPISO over TCP
          daveProtoISOTCP243ISO over TCP with CP243
          daveProtoIBHMPI with IBH NetLink MPI to ethernet gateway
          NameMeaning
          daveProtoMPIMPI for S7 300/400
          daveProtoMPI2MPI for S7 300/400, "Andrew's version"
          daveProtoPPIPPI for S7 200
          daveProtoISOTCPISO over TCP
          daveProtoISOTCP243ISO over TCP with CP243
          daveProtoIBHMPI with IBH NetLink MPI to ethernet gateway

          MPI/ProfiBus speed constants:

          - - - - - - - + + + + + + + + + + + + + + + + + + + + +
          daveSpeed9k
          daveSpeed19k
          daveSpeed187k
          daveSpeed500k
          daveSpeed1500k
          daveSpeed45k
          daveSpeed93k
          daveSpeed9k
          daveSpeed19k
          daveSpeed187k
          daveSpeed500k
          daveSpeed1500k
          daveSpeed45k
          daveSpeed93k
          The name field is provided for applications which may communicate with multiple PLCs on multiple pgysical connections. In such cases, the name helps to tell which interface an error message diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveOSserialType.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveOSserialType.html index b741e50e..5473eb46 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveOSserialType.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveOSserialType.html @@ -1,12 +1,12 @@

          _daveOSserialType

          -A wrapper type that contains variables representing the incoming (rfd) and outgoing (wfd) communication +A wrapper type that contains variables representing the incoming (rfd) and outgoing (wfd) communication channels on OS level. For LINUX and UNIX like systems, these are file descriptors, for Windows, they are handles. -For bidirectional channels, rfd and wfd are identical. The reasons for having separate in and out channels are:
          -1. On Unix-like systems, you can use two half duplex (unidirectional) +For bidirectional channels, rfd and wfd are identical. The reasons for having separate in and out channels are:
          +1. On Unix-like systems, you can use two half duplex (unidirectional) pipes. While there is no possibility to establish a pipe directly to the PLC, a helper program or a PLC simulator might provide such pipes.
          2. On not yet supported systems, e.g. microcontrollers or DOS with a special support for interrupt -controlled serial communication, these variables probably will contain addresses of different low +controlled serial communication, these variables probably will contain addresses of different low level routines or data structures which provide an interface to low level character I/O.
          In case of Unix or Windows, the variables are just identical.

          LINUX definition:

          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveReadBytes.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveReadBytes.html index bf4e080f..78328db4 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveReadBytes.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveReadBytes.html @@ -2,7 +2,7 @@

          daveReadBytes

          Reads a sequence of bytes from PLC memory.
               int daveReadBytes(daveConnection * dc, int area, int DB, int start, int len, void * buffer);
          -
          +

          Parameters:

        • dc: A pointer to a daveConnection structure representing an established connection.
        • area: A constant that specifies a memory area in the PLC.
        • @@ -13,31 +13,31 @@

          Parameters:

          Result:

          The function returns 0 on success. Nonzero return codes may be passed to daveStrerror() to get a textual explanation of what happened. Generally, positive error codes represent errors -reported by the PLC, while negative ones represent errors detected by LIBNODAVE, e.g. no +reported by the PLC, while negative ones represent errors detected by LIBNODAVE, e.g. no response from the PLC.

          Hints:

          len:

          -Note that timer, counters and the analog input/output words of the 200 family are +Note that timer, counters and the analog input/output words of the 200 family are allways words (2 bytes). To read n of them, you have to specify 2xn bytes as len.

          buffer:

          You may call daveReadBytes() without a buffer specifying NULL (C) or nil (Pascal). There is, however, an internal buffer that is part of the daveConnection structure. This internal buffer allways holds the result from the last read operation.

          Maximum length:

          -The maximum size of a block in S7-Communication is limited by the size of a message structure +The maximum size of a block in S7-Communication is limited by the size of a message structure calledPDU. Each call to daveReadBytes causes a the exchange of a request and a response PDU. The result data must fit into the "payload" area of a response PDU. This means a maximum block length is PDU size -18 bytes for read. A typical PDU size is 240 Byte, -limiting read calls to 222 byte result length. If you need more data, you need to use multiple +limiting read calls to 222 byte result length. If you need more data, you need to use multiple calls to daveReadBytes().

          Efficiency:

          Each call to daveReadBytes() causes a the exchange of a request -and a response PDU together with prefixes, ackknowledges and what else the transport layer +and a response PDU together with prefixes, ackknowledges and what else the transport layer requires. Therefore you should try to read as much as possible in a single call. Example:
               daveReadBytes(dc, daveDB, 5, 68, 14, appBuffer);
          -
          -reads DBD68 and DBD78 and everything in between and fills the range appBuffer+4 to appBuffer+9 + +reads DBD68 and DBD78 and everything in between and fills the range appBuffer+4 to appBuffer+9 with 6 unwanted bytes, but it is much faster than:
               daveReadBytes(dc, daveDB, 5, 68, 4, appBuffer);
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveWriteBytes.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveWriteBytes.html
          index d48b6427..bdbad867 100644
          --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveWriteBytes.html
          +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/daveWriteBytes.html
          @@ -2,7 +2,7 @@ 

          daveWriteBytes

          Write a sequence of bytes from a buffer to PLC memory.
               int daveWriteBytes(daveConnection * dc, int area, int DB, int start, int len, void * buffer);
          -
          +

          Parameters:

        • dc: A pointer to a daveConnection structure representing an established connection.
        • area: A constant that specifies a memory area in the PLC.
        • @@ -12,27 +12,27 @@

          Parameters:

        • buffer: A pointer to some memory space where you want the result to be copied too.
        • Hints:

          len:

          -Note that timer, counters and the analog input/output words of the 200 family are +Note that timer, counters and the analog input/output words of the 200 family are allways words (2 bytes). To read n of them, you have to specify 2xn bytes as len.

          buffer:

          You may call daveReadBytes() without a buffer specifying NULL (C) or nil (Pascal). There is, however, an internal buffer that is part of the daveConnection structure. This internal buffer allways holds the result from the last read operation.

          Maximum length:

          -The maximum size of a block in S7-Communication is limited by the size of a message structure +The maximum size of a block in S7-Communication is limited by the size of a message structure calledPDU. Each call to daveReadBytes causes a the exchange of a request and a response PDU. The result data must fit into the "payload" area of a response PDU. This means a maximum block length is PDU size -18 bytes for read. A typical PDU size is 240 Byte, -limiting read calls to 222 byte result length. If you need more data, you need to use multiple +limiting read calls to 222 byte result length. If you need more data, you need to use multiple calls to daveReadBytes().

          Efficiency:

          Each call to daveReadBytes() causes a the exchange of a request -and a response PDU together with prefixes, ackknowledges and what else the transport layer +and a response PDU together with prefixes, ackknowledges and what else the transport layer requires. Therefore you should try to read as much as possible in a single call. Example:
               daveReadBytes(dc, daveDB, 5, 68, 14, appBuffer);
          -
          -reads DBD68 and DBD78 and everything in between and fills the range appBuffer+4 to appBuffer+9 + +reads DBD68 and DBD78 and everything in between and fills the range appBuffer+4 to appBuffer+9 with 6 unwanted bytes, but it is much faster than:
               daveReadBytes(dc, daveDB, 5, 68, 4, appBuffer);
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/functions.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/functions.html
          index e6c582f6..2cb920bc 100644
          --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/functions.html
          +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/functions.html
          @@ -1,5 +1,6 @@
          -

          List of functions, structures and constants

          -

          Constants

          +

          List of functions, structures and constants +

          +

          Constants

           /* 
               This is a wrapper for the serial or ethernet interface. This is here to make porting easier.
          @@ -13,49 +14,109 @@ 

          Constants

          HANDLE wfd; } _daveOSserialType;
          -

          some frequently used ASCII control codes:

          +

          some frequently used ASCII control codes:

           DLE
           ETX
           STX
           SYN
           
          -

          Protocol types to be used with newInterface:

          - - - - - - - - - -
          NameMeaning
          daveProtoMPIMPI for S7 300/400
          daveProtoMPI2MPI for S7 300/400, "Andrew's version"
          daveProtoMPI3MPI for S7 300/400, The version Step7 uses. Not yet implemented.
          daveProtoPPIPPI for S7 200
          daveProtoISOTCPISO over TCP
          daveProtoISOTCP243ISO over TCP with CP243
          daveProtoIBHMPI with IBH NetLink MPI to ethernet gateway
          -

          ProfiBus/MPI speed constants to be used with newInterface:

          - - - - - - - - -
          daveSpeed9k
          daveSpeed19k
          daveSpeed187k
          daveSpeed500k
          daveSpeed1500k
          daveSpeed45k
          daveSpeed93k
          -

          Some S7 Communication function codes (yet unused ones may be incorrect).

          -These codes are used as the first byte of parameters in a PDU. - - - - - - - -ends the transmission of a part of a code block from PLC to programmer -
          NameMeaning
          daveFuncOpenS7Connectionconnect to a PLC, negotiate PDU length
          daveFuncReadmarks a read requeast
          daveFuncWritemarks a write requeast
          daveFuncStartUploadinitiates the transmission of a code block from PLC to programmer
          daveFuncUploadcontinues the transmission of a part of a code block from PLC to programmer
          daveFuncEndUpload
          -

          S7 specific constants:

          -

          Block Type codes

          - - S7 specific constants: +

          Protocol types to be used with newInterface:

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameMeaning
          daveProtoMPIMPI for S7 300/400
          daveProtoMPI2MPI for S7 300/400, "Andrew's version"
          daveProtoMPI3MPI for S7 300/400, The version Step7 uses. Not yet implemented.
          daveProtoPPIPPI for S7 200
          daveProtoISOTCPISO over TCP
          daveProtoISOTCP243ISO over TCP with CP243
          daveProtoIBHMPI with IBH NetLink MPI to ethernet gateway
          +

          ProfiBus/MPI speed constants to be used with newInterface:

          + + + + + + + + + + + + + + + + + + + + + + +
          daveSpeed9k
          daveSpeed19k
          daveSpeed187k
          daveSpeed500k
          daveSpeed1500k
          daveSpeed45k
          daveSpeed93k
          +

          Some S7 Communication function codes (yet unused ones may be incorrect).

          + These codes are used as the first byte of parameters in a PDU. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameMeaning
          daveFuncOpenS7Connectionconnect to a PLC, negotiate PDU length
          daveFuncReadmarks a read requeast
          daveFuncWritemarks a write requeast
          daveFuncStartUploadinitiates the transmission of a code block from PLC to programmer
          daveFuncUploadcontinues the transmission of a part of a code block from PLC to programmer
          daveFuncEndUploadends the transmission of a part of a code block from PLC to programmer
          +

          S7 specific constants:

          +

          Block Type codes

          + + S7 specific constants:
           	daveBlockType_OB
           	daveBlockType_DB
          @@ -67,32 +128,111 @@ 

          Block Type codes

          Memory Area Codes

          Use these constants for parameter "area" in daveReadBytes and daveWriteBytes. - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameMeaning
          daveSysInfo 0x3System info of 200 family
          daveSysFlagsSystem flags of 200 family
          daveAnaInanalog inputs of 200 family
          daveAnaOutanalog outputs of 200 family
          daveInputsInput image memory
          daveOutputsOutput image memory
          daveFlagsFlags (Merker) area
          daveDBData blocks in 300 and 400, V-Memory in 200
          daveCounterCounters in 300 and 400
          daveTimerTimers in 300 and 400
          NameMeaning
          daveSysInfo 0x3System info of 200 family
          daveSysFlagsSystem flags of 200 family
          daveAnaInanalog inputs of 200 family
          daveAnaOutanalog outputs of 200 family
          daveInputsInput image memory
          daveOutputsOutput image memory
          daveFlagsFlags (Merker) area
          daveDBData blocks in 300 and 400, V-Memory in 200
          daveCounterCounters in 300 and 400
          daveTimerTimers in 300 and 400

          Function Result Codes.

          Genarally, 0 means ok, >0 are results (also errors) reported by the PLC, <0 means error reported by library code. - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          NameValueMeaning
          daveResOK0all ok
          daveResMultipleBitsNotSupported6CPU tells it does not support to read a bit block with a length other than 1 bit
          daveResItemNotAvailable2003means a a piece of data is not available in the CPU, e.g. when trying to read a non existing DB or bit bloc of length<>1. This code seems to be specific to 200 family.
          daveResItemNotAvailable10 means a a piece of data is not available in the CPU, e.g. when trying to read a non existing DB
          daveAddressOutOfRange5means the data address is beyond the CPUs address range
          daveResCannotEvaluatePDU-123
          daveResCPUNoData-124
          daveUnknownError-125
          daveEmptyResultError-126
          daveEmptyResultSetError-127
          NameValueMeaning
          daveResOK0all ok
          daveResMultipleBitsNotSupported6CPU tells it does not support to read a bit block with a length other than 1 bit
          daveResItemNotAvailable2003means a a piece of data is not available in the CPU, e.g. when trying to read a non existing DB or bit bloc of length<>1. This + code seems to be specific to 200 family. +
          daveResItemNotAvailable10 means a a piece of data is not available in the CPU, e.g. when trying to read a non existing DB
          daveAddressOutOfRange5means the data address is beyond the CPUs address range
          daveResCannotEvaluatePDU-123
          daveResCPUNoData-124
          daveUnknownError-125
          daveEmptyResultError-126
          daveEmptyResultSetError-127

          Error code to message string conversion:

          Call this function to get an explanation for error codes returned by other functions. @@ -122,22 +262,70 @@

          Max number of bytes in a single message.

          Some definitions for debugging:

          - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          daveDebugRawReadShow the single bytes received
          daveDebugSpecialCharsShow when special chars are read
          daveDebugRawWriteShow the single bytes written
          daveDebugListReachablesShow the steps when determine devices in MPI net
          daveDebugInitAdapterShow the steps when Initilizing the MPI adapter
          daveDebugConnectShow the steps when connecting a PLC
          daveDebugPacket
          daveDebugByte
          daveDebugCompare
          daveDebugExchange
          daveDebugPDUdebug PDU handling
          daveDebugUploaddebug PDU loading program blocks from PLC
          daveDebugMPI
          daveDebugPrintErrorsPrint error messages
          daveDebugPassive
          daveDebugAllEnables all debug levels
          daveDebugRawReadShow the single bytes received
          daveDebugSpecialCharsShow when special chars are read
          daveDebugRawWriteShow the single bytes written
          daveDebugListReachablesShow the steps when determine devices in MPI net
          daveDebugInitAdapterShow the steps when Initilizing the MPI adapter
          daveDebugConnectShow the steps when connecting a PLC
          daveDebugPacket
          daveDebugByte
          daveDebugCompare
          daveDebugExchange
          daveDebugPDUdebug PDU handling
          daveDebugUploaddebug PDU loading program blocks from PLC
          daveDebugMPI
          daveDebugPrintErrorsPrint error messages
          daveDebugPassive
          daveDebugAllEnables all debug levels

          Global variables

          Current debug level:

          @@ -156,7 +344,8 @@

          Some useful data types:

          typedef struct _daveConnection daveConnection; typedef struct _daveInterface daveInterface; -

          Helper struct to manage PDUs. This is NOT the part of the packet called PDU, but a set of pointers that ease access to the "private parts" of a PDU.

          +

          Helper struct to manage PDUs. This is NOT the part of the packet called PDU, but a set of pointers that ease access to the "private + parts" of a PDU.

           typedef struct {
               uc * header;	/* pointer to start of PDU (PDU header) */
          @@ -169,7 +358,8 @@ 

          Helper struct to manage PDUs. This is NOT the part of the packet called PDU, int udlen; /* user or result data length */ } PDU;

          -

          Definitions of prototypes for the protocol specific functions. The library "switches" protocol by setting pointers to the protol specific implementations.

          +

          Definitions of prototypes for the protocol specific functions. The library "switches" protocol by setting pointers to the protol + specific implementations.

           typedef int (*_initAdapterFunc) ();
           typedef int (*_connectPLCFunc) ();
          @@ -338,121 +528,122 @@ 

          Build PDU for a read request

          void _daveConstructReadRequest(PDU *p, int area, int DBnum, int start, int bytes);

          - build PDU for a BIT read request + build PDU for a BIT read request

           void  _daveConstructBitReadRequest(PDU *p, int area, int DBnum, int start, int bytes);

          - build the PDU for a write request + build the PDU for a write request

           void  _daveConstructWriteRequest(PDU *p, int area, int DBnum, int start, int bytes,void * values);

          - build the PDU for a bit write request + build the PDU for a bit write request

           void  _daveConstructBitWriteRequest(PDU *p, int area, int DBnum, int start, int bytes,void * values);

          set up pointers to the fields of a received message -

          -
           int  _daveSetupReceivedPDU(daveConnection * dc,PDU * p);
          -

          - send PDU to PLC and retrieves the answer -

          -
           int  _daveExchange(daveConnection * dc,PDU *p);
          -

          Utilities:

          -

          Hex dump PDU:

          -
           void  _daveDumpPDU(PDU * p);
          -

          Compare blocks:

          - This is an extended memory compare routine. It can handle don't care and stop flags - in the sample data. A stop flag lets it return success, if there were no mismatches - up to this point. -
           int  _daveMemcmp(us * a, uc *b, size_t len);
          -

          Hex dump:

          -Writes the name followed by len bytes written in hex and a newline. -
           void  _daveDump(char * name,uc*b,int len);
          -

          names for Objects

          -
           char *  daveBlockName(uc bn);
          -
           char *  daveAreaName(uc n);
          -

          - Data conversion convenience functions: -

          - -
           int  daveGetByte(daveConnection * dc);
          - -
           float  daveGetFloat(daveConnection * dc);
          - -
           int  daveGetInteger(daveConnection * dc);
          - -
           unsigned int  daveGetDWORD(daveConnection * dc);
          - -
           unsigned int  daveGetUnsignedInteger(daveConnection * dc);
          - -
           unsigned int  daveGetWORD(daveConnection * dc);
          - -
           int  daveGetByteat(daveConnection * dc, int pos);
          - -
           unsigned int  daveGetWORDat(daveConnection * dc, int pos);
          - -
           unsigned int  daveGetDWORDat(daveConnection * dc, int pos);
          - -
           float  daveGetFloatat(daveConnection * dc, int pos);
          - -
           float  toPLCfloat(float ff);
          - -
           short  daveSwapIed_16(short ff);
          - -
           int  daveSwapIed_32(int ff);
          -

          Newer data conversion convenience functions:

          - Newer conversion routines. As the terms WORD, INT, INTEGER etc have different meanings - for users of different programming languages and compilers, I choose to provide a new - set of conversion routines named according to the bit length of the value used. The 'U' - or 'S' stands for unsigned or signed. -

          Get a value from the position b points to

          -B is typically a pointer to a buffer that has - been filled with daveReadBytes: -
           int  daveGetS8from(uc *b);
          -
           int  daveGetU8from(uc *b);
          -
           int  daveGetS16from(uc *b);
          -
           int  daveGetU16from(uc *b);
          -
           int  daveGetS32from(uc *b);
          -
           unsigned int  daveGetU32from(uc *b);
          -
           float  daveGetFloatfrom(uc *b);
          -

          Get a value from the current position

          - in the last result read on the connection dc. - This will increment an internal pointer, so the next value is read from the position - following this value. - -
           int  daveGetS8(daveConnection * dc);
          -
           int  daveGetU8(daveConnection * dc);
          -
           int  daveGetS16(daveConnection * dc);
          -
           int  daveGetU16(daveConnection * dc);
          -
           int  daveGetS32(daveConnection * dc);
          -
           unsigned int  daveGetU32(daveConnection * dc);
          -

          - Get a value from a given position in the last result read on the connection dc.

          -
           int  daveGetS8at(daveConnection * dc, int pos);
          -
           int  daveGetU8at(daveConnection * dc, int pos);
          -
           int  daveGetS16at(daveConnection * dc, int pos);
          -
           int  daveGetU16at(daveConnection * dc, int pos);
          -
           int  daveGetS32at(daveConnection * dc, int pos);
          -
           unsigned int  daveGetU32at(daveConnection * dc, int pos);
          -

          put one byte into buffer b:

          -
           uc *  davePut8(uc *b,int v);
          -
           uc *  davePut16(uc *b,int v);
          -
           uc *  davePut32(uc *b,int v);
          -
           uc *  davePutFloat(uc *b,float v);
          -
           void  davePut8at(uc *b, int pos, int v);
          -
           void  davePut16at(uc *b, int pos, int v);
          -
           void  davePut32at(uc *b, int pos, int v);
          -
           void  davePutFloatat(uc *b,int pos, float v);
          -/** - Timer and Counter conversion functions: -**/ -/* - get time in seconds from current read position: -*/ -
           float  daveGetSeconds(daveConnection * dc);
          -/* - get time in seconds from random position: -*/ +

          +
           int  _daveSetupReceivedPDU(daveConnection * dc,PDU * p);
          +

          + send PDU to PLC and retrieves the answer +

          +
           int  _daveExchange(daveConnection * dc,PDU *p);
          +

          Utilities: +

          +

          Hex dump PDU:

          +
           void  _daveDumpPDU(PDU * p);
          +

          Compare blocks:

          + This is an extended memory compare routine. It can handle don't care and stop flags + in the sample data. A stop flag lets it return success, if there were no mismatches + up to this point. +
           int  _daveMemcmp(us * a, uc *b, size_t len);
          +

          Hex dump:

          + Writes the name followed by len bytes written in hex and a newline. +
           void  _daveDump(char * name,uc*b,int len);
          +

          names for Objects

          +
           char *  daveBlockName(uc bn);
          +
           char *  daveAreaName(uc n);
          +

          + Data conversion convenience functions: +

          + +
           int  daveGetByte(daveConnection * dc);
          + +
           float  daveGetFloat(daveConnection * dc);
          + +
           int  daveGetInteger(daveConnection * dc);
          + +
           unsigned int  daveGetDWORD(daveConnection * dc);
          + +
           unsigned int  daveGetUnsignedInteger(daveConnection * dc);
          + +
           unsigned int  daveGetWORD(daveConnection * dc);
          + +
           int  daveGetByteat(daveConnection * dc, int pos);
          + +
           unsigned int  daveGetWORDat(daveConnection * dc, int pos);
          + +
           unsigned int  daveGetDWORDat(daveConnection * dc, int pos);
          + +
           float  daveGetFloatat(daveConnection * dc, int pos);
          + +
           float  toPLCfloat(float ff);
          + +
           short  daveSwapIed_16(short ff);
          + +
           int  daveSwapIed_32(int ff);
          +

          Newer data conversion convenience functions:

          + Newer conversion routines. As the terms WORD, INT, INTEGER etc have different meanings + for users of different programming languages and compilers, I choose to provide a new + set of conversion routines named according to the bit length of the value used. The 'U' + or 'S' stands for unsigned or signed. +

          Get a value from the position b points to

          + B is typically a pointer to a buffer that has + been filled with daveReadBytes: +
           int  daveGetS8from(uc *b);
          +
           int  daveGetU8from(uc *b);
          +
           int  daveGetS16from(uc *b);
          +
           int  daveGetU16from(uc *b);
          +
           int  daveGetS32from(uc *b);
          +
           unsigned int  daveGetU32from(uc *b);
          +
           float  daveGetFloatfrom(uc *b);
          +

          Get a value from the current position

          + in the last result read on the connection dc. + This will increment an internal pointer, so the next value is read from the position + following this value. + +
           int  daveGetS8(daveConnection * dc);
          +
           int  daveGetU8(daveConnection * dc);
          +
           int  daveGetS16(daveConnection * dc);
          +
           int  daveGetU16(daveConnection * dc);
          +
           int  daveGetS32(daveConnection * dc);
          +
           unsigned int  daveGetU32(daveConnection * dc);
          +

          + Get a value from a given position in the last result read on the connection dc.

          +
           int  daveGetS8at(daveConnection * dc, int pos);
          +
           int  daveGetU8at(daveConnection * dc, int pos);
          +
           int  daveGetS16at(daveConnection * dc, int pos);
          +
           int  daveGetU16at(daveConnection * dc, int pos);
          +
           int  daveGetS32at(daveConnection * dc, int pos);
          +
           unsigned int  daveGetU32at(daveConnection * dc, int pos);
          +

          put one byte into buffer b:

          +
           uc *  davePut8(uc *b,int v);
          +
           uc *  davePut16(uc *b,int v);
          +
           uc *  davePut32(uc *b,int v);
          +
           uc *  davePutFloat(uc *b,float v);
          +
           void  davePut8at(uc *b, int pos, int v);
          +
           void  davePut16at(uc *b, int pos, int v);
          +
           void  davePut32at(uc *b, int pos, int v);
          +
           void  davePutFloatat(uc *b,int pos, float v);
          + /** + Timer and Counter conversion functions: + **/ + /* + get time in seconds from current read position: + */ +
           float  daveGetSeconds(daveConnection * dc);
          + /* + get time in seconds from random position: + */
           float  daveGetSecondsAt(daveConnection * dc, int pos);
           /*	
               get counter value from current read position:
          @@ -494,13 +685,13 @@ 

          put one byte into buffer b:

          program. If the pointer is not NULL, the result data will be copied thereto. Hence it must be big enough to take up the result. In any case, you can also retrieve the result data using the get macros - on the connection pointer. - - FIXME: Existence of DB is not checked. - There is no error message for nonexistent data blocks. - There is no check for max. message len or - automatic splitting into multiple messages. -*/ + on the connection pointer. + + FIXME: Existence of DB is not checked. + There is no error message for nonexistent data blocks. + There is no check for max. message len or + automatic splitting into multiple messages. + */
           int  daveReadBytes(daveConnection * dc, int area, int DB, int start, int len, void * buffer);
           /* 
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/gettingStarted.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/gettingStarted.html
          index 0920ab98..918714c0 100644
          --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/gettingStarted.html
          +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/gettingStarted.html
          @@ -8,143 +8,181 @@ 

          Intended purpose

        • The debug output, obtained with debug option (-d), provides valuable informatioon in case Libnodave fails with some hardware..
        • The benchmark options let you measure the time needed for transfers of short and long data blocks.
        • Note on PASCAL source test programs:

          -Basic test programs are also available as Pascal sources. They are not as complete as their -C coded counterparts. Their main purpose is to test the interface unit nodave.pas. -

          Calling test programs

          -Just invoke the test programs without arguments. -They will print a list of possible arguments and options. -

          Which test program for which Setup?

          - - - - - - - - -
          CPUConnectionGenerell TestsLoad Program into CPU
          S7 300 or 400Serial with MPI adapter cabletestMPItestMPIload
          S7 200Serial with PPI adapter cabletestPPItestPPIload
          S7 300 or 400Ethernet CP343/443testISO_TCPtestISO_TCPload
          S7 200Ethernet CP243testISO_TCP -2testISO_TCPload -2
          S7 300 or 400Ethernet with IBH/MHJ-NetLink GatewaytestIBHtestMPI_IBHload
          S7 200Ethernet with IBH/MHJ-NetLink GatewaytestPPI_IBHtestPPI_IBHload
          -

          Options to make test programs work with certain configurations:

          -

          MPI transport with MPI adapter:

          -
        • --mpi=[number] Uses number as the MPI address of the PLC. Default is 2.
        • -
        • --local=[number] Uses number as the local MPI address of the adapter. Default is 0.
        • -
        • -2 Uses another variant of the MPI protocol. Try if you connect to adapter/PLC.
        • -
        • -[some numbers] Use dfferent MPI/Profibus speeds.
        • -

          ISO over TCP transport with CP343/CP443:

          -
        • --slot=[number] Uses number as the slot address of the PLC. Default rack 0, slot 2.
        • -

          ISO over TCP transport with CP243:

          -
        • -2 Fakes a MicroWin connection request. This is currently mandatory for CP243. -It will switch the CFG LED on.
        • -

          What can the test programs do?

          -If invoked with the connection as the only argument, all test programs will read some data from -the memory area of Flags (also known as Merkers).They try to read FD0,FD4 and FD8 as DWORDS and -FD12 as real.
          Depending on the contents of this memory, the results may or may no seem -reasonable.The obtained values are just the same as if you would observe these variables in Step7 -using the display formats signed,signed,signed and floating point.
          -If you specify the option -w, the test programs increment the data, write it back to your PLC -(Attention! This changes PLC internal memory!) and read it again, thus demonstrating the effect of -changes.
          -If you specify the option -c, the test programs write 0 to these memory locations. -(Attention! This changes PLC internal memory!). This is useful if the current memory contents -doesn't make much sense when displayed in the above mentioned format.
          -If you specify the option -b, the test programs try to do block read benchmark tests. Combining -b and --w will also do write benchmark tests.
          --r option tries to put your PLC into RUN mode.(Attention! May start actions on machinery!).
          --s option tries to put your PLC into STOP mode.(Attention! Will interrupt running machinery!).
          ---readout option tries to readout program blocks from the PLC and will store them in files named -like OB1.mc7.(Attention! I got reports, that this produces ill effects on S7-400!).
          --z reads System State Lists (System-Zustandslisten from the PLC. These lists exist -only in 300/400 family PLCs and provide diagnostic information. Please refer to Siemens documentation about -the meaning of IDs and indices.
          -

          Test programs to load blocks into CPU

          -
        • This is a quite experimental feature. -First you will need correctly formed program blocks stored in files. A possible source are files -previously read out using --readout. You cannot get them from Step7 as Step7 stores program -block in a data base. It has not been tested but may be so that third party programming software -that stores program blocks in files uses the same file format.
          -Loading of SDBs (System Data Blocks) is highly dependent of the sequence of -block numbers. -

          Programming a basic application

          -

          Preparations

          -The main purpose of this library is to read and write data from and to Siemens PLCs. -To do so, you need to establish a connection to the PLC. -First, you need to configure a serial port of your computer or establish a TCP connection. -This connection is represented by the type _daveOSserialType, which contains file descriptors -in case of Unix-like systems, handles in case of windows and what other systems supported in -the future might use for this purpose. + Basic test programs are also available as Pascal sources. They are not as complete as their + C coded counterparts. Their main purpose is to test the interface unit nodave.pas. +

          Calling test programs

          + Just invoke the test programs without arguments. + They will print a list of possible arguments and options. +

          Which test program for which Setup?

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          CPUConnectionGenerell TestsLoad Program into CPU
          S7 300 or 400Serial with MPI adapter cabletestMPItestMPIload
          S7 200Serial with PPI adapter cabletestPPItestPPIload
          S7 300 or 400Ethernet CP343/443testISO_TCPtestISO_TCPload
          S7 200Ethernet CP243testISO_TCP -2testISO_TCPload -2
          S7 300 or 400Ethernet with IBH/MHJ-NetLink GatewaytestIBHtestMPI_IBHload
          S7 200Ethernet with IBH/MHJ-NetLink GatewaytestPPI_IBHtestPPI_IBHload
          +

          Options to make test programs work with certain configurations:

          +

          MPI transport with MPI adapter:

          +
        • --mpi=[number] Uses number as the MPI address of the PLC. Default is 2.
        • +
        • --local=[number] Uses number as the local MPI address of the adapter. Default is 0.
        • +
        • -2 Uses another variant of the MPI protocol. Try if you connect to adapter/PLC.
        • +
        • -[some numbers] Use dfferent MPI/Profibus speeds.
        • +

          ISO over TCP transport with CP343/CP443:

          +
        • --slot=[number] Uses number as the slot address of the PLC. Default rack 0, slot 2.
        • +

          ISO over TCP transport with CP243:

          +
        • -2 Fakes a MicroWin connection request. This is currently mandatory for CP243. + It will switch the CFG LED on. +
        • +

          What can the test programs do?

          + If invoked with the connection as the only argument, all test programs will read some data from + the memory area of Flags (also known as Merkers).They try to read FD0,FD4 and FD8 as DWORDS and + FD12 as real.
          Depending on the contents of this memory, the results may or may no seem + reasonable.The obtained values are just the same as if you would observe these variables in Step7 + using the display formats signed,signed,signed and floating point.
          + If you specify the option -w, the test programs increment the data, write it back to your PLC + (Attention! This changes PLC internal memory!) and read it again, thus demonstrating the effect of + changes.
          + If you specify the option -c, the test programs write 0 to these memory locations. + (Attention! This changes PLC internal memory!). This is useful if the current memory contents + doesn't make much sense when displayed in the above mentioned format.
          + If you specify the option -b, the test programs try to do block read benchmark tests. Combining -b and + -w will also do write benchmark tests.
          + -r option tries to put your PLC into RUN mode.(Attention! May start actions on machinery!).
          + -s option tries to put your PLC into STOP mode.(Attention! Will interrupt running machinery!).
          + --readout option tries to readout program blocks from the PLC and will store them in files named + like OB1.mc7.(Attention! I got reports, that this produces ill effects on S7-400!).
          + -z reads System State Lists (System-Zustandslisten from the PLC. These lists exist + only in 300/400 family PLCs and provide diagnostic information. Please refer to Siemens documentation about + the meaning of IDs and indices.
          -use setport to initialize the members of a _daveOSserialType to something representing -a configured serial connection: +

          Test programs to load blocks into CPU

          +
        • This is a quite experimental feature. + First you will need correctly formed program blocks stored in files. A possible source are files + previously read out using --readout. You cannot get them from Step7 as Step7 stores program + block in a data base. It has not been tested but may be so that third party programming software + that stores program blocks in files uses the same file format.
          + Loading of SDBs (System Data Blocks) is highly dependent of the sequence of + block numbers. +

          Programming a basic application

          +

          Preparations

          + The main purpose of this library is to read and write data from and to Siemens PLCs. + To do so, you need to establish a connection to the PLC. + First, you need to configure a serial port of your computer or establish a TCP connection. + This connection is represented by the type _daveOSserialType, which contains file descriptors + in case of Unix-like systems, handles in case of windows and what other systems supported in + the future might use for this purpose. + + use setport to initialize the members of a _daveOSserialType to something representing + a configured serial connection:
               fds.rfd=setPort(argv[adrPos],"38400",'O');
           
          -for serial connections or: + for serial connections or:
               fds.rfd=openSocket(102, IPaddress_of_CP);
           
          -or + or
               fds.rfd=openSocket(1099, IPaddress_of_IBH-NetLink);
           
          -for TCP connections. Then do: + for TCP connections. Then do:
               fds.wfd=fds.rfd;
           
          -With the initialized _daveOSserialType, you will initialize a structure of type -daveInterface, -representing the physical connection to a PLC or a network of PLCs (e.g. like MPI). + With the initialized _daveOSserialType, you will initialize a structure of type + daveInterface, + representing the physical connection to a PLC or a network of PLCs (e.g. like MPI).
               di=daveNewInterface(fds, "IF1", localMPI, daveProtoXXX, daveSpeedYYY);
           
          -With the resulting daveInterface structure, you can initialize an adapter, if one is used: + With the resulting daveInterface structure, you can initialize an adapter, if one is used:
              
               res =daveInitAdapter(di);
          -
          -While currently only MPI-adapters and IBH-NetLinks really need this initialization procedure, it is save to use -daveInitAdapter() with any protocol type. If it has no meaning for the protocol used, it is -mapped to a dummy procedure that returns allways success. +
        • + While currently only MPI-adapters and IBH-NetLinks really need this initialization procedure, it is save to use + daveInitAdapter() with any protocol type. If it has no meaning for the protocol used, it is + mapped to a dummy procedure that returns allways success. -After successfully initializing your adapter, you can retrieve a list of reachable partners -on an MPI network. The function takes the daveInterface structure and a pointer to a buffer -of sufficient length as arguments. It returns the real length of the list. If the partners cannot -be listed with the protocol used, it just returns a length of 0. + After successfully initializing your adapter, you can retrieve a list of reachable partners + on an MPI network. The function takes the daveInterface structure and a pointer to a buffer + of sufficient length as arguments. It returns the real length of the list. If the partners cannot + be listed with the protocol used, it just returns a length of 0.
              
               listLength = daveListReachablePartners(di,buf1);
           
          -After successfully initializing your adapter, you can establish a connection to a certain PLC -on the network. To do so, you will first initialize a structure of -type daveConnection, -representing the logical connection to a single PLC. + After successfully initializing your adapter, you can establish a connection to a certain PLC + on the network. To do so, you will first initialize a structure of + type daveConnection, + representing the logical connection to a single PLC.
               dc =daveNewConnection(di, MPI_address, Rack, Slot);
           
          -With the resulting daveConnection structure, you need to really connect the PLC: + With the resulting daveConnection structure, you need to really connect the PLC:
              
               res =daveConnectPLC(dc);
          -
          -

          Exchanging values:

          -Once you have established a connection to your PLC, you can read and write values: +
          +

          Exchanging values:

          + Once you have established a connection to your PLC, you can read and write values:
               res=daveReadBytes(dc, AREA, area_Number, start_address, length, buffer);
           
               res=daveWriteBytes(dc, AREA, area_Number, start_address, length, buffer);
           
          -Usually, you will have to convert byte sequences from and to the buffer -to use the data in your application.
          -After you are done with your data exchanges, call: + Usually, you will have to convert byte sequences from and to the buffer + to use the data in your application.
          + After you are done with your data exchanges, call:
           	daveDisconnectPLC(dc);
           
          -To disconnect from the PLC and + To disconnect from the PLC and
           	daveDisconnectAdapter(di);
          -
          -to disconnect from the Adapter. -Now close the serial or TCP/IP connection using the appropriate system calls for your OS. -

          Advanced data exchange

          -Read multiple items with a single transaction.
          -Read and set single bits.
          -

          Other features

          -Read diagnostic info (300 and 400 only).
          -Load program code from PLC.
          -Load program code into PLC.
          + + to disconnect from the Adapter. + Now close the serial or TCP/IP connection using the appropriate system calls for your OS. +

          Advanced data exchange

          + Read multiple items with a single transaction.
          + Read and set single bits.
          + +

          Other features

          + Read diagnostic info (300 and 400 only).
          + Load program code from PLC.
          + Load program code into PLC.
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/index.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/index.html index 2a10d364..95be2689 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/index.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/index.html @@ -1,23 +1,29 @@ - + - - -

          The beginnings of a documentation for LIBNODAVE

          + + +

          The beginnings of a documentation for LIBNODAVE

          +

          Purpose

          -LIBNODAVE provides a way to exchange data with Siemens PLCs of S7-200, 300 and 400 families. It has also been successfully tested with a VIPA Speed7 CPU. It should also be useable with S7-compatible PLCs from SAIA.
          -Data exchange comprises all memory areas and variables you canaccess in your PLC programs, e.g. flags, data blocks,input and output image memory, timers and counters.
          -Additionally, LIBNODAVEprovides access to functions that are in the scope of programming software, e,g. reading diagnostic information, read program blocks from a PLC and write them to a PLC, start and stop a PLC. +LIBNODAVE provides a way to exchange data with Siemens PLCs of S7-200, 300 and 400 families. It has also been successfully tested with a VIPA Speed7 CPU. It should also be useable with S7-compatible PLCs from SAIA.
          +Data exchange comprises all memory areas and variables you canaccess in your PLC programs, e.g. flags, data blocks,input and output image +memory, timers and counters.
          +Additionally, LIBNODAVEprovides access to functions that are in the scope of programming software, e,g. reading diagnostic +information, read program blocks from a PLC and write them to a PLC, start and stop a PLC.

          Licensing

          LIBNODAVE is free software under GPL and LGPL.

          Availability

          -LIBNODAVE is currently available for UNIX and Win32. It comes with precompiled libraries for LINUX and Windows. You may port it yourself on any system providing a C compiler.
          +LIBNODAVE is currently available for UNIX and Win32. It comes with precompiled libraries for LINUX and Windows. You may port it +yourself on any system providing a C compiler.
          Get the latest version from Sourceforge.

          Basic usage

          getting started +

          FAQ

          frequently asked questions - + \ No newline at end of file diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/initAdapter.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/initAdapter.html index da0e1c9e..25b942a8 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/initAdapter.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/initAdapter.html @@ -1,8 +1,8 @@ With the resulting daveInterface structure, you need to initialize an adapter, if one is used:
              
               res =daveInitAdapter(di);
          -    
          -While currently only MPI-adapters really need this initialization procedure, it is save to use
          +    
          +    While currently only MPI-adapters really need this initialization procedure, it is save to use
           daveInitAdapter() with any protocol type. If it has no meaning for the protocol used, it is
           mapped to a dummy procedure that returns allways success.
           
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/openSocket.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/openSocket.html
          index 4f12bb16..b23508ed 100644
          --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/openSocket.html
          +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/openSocket.html
          @@ -10,5 +10,7 @@ 

          openSocket

        • port is the port number for the protocol, usually 102 for ISO over TCP or 1099 for the IBH/MHJ NetLink protocol.
        • peer is the IP address of the PLC/CP as a string, e.g. 192.168.0.3 .
        • Note:

          -With regard to Libnodave, you are free to use other port numbers. While you cannot change port numbers on S7 devices or IBH NetLinks, this can be useful with port redirecting software like
          rinetd, which makes a gateway listen on several ports and then redirects connections to other IP adresses.
          +With regard to +Libnodave, you are free to use other port numbers. While you cannot change port numbers on S7 devices or IBH NetLinks, this can be useful with port redirecting software like +
          rinetd, which makes a gateway listen on several ports and then redirects connections to other IP adresses.
          This is the reason, why default port numbers are not hard coded in Libnodave. \ No newline at end of file diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/pdu.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/pdu.html index 1477953f..a479c827 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/pdu.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/pdu.html @@ -5,56 +5,182 @@

          PDU (protocol data unit)

        • A data area
        • Header: - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0allways 0x32
          1type1,2,3 or 7
          2,3unknown0
          4,5sequence number
          6,7length of parameters
          8,9length of data
          10,11error code
          Positionmeaningpossible values
          0allways 0x32
          1type1,2,3 or 7
          2,3unknown0
          4,5sequence number
          6,7length of parameters
          8,9length of data
          10,11error code
          Parameters: - - - + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0a function number
          restdepends on function number
          Positionmeaningpossible values
          0a function number
          restdepends on function number
          Data: - - + + + + + + + + + +
          Positionmeaningpossible values
          restdepends on function number
          Positionmeaningpossible values
          restdepends on function number
          Parameters for read request: - - - - + + + + + + + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0function number for read4
          1number of items to read1..20
          2..item adresses, 12 byte each
          Positionmeaningpossible values
          0function number for read4
          1number of items to read1..20
          2..item adresses, 12 byte each
          Forming the item address: - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0,1,2unknownallways 0x12, 0x0a, 0x10
          3transport size or unit size1=single bit, 2=byte, 4=word
          4,5length in byte
          6,7number of data block0 for ares other than data block
          8area codesee area
          9,10,11Start address in bits.multiples of 8, if unit size is not bits
          Positionmeaningpossible values
          0,1,2unknownallways 0x12, 0x0a, 0x10
          3transport size or unit size1=single bit, 2=byte, 4=word
          4,5length in byte
          6,7number of data block0 for ares other than data block
          8area codesee area
          9,10,11Start address in bits.multiples of 8, if unit size is not bits
          read response: - - - - + + + + + + + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0function number for read4
          1number read items1..20
          2..items, 4 byte "data header" +data each
          Positionmeaningpossible values
          0function number for read4
          1number read items1..20
          2..items, 4 byte "data header" +data each
          Data header: - - - - + + + + + + + + + + + + + + + + + + + +
          Positionmeaningpossible values
          0return code0xFF means ok, data follows after this header. Other codes give reasons why no data is returned.
          1transport size or unit size4=single bit, 9=byte
          2,3length in bits
          Positionmeaningpossible values
          0return code0xFF means ok, data follows after this header. Other codes give reasons why no data is returned.
          1transport size or unit size4=single bit, 9=byte
          2,3length in bits
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/readmultiple.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/readmultiple.html index 04abeb5b..2691b81b 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/readmultiple.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/readmultiple.html @@ -1,12 +1,12 @@

          Read multiple items

          -The purpose of this mechanism ist to read multiple blocks of bytes from different start addresses and/or memory +The purpose of this mechanism ist to read multiple blocks of bytes from different start addresses and/or memory areas with a single request to the PLC.

          Basics:

          -First, you have to prepare an "empty" read request, i.e. one that doesn't contain the address of an -item. You need a variable of type PDU to store the request. To this request, you add the desired +First, you have to prepare an "empty" read request, i.e. one that doesn't contain the address of an +item. You need a variable of type PDU to store the request. To this request, you add the desired items using the same parameters you would specify to daveReadBytes. You may add up to 20 difeerent items (limit introduced by Siemens PLCs) provided that the result -data fits into a single response PDU. When you have added all desired items, call +data fits into a single response PDU. When you have added all desired items, call daveExecReadRequest which performs the actual data exchange with the PLC. Example:
               PDU p;
          @@ -18,13 +18,13 @@ 

          Basics:

          daveAddVarToReadRequest(&p,daveFlags,0,12,2); res=daveExecReadRequest(dc, &p, &rs);
          -Now the daveResultSet should contain a result for each item. Each result contains error information, +Now the daveResultSet should contain a result for each item. Each result contains error information, length information and the resulting byte array. You can use these results in two ways: Either access the structure daveResult directly or use:
          - daveUseResult(daveConnection *, daveResultSet * rs, int number); +daveUseResult(daveConnection *, daveResultSet * rs, int number); -This will set the internal result pointer of the daveConnection +This will set the internal result pointer of the daveConnection to the result byte array. After doing this, the normal conversion functions can be used to transfer single values to C variables. Example:
          @@ -34,7 +34,7 @@ 

          Basics:

          printf("%d\n",a); } else printf("*** Error: %s\n",daveStrerror(res)); -
          +
               res=daveUseResult(dc, rs, 1); // 2nd result
               if (res==0) {
          @@ -47,5 +47,5 @@ 

          Basics:

               daveFreeResults(&rs);  
           
          -This will free the memory occupied by the single results (but not by the resultSet itself), +This will free the memory occupied by the single results (but not by the resultSet itself), leaving you with an empty reultSet that can be reused in the next multi item read. diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/setport.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/setport.html index fe55cb64..b9089762 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/setport.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/setport.html @@ -1,5 +1,5 @@

          setport

          -An OS specific routine to configure and open a serial port. +An OS specific routine to configure and open a serial port. There are different implementations for LINUX and WIN32. While the respective implementation of setport() is part of LIBNODAVE dynamic library, you could use your own routine and copy the resulting filedescriptor/handle to the diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/speedissues.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/speedissues.html index 9827f008..7bb8a432 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/speedissues.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/speedissues.html @@ -1,73 +1,198 @@

          Conversion routines

          -The buffers used by daveReadBytes() and daveWriteBytes() will contain a copy of the PLC memory area. This means: If you read from the beginning of DB2, the buffer will contain a byte for byte copy of DB2. The values are the same and in the same order, as what you get when you observe byte variables in Step7. Example:
          +The buffers used by daveReadBytes() and daveWriteBytes() will contain a copy of the PLC memory area. This means: If you read from the beginning of DB2, the buffer will contain a byte for byte copy of DB2. The values are the same and in the same order, as what you get when you observe byte variables in Step7. Example: +
          - - - - - -
          DB20.DBB026
          DB20.DBB137
          DB20.DBB248
          DB20.DBB315
          DB20.DBB416
          -You are free to interpret these values as single bytes or multibyte values,the same way as you can do this in Step7 AWL.:
          -Also it is unusual, you can load a real value from DB20.DBD1:
          + + + + + + + + + + + + + + + + + + + + +
          DB20.DBB026
          DB20.DBB137
          DB20.DBB248
          DB20.DBB315
          DB20.DBB416
          + You are free to interpret these values as single bytes or multibyte values,the same way as you can do this in Step7 AWL.:
          + Also it is unusual, you can load a real value from DB20.DBD1:
           L DB20.DBD1
           L 2.0
           *R
           
          -A further complication results from the fact that Siemens PLCs store multibyte values beginning with the most significant byte (big endian) while Intel based PCs store the least significant byte first (little endian).
          -It is not possible to convert the byte order in the daveReadBytes() or daveWriteBytes() fuctions -because the start position of each multibyte value is not known then.
          -You are free to place such values at arbitrary byte addresses in your PLC program. -The same adresses must in turn be used to retrieve values from the copy of PLC memory. -If you have a data block DB2 with the following layout:
          -
          - - - -
          DBB 0BYTE
          DBD 1DWORD
          DBD 5REAL
          -You can retrieve the single values in three ways:
          -1. From the intenal buffer. After a successful call, an internal pointer points to the 1st byte. -Now use daveGetU8(dc) to get the value of the first byte as an unsigned value. The internal buffer pointer -is incremented by 1, now pointing to the copy of DBD1. Use daveGetS32(dc) to get the value of the -of the next 4 bytes as a signed value. The internal pointer is incremented by 4, now pointing to -the copy of DBD5. Use daveGetFloat(dc) to get the value of the next 4 bytes as a single precision -float.
          -2. From the internal buffer, specifying a position. Use daveGetU8at(dc,0) to get the value of the -first byte as an unsigned value. Next use daveGetS32at(dc,1) to get the value of the 4 bytes -starting at 1 as a signed value. Finally, use daveGetFloatat(dc,5) to get the value of the 4 bytes -starting at 5 as a single precision float. You may perform these operation in any order and also -repeat them.
          -3. From a user buffer. Use daveGetU8from(buffer) to get the value of the first byte as an -unsigned value. Use daveGetS32from(buffer+1) to get the value of the 4 bytes at buffer+1, i.e. -DBD 1, as a signed value. Use daveGetFloatat(buffer+5) to get the value of the 4 bytes starting -at buffer+5 as a single precision float, i.e. DBD5.
          -The conversion functions are named after the bit length and signedness they assume: - - - - - - - - - -
          int bufferint buffer+posbuffer pointersizesignedC-return typePascal ret type
          daveGetU8daveGetU8atdaveGetU8from8 bit=1 bytenointlongint
          daveGetS8daveGetS8atdaveGetS8from8 bit=1 byteyesintlongint
          daveGetU16daveGetU16atdaveGetU16from16 bit=2 bytenointlongint
          daveGetS16daveGetS16atdaveGetS16from16 bit=2 byteyesintlongint
          daveGetU32daveGetU32atdaveGetU32from32 bit=4 bytenounsigned intlongint
          daveGetS32daveGetS32atdaveGetS32from32 bit=4 byteyesintlongint
          daveGetFloatdaveGetFloatatdaveGetFloatfrom32 bit=4 byteyesfloatsingle
          + A further complication results from the fact that Siemens PLCs store multibyte values beginning with the most significant byte (big + endian) while Intel based PCs store the least significant byte first (little endian).
          + It is not possible to convert the byte order in the daveReadBytes() or daveWriteBytes() fuctions + because the start position of each multibyte value is not known then.
          + You are free to place such values at arbitrary byte addresses in your PLC program. + The same adresses must in turn be used to retrieve values from the copy of PLC memory. + If you have a data block DB2 with the following layout:
          + + + + + + + + + + + + + +
          DBB 0BYTE
          DBD 1DWORD
          DBD 5REAL
          + You can retrieve the single values in three ways:
          + 1. From the intenal buffer. After a successful call, an internal pointer points to the 1st byte. + Now use daveGetU8(dc) to get the value of the first byte as an unsigned value. The internal buffer pointer + is incremented by 1, now pointing to the copy of DBD1. Use daveGetS32(dc) to get the value of the + of the next 4 bytes as a signed value. The internal pointer is incremented by 4, now pointing to + the copy of DBD5. Use daveGetFloat(dc) to get the value of the next 4 bytes as a single precision + float.
          + 2. From the internal buffer, specifying a position. Use daveGetU8at(dc,0) to get the value of the + first byte as an unsigned value. Next use daveGetS32at(dc,1) to get the value of the 4 bytes + starting at 1 as a signed value. Finally, use daveGetFloatat(dc,5) to get the value of the 4 bytes + starting at 5 as a single precision float. You may perform these operation in any order and also + repeat them.
          + 3. From a user buffer. Use daveGetU8from(buffer) to get the value of the first byte as an + unsigned value. Use daveGetS32from(buffer+1) to get the value of the 4 bytes at buffer+1, i.e. + DBD 1, as a signed value. Use daveGetFloatat(buffer+5) to get the value of the 4 bytes starting + at buffer+5 as a single precision float, i.e. DBD5.
          + The conversion functions are named after the bit length and signedness they assume: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          int bufferint buffer+posbuffer pointersizesignedC-return typePascal ret type
          daveGetU8daveGetU8atdaveGetU8from8 bit=1 bytenointlongint
          daveGetS8daveGetS8atdaveGetS8from8 bit=1 byteyesintlongint
          daveGetU16daveGetU16atdaveGetU16from16 bit=2 bytenointlongint
          daveGetS16daveGetS16atdaveGetS16from16 bit=2 byteyesintlongint
          daveGetU32daveGetU32atdaveGetU32from32 bit=4 bytenounsigned intlongint
          daveGetS32daveGetS32atdaveGetS32from32 bit=4 byteyesintlongint
          daveGetFloatdaveGetFloatatdaveGetFloatfrom32 bit=4 byteyesfloatsingle
          -There had been an older set of those functions named after data types, e.g. -daveGetDWORD(). Those functions should not be used any more, as there names might be -misunderstandable between PLC and C or other programming languages. They are still supported -for compatibility with older versions. These functions had been inlined in earlier versions -but are now not inlined by default, because other languages than C cannot make use of inline -definitions in a C header file. -

          Notes:

          -Most commercial libraries handle the conversion issue differently: They provide functions to read one or a set of words, one or a set of long words, one or a set of reals. On the first glance, this might seem more convenient and it is as long as it can be applied to PLC memory areas containing only elements of the same type and size. But when you have to deal with data of mixed type and size, you would have to use another call to daveReadBytes() each time the type or size differs from the former. And each call contributes the overhead of the protocol and the response time of the PLC. Other libraries provide a way to read multiple items with a single call. So does Libnodave. You could also use it to retrieve data located on different boundaries. But this is limited to 20 items by the PLC. And it introduces some overhead as an address has to be transmitted for each item in the request. Use read multiple items to access data from different DBs or other memory areas when the combined results will fit in a single response. - - - - - - - - -
          When you want to readdoremark
          DB20.DBD0..DBD20read 24 bytes starting at DBB0
          DB20.DBD0..DBD8 and DBD20read 24 bytes starting at DBB0just do not evaluate bytes 11 to 19 of result.
          DB20.DBD0..DBD8 and DBD120either read 124 bytes starting at DBB0just do not evaluate bytes 11 to 119 of result.
          or use multiple read on: item1:DB20.DBD0..DBD8, item2:DB20.DBD120 you have to deal with the result set.
          DB20.DBD0..DBD8 and DB21.DBD120use multiple read on: item1:DB20.DBD0..DBD8, item2:DB21.DBD120 this is the only way to read from different DBs with a single request/reponse.
          DB20.DBD0..DBD118 and DB21.DBD4..DBD80use two calls to daveReadBytesthis is the only way if the two combined results will not fit into a single PDU.
          + There had been an older set of those functions named after data types, e.g. + daveGetDWORD(). Those functions should not be used any more, as there names might be + misunderstandable between PLC and C or other programming languages. They are still supported + for compatibility with older versions. These functions had been inlined in earlier versions + but are now not inlined by default, because other languages than C cannot make use of inline + definitions in a C header file. +

          Notes:

          + Most commercial libraries handle the conversion issue differently: They provide functions to read one or a set of words, one or a + set of long words, one or a set of reals. On the first glance, this might seem more convenient and it is as long as it can be + applied to PLC memory areas containing only elements of the same type and size. But when you have to deal with data of mixed type + and size, you would have to use another call to daveReadBytes() each time the type or size differs from the former. And each call + contributes the overhead of the protocol and the response time of the PLC. Other libraries provide a way to read multiple items with + a single call. So does Libnodave. You could also use it to retrieve data located on different boundaries. But this is limited + to 20 items by the PLC. And it introduces some overhead as an address has to be transmitted for each item in the request. Use read + multiple items to access data from different DBs or other memory areas when the combined results will fit in a single response. +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          When you want to read + + doremark
          DB20.DBD0..DBD20read 24 bytes starting at DBB0
          DB20.DBD0..DBD8 and DBD20read 24 bytes starting at DBB0just do not evaluate bytes 11 to 19 of result.
          DB20.DBD0..DBD8 and DBD120either read 124 bytes starting at DBB0just do not evaluate bytes 11 to 119 of result.
          or use multiple read on: item1:DB20.DBD0..DBD8, item2:DB20.DBD120you have to deal with the result set.
          DB20.DBD0..DBD8 and DB21.DBD120use multiple read on: item1:DB20.DBD0..DBD8, item2:DB21.DBD120this is the only way to read from different DBs with a single request/reponse.
          DB20.DBD0..DBD118 and DB21.DBD4..DBD80use two calls to daveReadBytesthis is the only way if the two combined results will not fit into a single PDU.
          diff --git a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/writemultiple.html b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/writemultiple.html index 24910038..d6a25501 100644 --- a/projects/driver/s7plc/libnodave-java/native/libnodave/doc/writemultiple.html +++ b/projects/driver/s7plc/libnodave-java/native/libnodave/doc/writemultiple.html @@ -1,12 +1,12 @@

          Write multiple items

          -The purpose of this mechanism ist to write multiple blocks of bytes from different start addresses and/or memory +The purpose of this mechanism ist to write multiple blocks of bytes from different start addresses and/or memory areas with a single request to the PLC.

          Basics:

          -First, you have to prepare an "empty" write request, i.e. one that doesn't contain the address of an -item. You need a variable of type PDU to store the request. To this request, you add the desired +First, you have to prepare an "empty" write request, i.e. one that doesn't contain the address of an +item. You need a variable of type PDU to store the request. To this request, you add the desired items using the same parameters you would specify to daveWriteBytes. You may add up to 20 different items (limit introduced by Siemens PLCs) provided that the result -data fits into a single response PDU. When you have added all desired items, call +data fits into a single response PDU. When you have added all desired items, call daveExecWriteRequest which performs the actual data exchange with the PLC. Example:
               PDU p;
          @@ -23,10 +23,10 @@ 

          Basics:

          You can use these results accessing the structure daveResult directly.
           	printf("*** Error: %s\n",daveStrerror(rs.results[2].error));
          -
          - If you do not need the results any more, call: +
          +If you do not need the results any more, call:
               daveFreeResults(&rs);  
           
          -This will free the memory occupied by the single results (but not by the resultSet itself), +This will free the memory occupied by the single results (but not by the resultSet itself), leaving you with an empty reultSet that can be reused in the next multi item read. diff --git a/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Connection.java b/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Connection.java index 216c85dd..13bdfa09 100644 --- a/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Connection.java +++ b/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Connection.java @@ -3,47 +3,45 @@ import java.io.IOException; /* - * Bundle-NativeCode: lib/i386/libnodave.so;lib/i386/liblibnodave-native.so;osname=Linux;processor=i386,lib/arm/libnodave.so;lib/arm/liblibnodave-native.so;osname=Linux;processor=arm + * Bundle-NativeCode: lib/i386/libnodave.so;lib/i386/liblibnodave-native.so;osname=Linux;processor=i386,lib/arm/libnodave.so; + * lib/arm/liblibnodave-native.so;osname=Linux;processor=arm */ public class Connection { - private long conHandle; - - public static final int AREA_DB = 0x84; - public static final int AREA_INPUTS = 0x81; - public static final int AREA_OUTPUTS = 0x82; - public static final int AREA_FLAGS = 0x82; - public static final int AREA_DIRECT_PERIPHERAL = 0x80; - - public Connection(Interface ifc, int mpiAddr, int rack, int slot) { - this.conHandle = Interface.daveNewConnection(ifc.getHandle(), mpiAddr, rack, slot); - } - - public synchronized boolean connectPLC() { - - if (Interface.daveConnectPLC(this.conHandle) == 0) - return true; - else - return false; - } - - public synchronized void disconnectPLC() { - Interface.daveDisconnectPLC(this.conHandle); - } - - public synchronized void writeBytes(int area, int areaNumber, int startAddress, int length, byte[] buffer) throws IOException { - Interface.daveWriteBytes(this.conHandle, area, areaNumber, startAddress, length, buffer); - } - - public synchronized void setBit(int area, int areaNumber, int byteAddr, int bitAddr) throws IOException { - Interface.daveSetBit(this.conHandle, area, areaNumber, byteAddr, bitAddr); - } - - public synchronized void clrBit(int area, int areaNumber, int byteAddr, int bitAddr) throws IOException { - Interface.daveClrBit(this.conHandle, area, areaNumber, byteAddr, bitAddr); - } - - public synchronized byte[] readBytes(int area, int areaNumber, int startAddress, int length) throws IOException { - return Interface.daveReadBytes(this.conHandle, area, areaNumber, startAddress, length); - } + private long conHandle; + + public static final int AREA_DB = 0x84; + public static final int AREA_INPUTS = 0x81; + public static final int AREA_OUTPUTS = 0x82; + public static final int AREA_FLAGS = 0x82; + public static final int AREA_DIRECT_PERIPHERAL = 0x80; + + public Connection(Interface ifc, int mpiAddr, int rack, int slot) { + this.conHandle = Interface.daveNewConnection(ifc.getHandle(), mpiAddr, rack, slot); + } + + public synchronized boolean connectPLC() { + + if (Interface.daveConnectPLC(this.conHandle) == 0) { return true; } else return false; + } + + public synchronized void disconnectPLC() { + Interface.daveDisconnectPLC(this.conHandle); + } + + public synchronized void writeBytes(int area, int areaNumber, int startAddress, int length, byte[] buffer) throws IOException { + Interface.daveWriteBytes(this.conHandle, area, areaNumber, startAddress, length, buffer); + } + + public synchronized void setBit(int area, int areaNumber, int byteAddr, int bitAddr) throws IOException { + Interface.daveSetBit(this.conHandle, area, areaNumber, byteAddr, bitAddr); + } + + public synchronized void clrBit(int area, int areaNumber, int byteAddr, int bitAddr) throws IOException { + Interface.daveClrBit(this.conHandle, area, areaNumber, byteAddr, bitAddr); + } + + public synchronized byte[] readBytes(int area, int areaNumber, int startAddress, int length) throws IOException { + return Interface.daveReadBytes(this.conHandle, area, areaNumber, startAddress, length); + } } diff --git a/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Interface.java b/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Interface.java index c937c769..6dd06b02 100644 --- a/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Interface.java +++ b/projects/driver/s7plc/libnodave-java/src/main/java/com/libnodave/Interface.java @@ -3,78 +3,82 @@ import java.io.IOException; public final class Interface { - - static { -// String osName = System.getProperty("org.osgi.framework.os.name"); -// -// System.out.println("osName: " + osName); -// -// if (osName.contains("Windows")) { -// System.out.println("Loading libnodave on windows"); -// System.loadLibrary("libnodave"); -// } - - System.loadLibrary("libnodave-native"); - } - - private long ifaceHandle; - private int socket = 0; - - protected static native int daveOpenSocket(String hostname, int port); - protected static native void daveCloseSocket(int socket); - protected static native long daveNewInterface(String name, int socket); - protected static native void daveSetTimeout(long handle, long timeout); - protected static native long daveNewConnection(long handle, int mpiAddr, int rack, int slot); - protected static native int daveConnectPLC(long dc); - protected static native int daveDisconnectPLC(long dc); - protected static native byte[] daveReadBytes(long dc, int area, int areaNumber, - int startAddress, int length) throws IOException; - - //TODO native side to be implemented - protected static native void daveWriteBytes(long dc, int area, int areaNumber, - int startAddress, int length, byte[] buffer) throws IOException; - - protected static native int daveSetBit(long dc, int area, int areaNumber, int byteAdr, int bitAdr) throws IOException; - - protected static native int daveClrBit(long dc, int area, int areaNumber, int byteAdr, int bitAdr) throws IOException; - - public Interface(String name, String hostname, int port) throws IOException { - this.socket = daveOpenSocket(hostname, port); - - if (this.socket == 0) - throw new IOException("Cannot create socket to " + hostname + ":" + port); - - this.ifaceHandle = daveNewInterface(name, this.socket); - - if (this.ifaceHandle == 0) - throw new IOException("Cannot create interface to " + hostname + ":" + port); - } - - protected long getHandle() { - return this.ifaceHandle; - } - - protected int getSocket() { - return this.socket; - } - - public void setTimeout(long timeout) { - daveSetTimeout(ifaceHandle, timeout); - } - - public void close() { - if (this.socket != 0) { - daveCloseSocket(this.socket); - this.socket = 0; - } - } - - protected void finalize() throws Throwable { - try { - this.close(); - } finally { - super.finalize(); - } - } - + + static { + // String osName = System.getProperty("org.osgi.framework.os.name"); + // + // System.out.println("osName: " + osName); + // + // if (osName.contains("Windows")) { + // System.out.println("Loading libnodave on windows"); + // System.loadLibrary("libnodave"); + // } + + System.loadLibrary("libnodave-native"); + } + + private long ifaceHandle; + private int socket = 0; + + protected static native int daveOpenSocket(String hostname, int port); + + protected static native void daveCloseSocket(int socket); + + protected static native long daveNewInterface(String name, int socket); + + protected static native void daveSetTimeout(long handle, long timeout); + + protected static native long daveNewConnection(long handle, int mpiAddr, int rack, int slot); + + protected static native int daveConnectPLC(long dc); + + protected static native int daveDisconnectPLC(long dc); + + protected static native byte[] daveReadBytes(long dc, int area, int areaNumber, int startAddress, int length) throws IOException; + + //TODO native side to be implemented + protected static native void daveWriteBytes(long dc, int area, int areaNumber, int startAddress, int length, byte[] buffer) throws + IOException; + + protected static native int daveSetBit(long dc, int area, int areaNumber, int byteAdr, int bitAdr) throws IOException; + + protected static native int daveClrBit(long dc, int area, int areaNumber, int byteAdr, int bitAdr) throws IOException; + + public Interface(String name, String hostname, int port) throws IOException { + this.socket = daveOpenSocket(hostname, port); + + if (this.socket == 0) throw new IOException("Cannot create socket to " + hostname + ":" + port); + + this.ifaceHandle = daveNewInterface(name, this.socket); + + if (this.ifaceHandle == 0) throw new IOException("Cannot create interface to " + hostname + ":" + port); + } + + protected long getHandle() { + return this.ifaceHandle; + } + + protected int getSocket() { + return this.socket; + } + + public void setTimeout(long timeout) { + daveSetTimeout(ifaceHandle, timeout); + } + + public void close() { + if (this.socket != 0) { + daveCloseSocket(this.socket); + this.socket = 0; + } + } + + protected void finalize() throws Throwable { + try { + this.close(); + } finally { + super.finalize(); + } + } + } diff --git a/projects/driver/s7plc/libnodave-java/src/test/java/com/libnodave/Test.java b/projects/driver/s7plc/libnodave-java/src/test/java/com/libnodave/Test.java index a0417c59..113193e0 100644 --- a/projects/driver/s7plc/libnodave-java/src/test/java/com/libnodave/Test.java +++ b/projects/driver/s7plc/libnodave-java/src/test/java/com/libnodave/Test.java @@ -6,123 +6,122 @@ public class Test { - /** - * @param args - * @throws IOException - */ - public static void main(String[] args) throws IOException { - byte[] buf = null; - - // TODO Auto-generated method stub - Interface ifc = new Interface("IF1", "10.0.0.7", 102); - // Interface ifc = new Interface("IF1", "192.168.1.110", 102); - - ifc.setTimeout(5000000); - + /** + * @param args + * @throws IOException + */ + public static void main(String[] args) throws IOException { + byte[] buf = null; + + // TODO Auto-generated method stub + Interface ifc = new Interface("IF1", "10.0.0.7", 102); + // Interface ifc = new Interface("IF1", "192.168.1.110", 102); + + ifc.setTimeout(5000000); + + + System.out.println("New connection..."); + Connection con = new Connection(ifc, 2, 0, 2); + + System.out.println("connect..."); + con.connectPLC(); + + System.out.println("read DB150 ..."); + try { + buf = con.readBytes(Connection.AREA_DB, 150, 0, 24); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + System.out.printf("Byte 0: [%02x]", (short) (0xff & (int) buf[0])); - - System.out.println("New connection..."); - Connection con = new Connection(ifc, 2, 0, 2); - - System.out.println("connect..."); - con.connectPLC(); - - System.out.println("read DB150 ..."); - try { - buf = con.readBytes(Connection.AREA_DB, 150, 0 , 24); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - System.out.printf("Byte 0: [%02x]", (short) (0xff & (int) buf[0])); - /* Write a REAL value */ - ByteBuffer bbuf; - bbuf = ByteBuffer.wrap(buf); - bbuf.order(ByteOrder.BIG_ENDIAN); - bbuf.putFloat(0, (float) 25.5); - try { - con.writeBytes(Connection.AREA_DB, 150, 10, 4, buf); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - System.out.println("read bytes..."); - try { - buf = con.readBytes(Connection.AREA_DB, 18, 0 , 128); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - System.out.println("read bytes..."); - - System.out.println("buf.length: " + buf.length); - - for (int i = 0; i < 128; i++) { - System.out.printf("[%02x]", (short) (0xff & (int) buf[i])); - } - - try { - con.setBit(Connection.AREA_DB, 150, 0, 2); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } + ByteBuffer bbuf; + bbuf = ByteBuffer.wrap(buf); + bbuf.order(ByteOrder.BIG_ENDIAN); + bbuf.putFloat(0, (float) 25.5); + try { + con.writeBytes(Connection.AREA_DB, 150, 10, 4, buf); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + System.out.println("read bytes..."); + try { + buf = con.readBytes(Connection.AREA_DB, 18, 0, 128); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + System.out.println("read bytes..."); + + System.out.println("buf.length: " + buf.length); + + for (int i = 0; i < 128; i++) { + System.out.printf("[%02x]", (short) (0xff & (int) buf[i])); + } + + try { + con.setBit(Connection.AREA_DB, 150, 0, 2); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } /* Setze Bit */ - for (int i = 0; i < 10; i++) { - - System.out.println("Toggle bit"); - try { - con.setBit(Connection.AREA_DB, 150, 0, 4); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - con.clrBit(Connection.AREA_DB, 150, 0, 4); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - try { - con.setBit(Connection.AREA_DB, 150, 0, 3); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + for (int i = 0; i < 10; i++) { + + System.out.println("Toggle bit"); + try { + con.setBit(Connection.AREA_DB, 150, 0, 4); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + con.clrBit(Connection.AREA_DB, 150, 0, 4); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + try { + con.setBit(Connection.AREA_DB, 150, 0, 3); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } /* Parse data block */ - bbuf = ByteBuffer.wrap(buf); - bbuf.order(ByteOrder.BIG_ENDIAN); - bbuf.position(0); - - System.out.println("Betriebsstunden: " + (0xffff & (int) bbuf.getShort())); - System.out.println("Netzspannung L1: " + bbuf.getFloat(56)); - System.out.println("Drehzahl: " + bbuf.getFloat(36)); - System.out.println("Power: " + bbuf.getFloat(100)); - } + bbuf = ByteBuffer.wrap(buf); + bbuf.order(ByteOrder.BIG_ENDIAN); + bbuf.position(0); + + System.out.println("Betriebsstunden: " + (0xffff & (int) bbuf.getShort())); + System.out.println("Netzspannung L1: " + bbuf.getFloat(56)); + System.out.println("Drehzahl: " + bbuf.getFloat(36)); + System.out.println("Power: " + bbuf.getFloat(100)); + } } diff --git a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/MalformendObjectLocatorException.java b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/MalformendObjectLocatorException.java index f925aeda..87f2dc96 100644 --- a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/MalformendObjectLocatorException.java +++ b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/MalformendObjectLocatorException.java @@ -22,10 +22,10 @@ public class MalformendObjectLocatorException extends Exception { - public MalformendObjectLocatorException(String msg) { - super(msg); - } + public MalformendObjectLocatorException(String msg) { + super(msg); + } - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7ChannelAddress.java b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7ChannelAddress.java index 75e23339..f36a8e19 100644 --- a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7ChannelAddress.java +++ b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7ChannelAddress.java @@ -23,164 +23,152 @@ import com.libnodave.Connection; /** - * * Parse an object locator for the Siemens S7 PLC driver - * + *

          * Object locator format: - * + *

          * DB<data block no>.<byte offset>.<data type> - * + *

          * examples DB20.2.uint16 means data block 20, byte offset 2, variable type 16bit unsigned integer - * + *

          * DB10.10.float maps to a REAL variable - * + * * @author mzillgit - * */ public class S7ChannelAddress { - public static final byte TYPE_BIT = 0; - public static final byte TYPE_INT8 = 1; - public static final byte TYPE_UINT8 = 2; - public static final byte TYPE_INT16 = 3; - public static final byte TYPE_UINT16 = 4; - public static final byte TYPE_INT32 = 5; - public static final byte TYPE_UINT32 = 6; - public static final byte TYPE_INT64 = 7; - public static final byte TYPE_UINT64 = 8; - public static final byte TYPE_FLOAT = 9; - public static final byte TYPE_DOUBLE = 10; - - private int memoryArea; - private int areaAddress; - private int offset; - private byte type; - private byte bitPos; - - public S7ChannelAddress(String locator) throws MalformendObjectLocatorException { - int areaAddressPos = 0; - - if (locator.startsWith("DB")) { - memoryArea = Connection.AREA_DB; - areaAddressPos = 2; - } - else { - throw new MalformendObjectLocatorException("Unknown area"); - } - - int offsetPos = locator.indexOf('.'); - try { - areaAddress = Integer.parseInt(locator.substring(areaAddressPos, offsetPos)); - } catch (NumberFormatException e) { - throw new MalformendObjectLocatorException("NumberFormatException in areaAddress"); - } - - int typePos = locator.indexOf(':'); - try { - offset = Integer.parseInt(locator.substring(offsetPos + 1, typePos)); - } catch (NumberFormatException e) { - throw new MalformendObjectLocatorException("NumberFormatException in offset"); - } - - String typeStr = locator.substring(typePos + 1); - - if (typeStr.equals("float")) { - type = TYPE_FLOAT; - } - else if (typeStr.equals("uint8")) { - type = TYPE_UINT8; - } - else if (typeStr.equals("int8")) { - type = TYPE_INT8; - } - else if (typeStr.equals("uint16")) { - type = TYPE_UINT16; - } - else if (typeStr.equals("int16")) { - type = TYPE_INT16; - } - else if (typeStr.equals("uint32")) { - type = TYPE_UINT32; - } - else if (typeStr.equals("int32")) { - type = TYPE_INT32; - } - else if (typeStr.equals("double")) { - type = TYPE_DOUBLE; - } - else if (typeStr.startsWith("bit(")) { - type = TYPE_BIT; - String bitPos = locator.substring(typePos + 5, typePos + 6); - try { - this.bitPos = Byte.parseByte(bitPos); - } catch (Exception e) { - throw new MalformendObjectLocatorException("Invalid bit locator"); - } - } - else { - throw new MalformendObjectLocatorException("Unknown or missing type"); - } - } - - public int getMemoryArea() { - return memoryArea; - } - - public int getAreaAddress() { - return areaAddress; - } - - public int getOffset() { - return offset; - } - - public int getDataLength() { - - switch (type) { - case TYPE_BIT: - case TYPE_UINT8: - case TYPE_INT8: - return 1; - case TYPE_UINT16: - case TYPE_INT16: - return 2; - case TYPE_UINT32: - case TYPE_INT32: - case TYPE_FLOAT: - return 4; - case TYPE_UINT64: - case TYPE_INT64: - case TYPE_DOUBLE: - return 8; - default: - return -1; - } - } - - public byte getType() { - return type; - } - - public byte getBitPos() { - return bitPos; - } - - // public static void main(String[] args) { - // try { - // S7ObjectLocator loc = new S7ObjectLocator("DB3.0:float"); - // System.out.println("Area DB? " + loc.getAreaAddress() + "." + - // loc.getOffset() + " type:" + loc.getType()); - // - // loc = new S7ObjectLocator("DB3.123:uint16"); - // System.out.println("Area DB? " + loc.getAreaAddress() + "." + - // loc.getOffset() + " type:" + loc.getType()); - // - // loc = new S7ObjectLocator("DB18.24:double"); - // System.out.println("Area DB? " + loc.getAreaAddress() + "." + - // loc.getOffset() + " type:" + loc.getType()); - // } catch (MalformendObjectLocatorException e) { - // e.printStackTrace(); - // } - // } + public static final byte TYPE_BIT = 0; + public static final byte TYPE_INT8 = 1; + public static final byte TYPE_UINT8 = 2; + public static final byte TYPE_INT16 = 3; + public static final byte TYPE_UINT16 = 4; + public static final byte TYPE_INT32 = 5; + public static final byte TYPE_UINT32 = 6; + public static final byte TYPE_INT64 = 7; + public static final byte TYPE_UINT64 = 8; + public static final byte TYPE_FLOAT = 9; + public static final byte TYPE_DOUBLE = 10; + + private int memoryArea; + private int areaAddress; + private int offset; + private byte type; + private byte bitPos; + + public S7ChannelAddress(String locator) throws MalformendObjectLocatorException { + int areaAddressPos = 0; + + if (locator.startsWith("DB")) { + memoryArea = Connection.AREA_DB; + areaAddressPos = 2; + } else { + throw new MalformendObjectLocatorException("Unknown area"); + } + + int offsetPos = locator.indexOf('.'); + try { + areaAddress = Integer.parseInt(locator.substring(areaAddressPos, offsetPos)); + } catch (NumberFormatException e) { + throw new MalformendObjectLocatorException("NumberFormatException in areaAddress"); + } + + int typePos = locator.indexOf(':'); + try { + offset = Integer.parseInt(locator.substring(offsetPos + 1, typePos)); + } catch (NumberFormatException e) { + throw new MalformendObjectLocatorException("NumberFormatException in offset"); + } + + String typeStr = locator.substring(typePos + 1); + + if (typeStr.equals("float")) { + type = TYPE_FLOAT; + } else if (typeStr.equals("uint8")) { + type = TYPE_UINT8; + } else if (typeStr.equals("int8")) { + type = TYPE_INT8; + } else if (typeStr.equals("uint16")) { + type = TYPE_UINT16; + } else if (typeStr.equals("int16")) { + type = TYPE_INT16; + } else if (typeStr.equals("uint32")) { + type = TYPE_UINT32; + } else if (typeStr.equals("int32")) { + type = TYPE_INT32; + } else if (typeStr.equals("double")) { + type = TYPE_DOUBLE; + } else if (typeStr.startsWith("bit(")) { + type = TYPE_BIT; + String bitPos = locator.substring(typePos + 5, typePos + 6); + try { + this.bitPos = Byte.parseByte(bitPos); + } catch (Exception e) { + throw new MalformendObjectLocatorException("Invalid bit locator"); + } + } else { + throw new MalformendObjectLocatorException("Unknown or missing type"); + } + } + + public int getMemoryArea() { + return memoryArea; + } + + public int getAreaAddress() { + return areaAddress; + } + + public int getOffset() { + return offset; + } + + public int getDataLength() { + + switch (type) { + case TYPE_BIT: + case TYPE_UINT8: + case TYPE_INT8: + return 1; + case TYPE_UINT16: + case TYPE_INT16: + return 2; + case TYPE_UINT32: + case TYPE_INT32: + case TYPE_FLOAT: + return 4; + case TYPE_UINT64: + case TYPE_INT64: + case TYPE_DOUBLE: + return 8; + default: + return -1; + } + } + + public byte getType() { + return type; + } + + public byte getBitPos() { + return bitPos; + } + + // public static void main(String[] args) { + // try { + // S7ObjectLocator loc = new S7ObjectLocator("DB3.0:float"); + // System.out.println("Area DB? " + loc.getAreaAddress() + "." + + // loc.getOffset() + " type:" + loc.getType()); + // + // loc = new S7ObjectLocator("DB3.123:uint16"); + // System.out.println("Area DB? " + loc.getAreaAddress() + "." + + // loc.getOffset() + " type:" + loc.getType()); + // + // loc = new S7ObjectLocator("DB18.24:double"); + // System.out.println("Area DB? " + loc.getAreaAddress() + "." + + // loc.getOffset() + " type:" + loc.getType()); + // } catch (MalformendObjectLocatorException e) { + // e.printStackTrace(); + // } + // } } diff --git a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcConnection.java b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcConnection.java index 29097404..5a92af0a 100644 --- a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcConnection.java +++ b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcConnection.java @@ -20,326 +20,299 @@ */ package org.openmuc.framework.driver.s7plc; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; - +import com.libnodave.Connection; +import com.libnodave.Interface; import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.Flag; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.Value; +import org.openmuc.framework.data.*; import org.openmuc.framework.driver.spi.ChannelRecordContainer; import org.openmuc.framework.driver.spi.ChannelValueContainer; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import com.libnodave.Connection; -import com.libnodave.Interface; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; public class S7PlcConnection implements org.openmuc.framework.driver.spi.Connection { - private final Connection connection; - private final Interface ifc; - - public S7PlcConnection(Connection connection, Interface ifc) { - this.connection = connection; - this.ifc = ifc; - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - throw new UnsupportedOperationException(); - } - - private class DataBlock { - int nr; - int maxOffset = 0; - byte[] buf = null; - - public DataBlock(int nr) { - this.nr = nr; - } - } - - private class DataObject { - ChannelRecordContainer container; - S7ChannelAddress channelAddress; - - public DataObject(ChannelRecordContainer container, S7ChannelAddress channelAddress) { - this.container = container; - this.channelAddress = channelAddress; - } - } - - private byte[] concat(byte[] A, byte[] B) { - byte[] C = new byte[A.length + B.length]; - System.arraycopy(A, 0, C, 0, A.length); - System.arraycopy(B, 0, C, A.length, B.length); - - return C; - } - - private int getBit(byte b, byte bitPos) { - switch (bitPos) { - case 0: - if ((b & 0x01) != 0) { - return 1; - } - else { - return 0; - } - case 1: - if ((b & 0x02) != 0) { - return 1; - } - else { - return 0; - } - case 2: - if ((b & 0x04) != 0) { - return 1; - } - else { - return 0; - } - case 3: - if ((b & 0x08) != 0) { - return 1; - } - else { - return 0; - } - case 4: - if ((b & 0x10) != 0) { - return 1; - } - else { - return 0; - } - case 5: - if ((b & 0x20) != 0) { - return 1; - } - else { - return 0; - } - case 6: - if ((b & 0x40) != 0) { - return 1; - } - else { - return 0; - } - case 7: - if ((b & 0x80) != 0) { - return 1; - } - else { - return 0; - } - default: - return 0; - } - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - - HashMap dbList = new HashMap(); - List objList = new LinkedList(); - - for (ChannelRecordContainer container : containers) { - S7ChannelAddress channelAddress; - try { - channelAddress = new S7ChannelAddress(container.getChannelAddress()); - - } catch (MalformendObjectLocatorException e) { - container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); - continue; - } - - int dbAddr = channelAddress.getAreaAddress(); - DataBlock db; - - if (!dbList.containsKey(dbAddr)) { - dbList.put(dbAddr, new DataBlock(dbAddr)); - } - - db = dbList.get(dbAddr); - - int size = channelAddress.getOffset() + channelAddress.getDataLength(); - - if (size > db.maxOffset) { - db.maxOffset = size; - } - - objList.add(new DataObject(container, channelAddress)); - - } + private final Connection connection; + private final Interface ifc; + + public S7PlcConnection(Connection connection, Interface ifc) { + this.connection = connection; + this.ifc = ifc; + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + private class DataBlock { + int nr; + int maxOffset = 0; + byte[] buf = null; + + public DataBlock(int nr) { + this.nr = nr; + } + } + + private class DataObject { + ChannelRecordContainer container; + S7ChannelAddress channelAddress; + + public DataObject(ChannelRecordContainer container, S7ChannelAddress channelAddress) { + this.container = container; + this.channelAddress = channelAddress; + } + } + + private byte[] concat(byte[] A, byte[] B) { + byte[] C = new byte[A.length + B.length]; + System.arraycopy(A, 0, C, 0, A.length); + System.arraycopy(B, 0, C, A.length, B.length); + + return C; + } + + private int getBit(byte b, byte bitPos) { + switch (bitPos) { + case 0: + if ((b & 0x01) != 0) { + return 1; + } else { + return 0; + } + case 1: + if ((b & 0x02) != 0) { + return 1; + } else { + return 0; + } + case 2: + if ((b & 0x04) != 0) { + return 1; + } else { + return 0; + } + case 3: + if ((b & 0x08) != 0) { + return 1; + } else { + return 0; + } + case 4: + if ((b & 0x10) != 0) { + return 1; + } else { + return 0; + } + case 5: + if ((b & 0x20) != 0) { + return 1; + } else { + return 0; + } + case 6: + if ((b & 0x40) != 0) { + return 1; + } else { + return 0; + } + case 7: + if ((b & 0x80) != 0) { + return 1; + } else { + return 0; + } + default: + return 0; + } + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + + HashMap dbList = new HashMap(); + List objList = new LinkedList(); + + for (ChannelRecordContainer container : containers) { + S7ChannelAddress channelAddress; + try { + channelAddress = new S7ChannelAddress(container.getChannelAddress()); + + } catch (MalformendObjectLocatorException e) { + container.setRecord(new Record(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID)); + continue; + } + + int dbAddr = channelAddress.getAreaAddress(); + DataBlock db; + + if (!dbList.containsKey(dbAddr)) { + dbList.put(dbAddr, new DataBlock(dbAddr)); + } + + db = dbList.get(dbAddr); + + int size = channelAddress.getOffset() + channelAddress.getDataLength(); + + if (size > db.maxOffset) { + db.maxOffset = size; + } + + objList.add(new DataObject(container, channelAddress)); + + } /* Read out data blocks */ - for (DataBlock db : dbList.values()) { - - try { - - int maxOffset = db.maxOffset; - - int startOffset = 0; - - while (maxOffset > 460) { - if (db.buf == null) { - db.buf = connection.readBytes(Connection.AREA_DB, db.nr, startOffset, 460); - } - else { - db.buf = concat(db.buf, connection.readBytes(Connection.AREA_DB, db.nr, startOffset, 460)); - } - startOffset += 460; - maxOffset -= 460; - } - - if (db.buf == null) { - db.buf = connection.readBytes(Connection.AREA_DB, db.nr, startOffset, maxOffset); - } - else { - db.buf = concat(db.buf, connection.readBytes(Connection.AREA_DB, db.nr, startOffset, maxOffset)); - } - - } catch (IOException e) { - ifc.close(); - throw new ConnectionException("plcs7: readout error - close socket"); - } - } + for (DataBlock db : dbList.values()) { + + try { + + int maxOffset = db.maxOffset; + + int startOffset = 0; + + while (maxOffset > 460) { + if (db.buf == null) { + db.buf = connection.readBytes(Connection.AREA_DB, db.nr, startOffset, 460); + } else { + db.buf = concat(db.buf, connection.readBytes(Connection.AREA_DB, db.nr, startOffset, 460)); + } + startOffset += 460; + maxOffset -= 460; + } + + if (db.buf == null) { + db.buf = connection.readBytes(Connection.AREA_DB, db.nr, startOffset, maxOffset); + } else { + db.buf = concat(db.buf, connection.readBytes(Connection.AREA_DB, db.nr, startOffset, maxOffset)); + } + + } catch (IOException e) { + ifc.close(); + throw new ConnectionException("plcs7: readout error - close socket"); + } + } /* Get data out of buffers */ - for (DataObject obj : objList) { - DataBlock db = dbList.get(obj.channelAddress.getAreaAddress()); - - if (db.buf != null) { - Value val = null; - ByteBuffer bbuf; - bbuf = ByteBuffer.wrap(db.buf); - bbuf.order(ByteOrder.BIG_ENDIAN); - - switch (obj.channelAddress.getType()) { - case S7ChannelAddress.TYPE_FLOAT: - val = new DoubleValue(bbuf.getFloat(obj.channelAddress.getOffset())); - break; - case S7ChannelAddress.TYPE_UINT32: - val = new LongValue(((long) 0xffffffff & (long) bbuf.getInt(obj.channelAddress.getOffset()))); - break; - case S7ChannelAddress.TYPE_UINT16: - val = new IntValue((0xffff & bbuf.getShort(obj.channelAddress.getOffset()))); - break; - case S7ChannelAddress.TYPE_UINT8: - val = new ShortValue((short) (0xff & bbuf.get(obj.channelAddress.getOffset()))); - break; - case S7ChannelAddress.TYPE_BIT: - val = new ByteValue((byte) getBit(bbuf.get(obj.channelAddress.getOffset()), - obj.channelAddress.getBitPos())); - break; - } - - obj.container.setRecord(new Record(val, System.currentTimeMillis())); - - } - else { - obj.container.setRecord(new Record(Flag.UNKNOWN_ERROR)); - } - - } - return null; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - // TODO Auto-generated method stub - - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - - for (ChannelValueContainer container : containers) { - - try { - S7ChannelAddress locator; - try { - locator = new S7ChannelAddress(container.getChannelAddress()); - } catch (MalformendObjectLocatorException e) { - container.setFlag(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID); - continue; - } - - byte[] buf; - - switch (locator.getType()) { - - case S7ChannelAddress.TYPE_BIT: - int intVal = container.getValue().asInt(); - if (intVal == 0) { - connection.clrBit(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), - locator.getBitPos()); - } - else { - connection.setBit(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), - locator.getBitPos()); - } - break; - - case S7ChannelAddress.TYPE_FLOAT: - buf = new byte[4]; - ByteBuffer bbuf = ByteBuffer.wrap(buf); - bbuf.order(ByteOrder.BIG_ENDIAN); - bbuf.putFloat(0, container.getValue().asFloat()); - connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 4, - buf); - break; - - case S7ChannelAddress.TYPE_UINT8: - buf = new byte[1]; - buf[0] = (byte) ((container.getValue().asInt()) & 0xff); - connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 1, - buf); - break; - - case S7ChannelAddress.TYPE_UINT16: - buf = new byte[2]; - buf[0] = (byte) ((container.getValue().asInt()) / 0xff); - buf[1] = (byte) ((container.getValue().asInt()) & 0xff); - - System.out.printf("buf[0]:%02x buf[1]:%02x", buf[0], buf[1]); - connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 2, - buf); - break; - } - - } catch (IOException e) { - // TODO socket close - throw new ConnectionException(); - } - - container.setFlag(Flag.VALID); - - } - return null; - } - - @Override - public void disconnect() { - // TODO Auto-generated method stub - - } + for (DataObject obj : objList) { + DataBlock db = dbList.get(obj.channelAddress.getAreaAddress()); + + if (db.buf != null) { + Value val = null; + ByteBuffer bbuf; + bbuf = ByteBuffer.wrap(db.buf); + bbuf.order(ByteOrder.BIG_ENDIAN); + + switch (obj.channelAddress.getType()) { + case S7ChannelAddress.TYPE_FLOAT: + val = new DoubleValue(bbuf.getFloat(obj.channelAddress.getOffset())); + break; + case S7ChannelAddress.TYPE_UINT32: + val = new LongValue(((long) 0xffffffff & (long) bbuf.getInt(obj.channelAddress.getOffset()))); + break; + case S7ChannelAddress.TYPE_UINT16: + val = new IntValue((0xffff & bbuf.getShort(obj.channelAddress.getOffset()))); + break; + case S7ChannelAddress.TYPE_UINT8: + val = new ShortValue((short) (0xff & bbuf.get(obj.channelAddress.getOffset()))); + break; + case S7ChannelAddress.TYPE_BIT: + val = new ByteValue((byte) getBit(bbuf.get(obj.channelAddress.getOffset()), obj.channelAddress.getBitPos())); + break; + } + + obj.container.setRecord(new Record(val, System.currentTimeMillis())); + + } else { + obj.container.setRecord(new Record(Flag.UNKNOWN_ERROR)); + } + + } + return null; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException, ConnectionException { + // TODO Auto-generated method stub + + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + + for (ChannelValueContainer container : containers) { + + try { + S7ChannelAddress locator; + try { + locator = new S7ChannelAddress(container.getChannelAddress()); + } catch (MalformendObjectLocatorException e) { + container.setFlag(Flag.DRIVER_ERROR_CHANNEL_ADDRESS_SYNTAX_INVALID); + continue; + } + + byte[] buf; + + switch (locator.getType()) { + + case S7ChannelAddress.TYPE_BIT: + int intVal = container.getValue().asInt(); + if (intVal == 0) { + connection.clrBit(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), locator.getBitPos()); + } else { + connection.setBit(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), locator.getBitPos()); + } + break; + + case S7ChannelAddress.TYPE_FLOAT: + buf = new byte[4]; + ByteBuffer bbuf = ByteBuffer.wrap(buf); + bbuf.order(ByteOrder.BIG_ENDIAN); + bbuf.putFloat(0, container.getValue().asFloat()); + connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 4, buf); + break; + + case S7ChannelAddress.TYPE_UINT8: + buf = new byte[1]; + buf[0] = (byte) ((container.getValue().asInt()) & 0xff); + connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 1, buf); + break; + + case S7ChannelAddress.TYPE_UINT16: + buf = new byte[2]; + buf[0] = (byte) ((container.getValue().asInt()) / 0xff); + buf[1] = (byte) ((container.getValue().asInt()) & 0xff); + + System.out.printf("buf[0]:%02x buf[1]:%02x", buf[0], buf[1]); + connection.writeBytes(locator.getMemoryArea(), locator.getAreaAddress(), locator.getOffset(), 2, buf); + break; + } + + } catch (IOException e) { + // TODO socket close + throw new ConnectionException(); + } + + container.setFlag(Flag.VALID); + + } + return null; + } + + @Override + public void disconnect() { + // TODO Auto-generated method stub + + } } diff --git a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDevice.java b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDevice.java index c2024097..2c0e353e 100644 --- a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDevice.java +++ b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDevice.java @@ -22,30 +22,26 @@ public class S7PlcDevice { - private Integer port; + private Integer port; - public S7PlcDevice(String addr) { - setSlaveAddress(addr); - } + public S7PlcDevice(String addr) { + setSlaveAddress(addr); + } - /** - * - * @param deviceAddress - * e.g. localhost:1502 - */ - private void setSlaveAddress(String deviceAddress) { - String[] address = deviceAddress.toLowerCase().split(":"); + /** + * @param deviceAddress e.g. localhost:1502 + */ + private void setSlaveAddress(String deviceAddress) { + String[] address = deviceAddress.toLowerCase().split(":"); - port = 102; + port = 102; - if (address.length == 1) { - } - else if (address.length == 2) { - port = Integer.parseInt(address[1]); - } - else { - throw new RuntimeException("Invalid device address: '" + deviceAddress - + "'! Use following format: [ip:port] like localhost:1502 or 127.0.0.1:1502"); - } - } + if (address.length == 1) { + } else if (address.length == 2) { + port = Integer.parseInt(address[1]); + } else { + throw new RuntimeException( + "Invalid device address: '" + deviceAddress + "'! Use following format: [ip:port] like localhost:1502 or 127.0.0.1:1502"); + } + } } diff --git a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDriver.java b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDriver.java index e29f762b..2da61762 100644 --- a/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDriver.java +++ b/projects/driver/s7plc/src/main/java/org/openmuc/framework/driver/s7plc/S7PlcDriver.java @@ -21,8 +21,8 @@ package org.openmuc.framework.driver.s7plc; -import java.io.IOException; - +import com.libnodave.Connection; +import com.libnodave.Interface; import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.DriverInfo; import org.openmuc.framework.config.ScanException; @@ -33,83 +33,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.libnodave.Connection; -import com.libnodave.Interface; +import java.io.IOException; public final class S7PlcDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(S7PlcDriver.class); - - private final static DriverInfo info = new DriverInfo("s7plc", "Driver for WinAC / s7 PLC", "?", "?", "?", "?"); - - private final int c = 1; - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - - } - - @Override - public org.openmuc.framework.driver.spi.Connection connect(String deviceAddress, String settings) - throws ArgumentSyntaxException, ConnectionException { - - int index = deviceAddress.indexOf(":"); - if (index == -1) { - throw new ArgumentSyntaxException(); - } - - Interface ifc; - try { - ifc = new Interface("IF" + c, deviceAddress.substring(0, index), Integer.parseInt(deviceAddress - .substring(index + 1))); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException(); - } catch (IOException e) { - throw new ConnectionException(e); - } - - ifc.setTimeout(5000000); - - int mpi = 2; - int rack = 0; - int slot = 2; - - // if (url.getParameter("mpi") != null) { - // mpi = new Integer(url.getParameter("mpi")); - // System.out.println("mpi: " + mpi); - // } - // if (url.getParameter("rack") != null) { - // rack = new Integer(url.getParameter("rack")); - // System.out.println("rack: " + rack); - // } - // if (url.getParameter("slot") != null) { - // slot = new Integer(url.getParameter("slot")); - // System.out.println("slot: " + slot); - // } - - Connection con = new Connection(ifc, mpi, rack, slot); - - if (con.connectPLC() == true) { - logger.debug("plcs7: connection established to " + deviceAddress); - return new S7PlcConnection(con, ifc); - } - else { - throw new ConnectionException(); - } - - } + private final static Logger logger = LoggerFactory.getLogger(S7PlcDriver.class); + + private final static DriverInfo info = new DriverInfo("s7plc", "Driver for WinAC / s7 PLC", "?", "?", "?", "?"); + + private final int c = 1; + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + + } + + @Override + public org.openmuc.framework.driver.spi.Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, + ConnectionException { + + int index = deviceAddress.indexOf(":"); + if (index == -1) { + throw new ArgumentSyntaxException(); + } + + Interface ifc; + try { + ifc = new Interface("IF" + c, deviceAddress.substring(0, index), Integer.parseInt(deviceAddress.substring(index + 1))); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException(); + } catch (IOException e) { + throw new ConnectionException(e); + } + + ifc.setTimeout(5000000); + + int mpi = 2; + int rack = 0; + int slot = 2; + + // if (url.getParameter("mpi") != null) { + // mpi = new Integer(url.getParameter("mpi")); + // System.out.println("mpi: " + mpi); + // } + // if (url.getParameter("rack") != null) { + // rack = new Integer(url.getParameter("rack")); + // System.out.println("rack: " + rack); + // } + // if (url.getParameter("slot") != null) { + // slot = new Integer(url.getParameter("slot")); + // System.out.println("slot: " + slot); + // } + + Connection con = new Connection(ifc, mpi, rack, slot); + + if (con.connectPLC() == true) { + logger.debug("plcs7: connection established to " + deviceAddress); + return new S7PlcConnection(con, ifc); + } else { + throw new ConnectionException(); + } + + } } diff --git a/projects/driver/s7plc/src/main/resources/OSGI-INF/components.xml b/projects/driver/s7plc/src/main/resources/OSGI-INF/components.xml index 86c50c9b..44732e08 100644 --- a/projects/driver/s7plc/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/s7plc/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/snmp/build.gradle b/projects/driver/snmp/build.gradle index 6daf9287..299e4fe4 100644 --- a/projects/driver/snmp/build.gradle +++ b/projects/driver/snmp/build.gradle @@ -1,29 +1,28 @@ - configurations.create('embed') repositories { - mavenCentral() + mavenCentral() } dependencies { - compile project(':openmuc-core-spi') - compile files('dependencies/snmp4j-2.2.5.jar') - embed files('dependencies/snmp4j-2.2.5.jar') + compile project(':openmuc-core-spi') + compile files('dependencies/snmp4j-2.2.5.jar') + embed files('dependencies/snmp4j-2.2.5.jar') } jar { - manifest { - name = "OpenMUC Snmp Driver" - instruction 'Bundle-ClassPath', '.,lib/snmp4j-2.2.5.jar' - instruction 'Import-Package', '!org.snmp4j*,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Snmp Driver" + instruction 'Bundle-ClassPath', '.,lib/snmp4j-2.2.5.jar' + instruction 'Import-Package', '!org.snmp4j*,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } \ No newline at end of file diff --git a/projects/driver/snmp/example-config.xml b/projects/driver/snmp/example-config.xml index 78468715..dc6bf70c 100644 --- a/projects/driver/snmp/example-config.xml +++ b/projects/driver/snmp/example-config.xml @@ -1,25 +1,27 @@ - + 2s 5s false - [1.3.6.1.2.1.1.1.0 = Linux test-aitor 2.4.37 #7585 Sat Oct 10 02:08:51 CEST 2009 mips, 1.3.6.1.2.1.1.3.0 = 1:01:23.00, 1.3.6.1.2.1.1.6.0 = unknown, 1.3.6.1.2.1.1.2.0 = 1.3.6.1.4.1.8072.3.2.10, 1.3.6.1.2.1.1.4.0 = root, 1.3.6.1.2.1.1.5.0 = root] - 192.168.1.1/161 - V2c - USERNAME=root:SECURITYNAME=root:AUTHENTICATIONPASSPHRASE=adminadmin:PRIVACYPASSPHRASE=adminadmin - 2s - 5s - false - - idontcare - 1.3.6.1.2.1.25.2.3.1.5.101 - STRING - false - 100ms - 0 - 5s - 0 - + [1.3.6.1.2.1.1.1.0 = Linux test-aitor 2.4.37 #7585 Sat Oct 10 02:08:51 CEST 2009 mips, 1.3.6.1.2.1.1.3.0 = 1:01:23.00, + 1.3.6.1.2.1.1.6.0 = unknown, 1.3.6.1.2.1.1.2.0 = 1.3.6.1.4.1.8072.3.2.10, 1.3.6.1.2.1.1.4.0 = root, 1.3.6.1.2.1.1.5.0 = root] + + 192.168.1.1/161 + V2c + USERNAME=root:SECURITYNAME=root:AUTHENTICATIONPASSPHRASE=adminadmin:PRIVACYPASSPHRASE=adminadmin + 2s + 5s + false + + idontcare + 1.3.6.1.2.1.25.2.3.1.5.101 + STRING + false + 100ms + 0 + 5s + 0 + - + diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriver.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriver.java index f387a5cf..3d85fb32 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriver.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriver.java @@ -20,9 +20,6 @@ */ package org.openmuc.framework.driver.snmp; -import java.util.HashMap; -import java.util.Map; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.DriverInfo; import org.openmuc.framework.config.ScanException; @@ -38,171 +35,166 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; + /** - * * @author Mehran Shakeri - * */ public final class SnmpDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(SnmpDriver.class); - - private final static DriverInfo info = new DriverInfo("snmp", "snmp v1/v2c/v3 are supported.", "?", "?", "?", "?"); - - // AUTHENTICATIONPASSPHRASE is the same COMMUNITY word in SNMP V2c - public enum SnmpDriverSettingVariableNames { - SNMPVersion, USERNAME, SECURITYNAME, AUTHENTICATIONPASSPHRASE, PRIVACYPASSPHRASE - }; - - // AUTHENTICATIONPASSPHRASE is the same COMMUNITY word in SNMP V2c - public enum SnmpDriverScanSettingVariableNames { - SNMPVersion, USERNAME, SECURITYNAME, AUTHENTICATIONPASSPHRASE, PRIVACYPASSPHRASE, STARTIP, ENDIP - }; - - // exception messages - private final static String nullDeviceAddressException = "No device address found in config. Please specify one [eg. \"1.1.1.1/161\"]."; - private final static String nullSettingsException = "No device settings found in config. Please specify settings."; - private final static String incorrectSettingsFormatException = "Format of setting string is invalid! \n Please use this format: " - + "USERNAME=username:SECURITYNAME=securityname:AUTHENTICATIONPASSPHRASE=password:PRIVACYPASSPHRASE=privacy"; - private final static String incorrectSNMPVersionException = "Incorrect snmp version value. " - + "Please choose proper version. Possible values are defined in SNMPVersion enum"; - private final static String nullSNMPVersionException = "Snmp version is not defined. " - + "Please choose proper version. Possible values are defined in SNMPVersion enum"; - - @Override - public DriverInfo getInfo() { - return info; - } - - /** - * Currently only supports SNMP V2c - * - * Default port number 161 is used - * - * @param settings - * at least must contain
          - * - *
          - * SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE: (community word) in case of more than on - * value, they should be separated by ",". No community word is allowed to contain ","
          - * SnmpDriverScanSettingVariableNames.STARTIP: Start of IP range
          - * SnmpDriverScanSettingVariableNames.ENDIP: End of IP range
          - * eg. "AUTHENTICATIONPASSPHRASE=community,public:STARTIP=1.1.1.1:ENDIP=1.10.1.1" - * - */ - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) throws ArgumentSyntaxException, - ScanException, ScanInterruptedException { - - Map settingMapper = settingParser(settings); - - // Current implementation is only for SNMP version 2c - SnmpDeviceV1V2c snmpScanner; - try { - snmpScanner = new SnmpDeviceV1V2c(SNMPVersion.V2c); - } catch (ConnectionException e) { - throw new ScanException(e.getMessage()); - } - - SnmpDriverDiscoveryListener discoveryListener = new SnmpDriverDiscoveryListener(listener); - snmpScanner.addEventListener(discoveryListener); - String[] communityWords = settingMapper.get( - SnmpDriverScanSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString()).split(","); - snmpScanner.scanSnmpV2cEnabledDevices(settingMapper.get(SnmpDriverScanSettingVariableNames.STARTIP.toString()), - settingMapper.get(SnmpDriverScanSettingVariableNames.ENDIP.toString()), communityWords); - - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - /** - * - * @param settings - * SNMPVersion=V2c:COMMUNITY=value:SECURITYNAME=value:AUTHENTICATIONPASSPHRASE=value:PRIVACYPASSPHRASE= - * value - * - * @throws ConnectionException - * @throws ArgumentSyntaxException - */ - @Override - public Connection connect(String deviceAddress, String settings) throws ConnectionException, - ArgumentSyntaxException { - - SnmpDevice device = null; - SNMPVersion snmpVersion = null; - - // check arguments - if (deviceAddress == null || deviceAddress.equals("")) { - throw new ArgumentSyntaxException(nullDeviceAddressException); - } - else if (settings == null || settings.equals("")) { - throw new ArgumentSyntaxException(nullSettingsException); - } - else { - - Map mappedSettings = settingParser(settings); - - try { - snmpVersion = SNMPVersion.valueOf(mappedSettings.get(SnmpDriverSettingVariableNames.SNMPVersion - .toString())); - } catch (IllegalArgumentException e) { - throw new ArgumentSyntaxException(incorrectSNMPVersionException); - } catch (NullPointerException e) { - throw new ArgumentSyntaxException(nullSNMPVersionException); - } - - // create SnmpDevice object based on SNMP version - switch (snmpVersion) { - case V1: - case V2c: - device = new SnmpDeviceV1V2c(snmpVersion, deviceAddress, - mappedSettings.get(SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString())); - break; - case V3: - device = new SnmpDeviceV3(deviceAddress, mappedSettings.get(SnmpDriverSettingVariableNames.USERNAME - .toString()), mappedSettings.get(SnmpDriverSettingVariableNames.SECURITYNAME.toString()), - mappedSettings.get(SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString()), - mappedSettings.get(SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE.toString())); - break; - - default: - throw new ArgumentSyntaxException(incorrectSNMPVersionException); - } - - } - - return device; - } - - /** - * Read settings string and put them in a Key,Value HashMap Each setting consists of a pair of key/value and is - * separated by ":" from other settings Inside the setting string, key and value are separated by "=" e.g. - * "key1=value1:key2=value3" Be careful! "=" and ":" are not allowed in keys and values - * - * if your key contains more than one value, you can separate values by ",". in this case "," is not allowed in - * values. - * - * @param settings - * @return Map - * @throws ArgumentSyntaxException - */ - private Map settingParser(String settings) throws ArgumentSyntaxException { - - Map settingsMaper = new HashMap(); - - try { - String[] settingsArray = settings.split(":"); - for (String setting : settingsArray) { - String[] keyValue = setting.split("=", 2); - settingsMaper.put(keyValue[0], keyValue[1]); - } - } catch (ArrayIndexOutOfBoundsException e) { - throw new ArgumentSyntaxException(incorrectSettingsFormatException); - } - return settingsMaper; - } + private final static Logger logger = LoggerFactory.getLogger(SnmpDriver.class); + + private final static DriverInfo info = new DriverInfo("snmp", "snmp v1/v2c/v3 are supported.", "?", "?", "?", "?"); + + // AUTHENTICATIONPASSPHRASE is the same COMMUNITY word in SNMP V2c + public enum SnmpDriverSettingVariableNames { + SNMPVersion, USERNAME, SECURITYNAME, AUTHENTICATIONPASSPHRASE, PRIVACYPASSPHRASE + } + + ; + + // AUTHENTICATIONPASSPHRASE is the same COMMUNITY word in SNMP V2c + public enum SnmpDriverScanSettingVariableNames { + SNMPVersion, USERNAME, SECURITYNAME, AUTHENTICATIONPASSPHRASE, PRIVACYPASSPHRASE, STARTIP, ENDIP + } + + ; + + // exception messages + private final static String nullDeviceAddressException = "No device address found in config. Please specify one [eg. \"1.1.1.1/161\"]."; + private final static String nullSettingsException = "No device settings found in config. Please specify settings."; + private final static String incorrectSettingsFormatException = "Format of setting string is invalid! \n Please use this format: " + + "USERNAME=username:SECURITYNAME=securityname:AUTHENTICATIONPASSPHRASE=password:PRIVACYPASSPHRASE=privacy"; + private final static String incorrectSNMPVersionException = "Incorrect snmp version value. " + "Please choose proper version. " + + "Possible values are defined in SNMPVersion enum"; + private final static String nullSNMPVersionException = "Snmp version is not defined. " + "Please choose proper version. Possible " + + "values are defined in SNMPVersion enum"; + + @Override + public DriverInfo getInfo() { + return info; + } + + /** + * Currently only supports SNMP V2c + *

          + * Default port number 161 is used + * + * @param settings at least must contain
          + *

          + *
          + * SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE: (community word) in case of more than on + * value, they should be separated by ",". No community word is allowed to contain ","
          + * SnmpDriverScanSettingVariableNames.STARTIP: Start of IP range
          + * SnmpDriverScanSettingVariableNames.ENDIP: End of IP range
          + * eg. "AUTHENTICATIONPASSPHRASE=community,public:STARTIP=1.1.1.1:ENDIP=1.10.1.1" + */ + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws ArgumentSyntaxException, ScanException, + ScanInterruptedException { + + Map settingMapper = settingParser(settings); + + // Current implementation is only for SNMP version 2c + SnmpDeviceV1V2c snmpScanner; + try { + snmpScanner = new SnmpDeviceV1V2c(SNMPVersion.V2c); + } catch (ConnectionException e) { + throw new ScanException(e.getMessage()); + } + + SnmpDriverDiscoveryListener discoveryListener = new SnmpDriverDiscoveryListener(listener); + snmpScanner.addEventListener(discoveryListener); + String[] communityWords = settingMapper.get(SnmpDriverScanSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString()).split(","); + snmpScanner.scanSnmpV2cEnabledDevices(settingMapper.get(SnmpDriverScanSettingVariableNames.STARTIP.toString()), + settingMapper.get(SnmpDriverScanSettingVariableNames.ENDIP.toString()), communityWords); + + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * @param settings SNMPVersion=V2c:COMMUNITY=value:SECURITYNAME=value:AUTHENTICATIONPASSPHRASE=value:PRIVACYPASSPHRASE= + * value + * @throws ConnectionException + * @throws ArgumentSyntaxException + */ + @Override + public Connection connect(String deviceAddress, String settings) throws ConnectionException, ArgumentSyntaxException { + + SnmpDevice device = null; + SNMPVersion snmpVersion = null; + + // check arguments + if (deviceAddress == null || deviceAddress.equals("")) { + throw new ArgumentSyntaxException(nullDeviceAddressException); + } else if (settings == null || settings.equals("")) { + throw new ArgumentSyntaxException(nullSettingsException); + } else { + + Map mappedSettings = settingParser(settings); + + try { + snmpVersion = SNMPVersion.valueOf(mappedSettings.get(SnmpDriverSettingVariableNames.SNMPVersion.toString())); + } catch (IllegalArgumentException e) { + throw new ArgumentSyntaxException(incorrectSNMPVersionException); + } catch (NullPointerException e) { + throw new ArgumentSyntaxException(nullSNMPVersionException); + } + + // create SnmpDevice object based on SNMP version + switch (snmpVersion) { + case V1: + case V2c: + device = new SnmpDeviceV1V2c(snmpVersion, deviceAddress, + mappedSettings.get(SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString())); + break; + case V3: + device = new SnmpDeviceV3(deviceAddress, mappedSettings.get(SnmpDriverSettingVariableNames.USERNAME.toString()), + mappedSettings.get(SnmpDriverSettingVariableNames.SECURITYNAME.toString()), + mappedSettings.get(SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE.toString()), + mappedSettings.get(SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE.toString())); + break; + + default: + throw new ArgumentSyntaxException(incorrectSNMPVersionException); + } + + } + + return device; + } + + /** + * Read settings string and put them in a Key,Value HashMap Each setting consists of a pair of key/value and is + * separated by ":" from other settings Inside the setting string, key and value are separated by "=" e.g. + * "key1=value1:key2=value3" Be careful! "=" and ":" are not allowed in keys and values + *

          + * if your key contains more than one value, you can separate values by ",". in this case "," is not allowed in + * values. + * + * @param settings + * @return Map + * @throws ArgumentSyntaxException + */ + private Map settingParser(String settings) throws ArgumentSyntaxException { + + Map settingsMaper = new HashMap(); + + try { + String[] settingsArray = settings.split(":"); + for (String setting : settingsArray) { + String[] keyValue = setting.split("=", 2); + settingsMaper.put(keyValue[0], keyValue[1]); + } + } catch (ArrayIndexOutOfBoundsException e) { + throw new ArgumentSyntaxException(incorrectSettingsFormatException); + } + return settingsMaper; + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriverDiscoveryListener.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriverDiscoveryListener.java index 3f6d4906..6dcc20fd 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriverDiscoveryListener.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/SnmpDriverDiscoveryListener.java @@ -28,22 +28,21 @@ /** * In scanner we need to notify a listener which is given in arguments and also we have to create another listener in * order to listen to SNMP scanner in SnmpDevice. So we notify given listener in callback method of SnmpDevice listener - * + * * @author Mehran Shakeri - * */ public class SnmpDriverDiscoveryListener implements SnmpDiscoveryListener { - private final DriverDeviceScanListener scannerListener; + private final DriverDeviceScanListener scannerListener; - public SnmpDriverDiscoveryListener(DriverDeviceScanListener listener) { - scannerListener = listener; - } + public SnmpDriverDiscoveryListener(DriverDeviceScanListener listener) { + scannerListener = listener; + } - @Override - public void onNewDeviceFound(SnmpDiscoveryEvent e) { - DeviceScanInfo newDevice = new DeviceScanInfo(e.getDeviceAddress().toString(), null, e.getDescription()); - scannerListener.deviceFound(newDevice); - } + @Override + public void onNewDeviceFound(SnmpDiscoveryEvent e) { + DeviceScanInfo newDevice = new DeviceScanInfo(e.getDeviceAddress().toString(), null, e.getDescription()); + scannerListener.deviceFound(newDevice); + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDevice.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDevice.java index 275c2c83..aab6eb6e 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDevice.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDevice.java @@ -20,25 +20,12 @@ */ package org.openmuc.framework.driver.snmp.implementation; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; import org.openmuc.framework.data.ByteArrayValue; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; +import org.openmuc.framework.driver.spi.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.snmp4j.AbstractTarget; @@ -49,350 +36,335 @@ import org.snmp4j.security.SecurityModels; import org.snmp4j.security.SecurityProtocols; import org.snmp4j.security.USM; -import org.snmp4j.smi.Address; -import org.snmp4j.smi.GenericAddress; -import org.snmp4j.smi.OID; -import org.snmp4j.smi.OctetString; -import org.snmp4j.smi.VariableBinding; +import org.snmp4j.smi.*; import org.snmp4j.transport.DefaultUdpTransportMapping; +import java.io.IOException; +import java.util.*; + /** - * * Super class for defining SNMP enabled devices. - * + * * @author Mehran Shakeri - * */ public abstract class SnmpDevice implements Connection { - private final static Logger logger = LoggerFactory.getLogger(SnmpDevice.class); - - public enum SNMPVersion { - V1, V2c, V3 - }; - - protected Address targetAddress; - protected Snmp snmp; - protected USM usm; - protected int timeout = 3000; // in milliseconds - protected int retries = 3; - protected String authenticationPassphrase; - protected AbstractTarget target; - - protected List listeners = new ArrayList(); - - public static final Map ScanOIDs = new HashMap(); - static { - // some general OIDs that are valid in almost every MIB - ScanOIDs.put("Device name: ", "1.3.6.1.2.1.1.5.0"); - ScanOIDs.put("Description: ", "1.3.6.1.2.1.1.1.0"); - ScanOIDs.put("Location: ", "1.3.6.1.2.1.1.6.0"); - }; - - /** - * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol - * - * @param address - * Contains ip and port. accepted string "X.X.X.X/portNo" - * @param authenticationPassphrase - * the authentication pass phrase. If not null, authenticationProtocol must - * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 - * bytes. If the length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * - * @throws ConnectionException - * @throws ArgumentSyntaxException - */ - public SnmpDevice(String address, String authenticationPassphrase) throws ConnectionException, - ArgumentSyntaxException { - - // start snmp compatible with all versions - try { - snmp = new Snmp(new DefaultUdpTransportMapping()); - } catch (IOException e) { - throw new ConnectionException("SNMP initialization failed! \n" + e.getMessage()); - } - usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); - SecurityModels.getInstance().addSecurityModel(usm); - try { - snmp.listen(); - } catch (IOException e) { - throw new ConnectionException("SNMP listen failed! \n" + e.getMessage()); - } - - // set address - try { - targetAddress = GenericAddress.parse(address); - } catch (IllegalArgumentException e) { - throw new ArgumentSyntaxException("Device address foramt is wrong! (eg. 1.1.1.1/1)"); - } - - this.authenticationPassphrase = authenticationPassphrase; - - } - - /** - * Default constructor useful for scanner - */ - public SnmpDevice() { - } - - /** - * set target parameters. Implementations are different in SNMP v1, v2c and v3 - */ - abstract void setTarget(); - - /** - * Receives a list of all OIDs in string format, creates PDU and sends GET request to defined target. This method is - * a blocking method. It waits for response. - * - * @param OIDs - * list of OIDs that should be read from target - * @return Map<String, String> returns a Map of OID as Key and received value corresponding to that OID from - * the target as Value - * - * @throws SnmpTimeoutException - * @throws ConnectionException - */ - public Map getRequestsList(List OIDs) throws SnmpTimeoutException, ConnectionException { - - Map result = new HashMap(); - - // set PDU - PDU pdu = new PDU(); - pdu.setType(PDU.GET); - - for (String oid : OIDs) { - pdu.add(new VariableBinding(new OID(oid))); - } - - // send GET request - ResponseEvent response; - try { - response = snmp.send(pdu, target); - PDU responsePDU = response.getResponse(); - @SuppressWarnings("rawtypes") - Vector vbs = responsePDU.getVariableBindings(); - for (int i = 0; i < vbs.size(); i++) { - VariableBinding vb = (VariableBinding) vbs.get(i); - result.put(vb.getOid().toString(), vb.getVariable().toString()); - } - } catch (IOException e) { - throw new ConnectionException("SNMP get request failed! " + e.getMessage()); - } catch (NullPointerException e) { - throw new SnmpTimeoutException("Timeout: Target doesn't respond!"); - } - - return result; - } - - /** - * Receives one single OID in string format, creates PDU and sends GET request to defined target. This method is a - * blocking method. It waits for response. - * - * @param OID - * OID that should be read from target - * @return String containing read value - * - * @throws SnmpTimeoutException - * @throws ConnectionException - */ - public String getSingleRequests(String OID) throws SnmpTimeoutException, ConnectionException { - - String result = null; - - // set PDU - PDU pdu = new PDU(); - pdu.setType(PDU.GET); - - pdu.add(new VariableBinding(new OID(OID))); - - // send GET request - ResponseEvent response; - try { - response = snmp.send(pdu, target); - PDU responsePDU = response.getResponse(); - @SuppressWarnings("rawtypes") - Vector vbs = responsePDU.getVariableBindings(); - result = ((VariableBinding) vbs.get(0)).getVariable().toString(); - } catch (IOException e) { - throw new ConnectionException("SNMP get request failed! " + e.getMessage()); - } catch (NullPointerException e) { - throw new SnmpTimeoutException("Timeout: Target doesn't respond!"); - } - - return result; - } - - public String getDeviceAddress() { - return targetAddress.toString(); - } - - public synchronized void addEventListener(SnmpDiscoveryListener listener) { - listeners.add(listener); - } - - public synchronized void removeEventListener(SnmpDiscoveryListener listener) { - listeners.remove(listener); - } - - /** - * This method will call all listeners for given new device - * - * @param address - * address of device - * @param version - * version of snmp that this device support - * @param description - * other extra information which can be useful - * - */ - protected synchronized void NotifyForNewDevice(Address address, SNMPVersion version, String description) { - SnmpDiscoveryEvent event = new SnmpDiscoveryEvent(this, address, version, description); - @SuppressWarnings("rawtypes") - Iterator i = listeners.iterator(); - while (i.hasNext()) { - ((SnmpDiscoveryListener) i.next()).onNewDeviceFound(event); - } - } - - /** - * Calculate and return next broadcast address. (eg. if ip=1.2.3.x, returns 1.2.4.255) - * - * @param ip - * @return String - */ - public static String getNextBroadcastIPV4Address(String ip) { - String[] nums = ip.split("\\."); - int i = (Integer.parseInt(nums[0]) << 24 | Integer.parseInt(nums[2]) << 8 | Integer.parseInt(nums[1]) << 16 | Integer - .parseInt(nums[3])) + 256; - - return String.format("%d.%d.%d.%d", i >>> 24 & 0xFF, i >> 16 & 0xFF, i >> 8 & 0xFF, 255); - } - - /** - * Helper function in order to parse response vector to map structure - * - * @param responseVector - * @return HashMap<String, String> - */ - public static HashMap parseResponseVectorToHashMap(Vector responseVector) { - - HashMap map = new HashMap(); - for (VariableBinding elem : responseVector) { - map.put(elem.getOid().toString(), elem.getVariable().toString()); - } - return map; - } - - protected static String scannerMakeDescriptionString(HashMap scannerResult) { - - StringBuilder desc = new StringBuilder(); - for (String key : ScanOIDs.keySet()) { - desc.append('[').append(key).append('(').append(ScanOIDs.get(key)).append(")=") - .append(scannerResult.get(ScanOIDs.get(key))).append("] "); - } - return desc.toString(); - } - - /** - * Returns respective SNMPVersion enum value based on given SnmpConstant version value - * - * @param version - * @return SNMPVersion or null if given value is not valid - */ - protected static SNMPVersion getSnmpVersionFromSnmpConstantsValue(int version) { - switch (version) { - case 0: - return SNMPVersion.V1; - case 1: - return SNMPVersion.V2c; - case 3: - return SNMPVersion.V3; - } - return null; - } - - @Override - public void disconnect() { - } - - /** - * At least device address and channel address must be specified in the container.
          - *
          - * containers.deviceAddress = device address (eg. 1.1.1.1/161)
          - * containers.channelAddress = OID (eg. 1.3.6.1.2.1.1.0) - * - */ - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws ConnectionException { - - return readChannelGroup(containers, timeout); - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - // TODO snmp set request will be implemented here - throw new UnsupportedOperationException(); - } - - /** - * Read all the channels of the device at once. - * - * @param device - * @param containers - * @param timeout - * @return Object - * @throws ConnectionException - */ - private Object readChannelGroup(List containers, int timeout) throws ConnectionException { - - new Date().getTime(); - - List oids = new ArrayList(); - - for (ChannelRecordContainer container : containers) { - if (getDeviceAddress().equalsIgnoreCase(container.getChannel().getDeviceAddress())) { - oids.add(container.getChannelAddress()); - } - } - - Map values; - - try { - values = getRequestsList(oids); - long receiveTime = System.currentTimeMillis(); - - for (ChannelRecordContainer container : containers) { - // make sure the value exists for corresponding channel - if (values.get(container.getChannelAddress()) != null) { - logger.debug("{}: value = '{}'", container.getChannelAddress(), - values.get(container.getChannelAddress())); - container.setRecord(new Record(new ByteArrayValue(values.get(container.getChannelAddress()) - .getBytes()), receiveTime)); - } - } - } catch (SnmpTimeoutException e) { - for (ChannelRecordContainer container : containers) { - container.setRecord(new Record(Flag.TIMEOUT)); - } - } - - return null; - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - throw new UnsupportedOperationException(); - } + private final static Logger logger = LoggerFactory.getLogger(SnmpDevice.class); + + public enum SNMPVersion { + V1, V2c, V3 + } + + ; + + protected Address targetAddress; + protected Snmp snmp; + protected USM usm; + protected int timeout = 3000; // in milliseconds + protected int retries = 3; + protected String authenticationPassphrase; + protected AbstractTarget target; + + protected List listeners = new ArrayList(); + + public static final Map ScanOIDs = new HashMap(); + + static { + // some general OIDs that are valid in almost every MIB + ScanOIDs.put("Device name: ", "1.3.6.1.2.1.1.5.0"); + ScanOIDs.put("Description: ", "1.3.6.1.2.1.1.1.0"); + ScanOIDs.put("Location: ", "1.3.6.1.2.1.1.6.0"); + } + + ; + + /** + * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol + * + * @param address Contains ip and port. accepted string "X.X.X.X/portNo" + * @param authenticationPassphrase the authentication pass phrase. If not null, authenticationProtocol must + * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 + * bytes. If the length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @throws ConnectionException + * @throws ArgumentSyntaxException + */ + public SnmpDevice(String address, String authenticationPassphrase) throws ConnectionException, ArgumentSyntaxException { + + // start snmp compatible with all versions + try { + snmp = new Snmp(new DefaultUdpTransportMapping()); + } catch (IOException e) { + throw new ConnectionException("SNMP initialization failed! \n" + e.getMessage()); + } + usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); + SecurityModels.getInstance().addSecurityModel(usm); + try { + snmp.listen(); + } catch (IOException e) { + throw new ConnectionException("SNMP listen failed! \n" + e.getMessage()); + } + + // set address + try { + targetAddress = GenericAddress.parse(address); + } catch (IllegalArgumentException e) { + throw new ArgumentSyntaxException("Device address foramt is wrong! (eg. 1.1.1.1/1)"); + } + + this.authenticationPassphrase = authenticationPassphrase; + + } + + /** + * Default constructor useful for scanner + */ + public SnmpDevice() { + } + + /** + * set target parameters. Implementations are different in SNMP v1, v2c and v3 + */ + abstract void setTarget(); + + /** + * Receives a list of all OIDs in string format, creates PDU and sends GET request to defined target. This method is + * a blocking method. It waits for response. + * + * @param OIDs list of OIDs that should be read from target + * @return Map<String, String> returns a Map of OID as Key and received value corresponding to that OID from + * the target as Value + * @throws SnmpTimeoutException + * @throws ConnectionException + */ + public Map getRequestsList(List OIDs) throws SnmpTimeoutException, ConnectionException { + + Map result = new HashMap(); + + // set PDU + PDU pdu = new PDU(); + pdu.setType(PDU.GET); + + for (String oid : OIDs) { + pdu.add(new VariableBinding(new OID(oid))); + } + + // send GET request + ResponseEvent response; + try { + response = snmp.send(pdu, target); + PDU responsePDU = response.getResponse(); + @SuppressWarnings("rawtypes") + Vector vbs = responsePDU.getVariableBindings(); + for (int i = 0; i < vbs.size(); i++) { + VariableBinding vb = (VariableBinding) vbs.get(i); + result.put(vb.getOid().toString(), vb.getVariable().toString()); + } + } catch (IOException e) { + throw new ConnectionException("SNMP get request failed! " + e.getMessage()); + } catch (NullPointerException e) { + throw new SnmpTimeoutException("Timeout: Target doesn't respond!"); + } + + return result; + } + + /** + * Receives one single OID in string format, creates PDU and sends GET request to defined target. This method is a + * blocking method. It waits for response. + * + * @param OID OID that should be read from target + * @return String containing read value + * @throws SnmpTimeoutException + * @throws ConnectionException + */ + public String getSingleRequests(String OID) throws SnmpTimeoutException, ConnectionException { + + String result = null; + + // set PDU + PDU pdu = new PDU(); + pdu.setType(PDU.GET); + + pdu.add(new VariableBinding(new OID(OID))); + + // send GET request + ResponseEvent response; + try { + response = snmp.send(pdu, target); + PDU responsePDU = response.getResponse(); + @SuppressWarnings("rawtypes") + Vector vbs = responsePDU.getVariableBindings(); + result = ((VariableBinding) vbs.get(0)).getVariable().toString(); + } catch (IOException e) { + throw new ConnectionException("SNMP get request failed! " + e.getMessage()); + } catch (NullPointerException e) { + throw new SnmpTimeoutException("Timeout: Target doesn't respond!"); + } + + return result; + } + + public String getDeviceAddress() { + return targetAddress.toString(); + } + + public synchronized void addEventListener(SnmpDiscoveryListener listener) { + listeners.add(listener); + } + + public synchronized void removeEventListener(SnmpDiscoveryListener listener) { + listeners.remove(listener); + } + + /** + * This method will call all listeners for given new device + * + * @param address address of device + * @param version version of snmp that this device support + * @param description other extra information which can be useful + */ + protected synchronized void NotifyForNewDevice(Address address, SNMPVersion version, String description) { + SnmpDiscoveryEvent event = new SnmpDiscoveryEvent(this, address, version, description); + @SuppressWarnings("rawtypes") + Iterator i = listeners.iterator(); + while (i.hasNext()) { + ((SnmpDiscoveryListener) i.next()).onNewDeviceFound(event); + } + } + + /** + * Calculate and return next broadcast address. (eg. if ip=1.2.3.x, returns 1.2.4.255) + * + * @param ip + * @return String + */ + public static String getNextBroadcastIPV4Address(String ip) { + String[] nums = ip.split("\\."); + int i = (Integer.parseInt(nums[0]) << 24 | Integer.parseInt(nums[2]) << 8 | Integer.parseInt(nums[1]) << 16 | Integer + .parseInt(nums[3])) + 256; + + return String.format("%d.%d.%d.%d", i >>> 24 & 0xFF, i >> 16 & 0xFF, i >> 8 & 0xFF, 255); + } + + /** + * Helper function in order to parse response vector to map structure + * + * @param responseVector + * @return HashMap<String, String> + */ + public static HashMap parseResponseVectorToHashMap(Vector responseVector) { + + HashMap map = new HashMap(); + for (VariableBinding elem : responseVector) { + map.put(elem.getOid().toString(), elem.getVariable().toString()); + } + return map; + } + + protected static String scannerMakeDescriptionString(HashMap scannerResult) { + + StringBuilder desc = new StringBuilder(); + for (String key : ScanOIDs.keySet()) { + desc.append('[').append(key).append('(').append(ScanOIDs.get(key)).append(")=").append(scannerResult.get(ScanOIDs.get(key))) + .append("] "); + } + return desc.toString(); + } + + /** + * Returns respective SNMPVersion enum value based on given SnmpConstant version value + * + * @param version + * @return SNMPVersion or null if given value is not valid + */ + protected static SNMPVersion getSnmpVersionFromSnmpConstantsValue(int version) { + switch (version) { + case 0: + return SNMPVersion.V1; + case 1: + return SNMPVersion.V2c; + case 3: + return SNMPVersion.V3; + } + return null; + } + + @Override + public void disconnect() { + } + + /** + * At least device address and channel address must be specified in the container.
          + *
          + * containers.deviceAddress = device address (eg. 1.1.1.1/161)
          + * containers.channelAddress = OID (eg. 1.3.6.1.2.1.1.0) + */ + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + ConnectionException { + + return readChannelGroup(containers, timeout); + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, + ConnectionException { + // TODO snmp set request will be implemented here + throw new UnsupportedOperationException(); + } + + /** + * Read all the channels of the device at once. + * + * @param device + * @param containers + * @param timeout + * @return Object + * @throws ConnectionException + */ + private Object readChannelGroup(List containers, int timeout) throws ConnectionException { + + new Date().getTime(); + + List oids = new ArrayList(); + + for (ChannelRecordContainer container : containers) { + if (getDeviceAddress().equalsIgnoreCase(container.getChannel().getDeviceAddress())) { + oids.add(container.getChannelAddress()); + } + } + + Map values; + + try { + values = getRequestsList(oids); + long receiveTime = System.currentTimeMillis(); + + for (ChannelRecordContainer container : containers) { + // make sure the value exists for corresponding channel + if (values.get(container.getChannelAddress()) != null) { + logger.debug("{}: value = '{}'", container.getChannelAddress(), values.get(container.getChannelAddress())); + container.setRecord(new Record(new ByteArrayValue(values.get(container.getChannelAddress()).getBytes()), receiveTime)); + } + } + } catch (SnmpTimeoutException e) { + for (ChannelRecordContainer container : containers) { + container.setRecord(new Record(Flag.TIMEOUT)); + } + } + + return null; + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV1V2c.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV1V2c.java index da241992..7bd61a9e 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV1V2c.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV1V2c.java @@ -20,9 +20,6 @@ */ package org.openmuc.framework.driver.snmp.implementation; -import java.io.IOException; -import java.util.Vector; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.driver.snmp.SnmpDriver.SnmpDriverSettingVariableNames; import org.openmuc.framework.driver.spi.ConnectionException; @@ -42,210 +39,205 @@ import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; +import java.io.IOException; +import java.util.Vector; + /** - * * @author Mehran Shakeri - * */ public class SnmpDeviceV1V2c extends SnmpDevice { - private int snmpVersion; - - /** - * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol - * - * @param version - * Can be V1 or V2c corresponding to snmp v1 or v2c - * @param address - * Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" - * @param authenticationPassphrase - * the authentication pass phrase. If not null, authenticationProtocol must - * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 - * bytes. If the length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * - * @throws ConnectionException - * @throws ArgumentSyntaxException - */ - - public SnmpDeviceV1V2c(SNMPVersion version, String address, String authenticationPassphrase) - throws ConnectionException, ArgumentSyntaxException { - super(address, authenticationPassphrase); - setVersion(version); - setTarget(); - - } - - /** - * scanner constructor - * - * @param version - * @throws ArgumentSyntaxException - * @throws ConnectionException - */ - public SnmpDeviceV1V2c(SNMPVersion version) throws ArgumentSyntaxException, ConnectionException { - setVersion(version); - try { - snmp = new Snmp(new DefaultUdpTransportMapping()); - } catch (IOException e) { - throw new ConnectionException("SNMP initialization failed! \n" + e.getMessage()); - } - usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); - SecurityModels.getInstance().addSecurityModel(usm); - try { - snmp.listen(); - } catch (IOException e) { - throw new ConnectionException("SNMP listen failed! \n" + e.getMessage()); - } - - } - - /** - * set SNMP version - * - * @param version - * @throws ArgumentSyntaxException - */ - private void setVersion(SNMPVersion version) throws ArgumentSyntaxException { - switch (version) { - case V1: - snmpVersion = SnmpConstants.version1; - break; - case V2c: - snmpVersion = SnmpConstants.version2c; - break; - - default: - throw new ArgumentSyntaxException( - "Given snmp version is not correct or supported! Expected values are [V1,V2c]."); - } - } - - @Override - void setTarget() { - target = new CommunityTarget(); - ((CommunityTarget) target).setCommunity(new OctetString(authenticationPassphrase)); - target.setAddress(targetAddress); - target.setRetries(retries); - target.setTimeout(timeout); - target.setVersion(snmpVersion); - } - - public String getInterfaceAddress() { - return null; - } - - @Override - public String getDeviceAddress() { - return targetAddress.toString(); - } - - public String getSettings() { - String settings = SnmpDriverSettingVariableNames.SNMPVersion.toString() + "=" - + getSnmpVersionFromSnmpConstantsValue(snmpVersion) + ":COMMUNITY=" + authenticationPassphrase; - - return settings; - } - - public Object getConnectionHandle() { - return this; - } - - /** - * Search for SNMP V2c enabled devices in network by sending proper SNMP GET request to given range of IP addresses. - * - * For network and process efficiency, requests are sent to broadcast addresses (IP addresses ending with .255). - * - * startIPRange can be greater than endIPRange. In this case, it will reach the last available address and start - * from the first IP address again - * - * @param startIPRange - * @param endIPRange - * @param communityWords - * @throws ArgumentSyntaxException - */ - public void scanSnmpV2cEnabledDevices(String startIPRange, String endIPRange, String[] communityWords) - throws ArgumentSyntaxException { - - // create PDU - PDU pdu = new PDU(); - - for (String oid : ScanOIDs.values()) { - pdu.add(new VariableBinding(new OID(oid))); - } - pdu.setType(PDU.GET); - - // make sure the start/end IP is broadcast (eg. X.Y.Z.255) - try { - String[] ip = startIPRange.split("\\."); - startIPRange = ip[0] + "." + ip[1] + "." + ip[2] + ".255"; - ip = endIPRange.split("\\."); - endIPRange = ip[0] + "." + ip[1] + "." + ip[2] + ".255"; - } catch (ArrayIndexOutOfBoundsException e) { - throw new ArgumentSyntaxException("Given start ip address is not a valid IPV4 address."); - } - String nextIp = startIPRange; - // in order to check also the EndIPRange - endIPRange = getNextBroadcastIPV4Address(endIPRange); - try { - - // loop through all IP addresses - while (endIPRange.compareTo(nextIp) != 0) { - // TODO scan progress can be implemented here - - // define broadcast address - try { - targetAddress = GenericAddress.parse("udp:" + nextIp + "/161"); - } catch (IllegalArgumentException e) { - throw new ArgumentSyntaxException("Device address format is wrong! (eg. 1.1.1.255)"); - } - - // loop through all community words - for (String community : communityWords) { - - // set target V2c - authenticationPassphrase = community; - setTarget(); - - class ScanResponseListener implements ResponseListener { - - @Override - @SuppressWarnings("unchecked") - public void onResponse(ResponseEvent event) { - /** - * Since we are sending broadcast request we have to keep async request alive. Otherwise - * async request must be cancel by blew code in order to prevent memory leak - * - * ((Snmp)event.getSource()).cancel(event.getRequest (), this); - * - */ - - if (event.getResponse() != null) { - @SuppressWarnings("rawtypes") - Vector vbs = event.getResponse().getVariableBindings(); - // check if sent and received OIDs are the same - // or else snmp version may not compatible - if (!ScanOIDs.containsValue(((VariableBinding) vbs.get(0)).getOid().toString())) { - // wrong version or not correct response! - return; - } - NotifyForNewDevice(event.getPeerAddress(), SNMPVersion.V2c, - scannerMakeDescriptionString(parseResponseVectorToHashMap(vbs))); - } - } - } - ; - - ScanResponseListener listener = new ScanResponseListener(); - snmp.send(pdu, target, null, listener); - } // end of community loop - - nextIp = getNextBroadcastIPV4Address(nextIp); - } // end of IP loop - - } catch (IOException e1) { - e1.printStackTrace(); - } - - } + private int snmpVersion; + + /** + * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol + * + * @param version Can be V1 or V2c corresponding to snmp v1 or v2c + * @param address Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" + * @param authenticationPassphrase the authentication pass phrase. If not null, authenticationProtocol must + * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 + * bytes. If the length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @throws ConnectionException + * @throws ArgumentSyntaxException + */ + + public SnmpDeviceV1V2c(SNMPVersion version, String address, String authenticationPassphrase) throws ConnectionException, + ArgumentSyntaxException { + super(address, authenticationPassphrase); + setVersion(version); + setTarget(); + + } + + /** + * scanner constructor + * + * @param version + * @throws ArgumentSyntaxException + * @throws ConnectionException + */ + public SnmpDeviceV1V2c(SNMPVersion version) throws ArgumentSyntaxException, ConnectionException { + setVersion(version); + try { + snmp = new Snmp(new DefaultUdpTransportMapping()); + } catch (IOException e) { + throw new ConnectionException("SNMP initialization failed! \n" + e.getMessage()); + } + usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); + SecurityModels.getInstance().addSecurityModel(usm); + try { + snmp.listen(); + } catch (IOException e) { + throw new ConnectionException("SNMP listen failed! \n" + e.getMessage()); + } + + } + + /** + * set SNMP version + * + * @param version + * @throws ArgumentSyntaxException + */ + private void setVersion(SNMPVersion version) throws ArgumentSyntaxException { + switch (version) { + case V1: + snmpVersion = SnmpConstants.version1; + break; + case V2c: + snmpVersion = SnmpConstants.version2c; + break; + + default: + throw new ArgumentSyntaxException("Given snmp version is not correct or supported! Expected values are [V1,V2c]."); + } + } + + @Override + void setTarget() { + target = new CommunityTarget(); + ((CommunityTarget) target).setCommunity(new OctetString(authenticationPassphrase)); + target.setAddress(targetAddress); + target.setRetries(retries); + target.setTimeout(timeout); + target.setVersion(snmpVersion); + } + + public String getInterfaceAddress() { + return null; + } + + @Override + public String getDeviceAddress() { + return targetAddress.toString(); + } + + public String getSettings() { + String settings = SnmpDriverSettingVariableNames.SNMPVersion.toString() + "=" + getSnmpVersionFromSnmpConstantsValue( + snmpVersion) + ":COMMUNITY=" + authenticationPassphrase; + + return settings; + } + + public Object getConnectionHandle() { + return this; + } + + /** + * Search for SNMP V2c enabled devices in network by sending proper SNMP GET request to given range of IP addresses. + *

          + * For network and process efficiency, requests are sent to broadcast addresses (IP addresses ending with .255). + *

          + * startIPRange can be greater than endIPRange. In this case, it will reach the last available address and start + * from the first IP address again + * + * @param startIPRange + * @param endIPRange + * @param communityWords + * @throws ArgumentSyntaxException + */ + public void scanSnmpV2cEnabledDevices(String startIPRange, String endIPRange, String[] communityWords) throws ArgumentSyntaxException { + + // create PDU + PDU pdu = new PDU(); + + for (String oid : ScanOIDs.values()) { + pdu.add(new VariableBinding(new OID(oid))); + } + pdu.setType(PDU.GET); + + // make sure the start/end IP is broadcast (eg. X.Y.Z.255) + try { + String[] ip = startIPRange.split("\\."); + startIPRange = ip[0] + "." + ip[1] + "." + ip[2] + ".255"; + ip = endIPRange.split("\\."); + endIPRange = ip[0] + "." + ip[1] + "." + ip[2] + ".255"; + } catch (ArrayIndexOutOfBoundsException e) { + throw new ArgumentSyntaxException("Given start ip address is not a valid IPV4 address."); + } + String nextIp = startIPRange; + // in order to check also the EndIPRange + endIPRange = getNextBroadcastIPV4Address(endIPRange); + try { + + // loop through all IP addresses + while (endIPRange.compareTo(nextIp) != 0) { + // TODO scan progress can be implemented here + + // define broadcast address + try { + targetAddress = GenericAddress.parse("udp:" + nextIp + "/161"); + } catch (IllegalArgumentException e) { + throw new ArgumentSyntaxException("Device address format is wrong! (eg. 1.1.1.255)"); + } + + // loop through all community words + for (String community : communityWords) { + + // set target V2c + authenticationPassphrase = community; + setTarget(); + + class ScanResponseListener implements ResponseListener { + + @Override + @SuppressWarnings("unchecked") + public void onResponse(ResponseEvent event) { + /** + * Since we are sending broadcast request we have to keep async request alive. Otherwise + * async request must be cancel by blew code in order to prevent memory leak + * + * ((Snmp)event.getSource()).cancel(event.getRequest (), this); + * + */ + + if (event.getResponse() != null) { + @SuppressWarnings("rawtypes") + Vector vbs = event.getResponse().getVariableBindings(); + // check if sent and received OIDs are the same + // or else snmp version may not compatible + if (!ScanOIDs.containsValue(((VariableBinding) vbs.get(0)).getOid().toString())) { + // wrong version or not correct response! + return; + } + NotifyForNewDevice(event.getPeerAddress(), SNMPVersion.V2c, + scannerMakeDescriptionString(parseResponseVectorToHashMap(vbs))); + } + } + } + ; + + ScanResponseListener listener = new ScanResponseListener(); + snmp.send(pdu, target, null, listener); + } // end of community loop + + nextIp = getNextBroadcastIPV4Address(nextIp); + } // end of IP loop + + } catch (IOException e1) { + e1.printStackTrace(); + } + + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV3.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV3.java index 0f0693aa..4e33fdb9 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV3.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDeviceV3.java @@ -33,155 +33,133 @@ import org.snmp4j.smi.OctetString; /** - * * @author Mehran Shakeri - * */ public class SnmpDeviceV3 extends SnmpDevice { - // private UserTarget target; // snmp v3 target - private final String username; - private final String securityName; - private final OID authenticationProtocol; - private final String authenticationPassphrase; - private final OID privacyProtocol; - private final String privacyPassphrase; - - /** - * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol - * - * @param address - * Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" - * @param username - * String containing username - * @param securityName - * the security name of the user (typically the user name). [required by snmp4j library] - * @param authenticationProtocol - * the authentication protocol ID to be associated with this user. If set to null, this user - * only supports unauthenticated messages. [required by snmp4j library] eg. AuthMD5.ID - * @param authenticationPassphrase - * the authentication pass phrase. If not null, authenticationProtocol must - * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 - * bytes. If the length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * @param privacyProtocol - * the privacy protocol ID to be associated with this user. If set to null, this user only - * supports not encrypted messages. [required by snmp4j library] eg. PrivDES.ID - * @param privacyPassphrase - * the privacy pass phrase. If not null, privacyProtocol must also be not - * null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 bytes. If the - * length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * - * @throws ConnectionException - * @throws ArgumentSyntaxException - */ - - public SnmpDeviceV3(String address, String username, String securityName, OID authenticationProtocol, - String authenticationPassphrase, OID privacyProtocol, String privacyPassphrase) throws ConnectionException, - ArgumentSyntaxException { - super(address, authenticationPassphrase); - - this.username = username; - this.securityName = securityName; - this.authenticationProtocol = authenticationProtocol; - this.authenticationPassphrase = authenticationPassphrase; - this.privacyProtocol = privacyProtocol; - this.privacyPassphrase = privacyPassphrase; - } - - /** - * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol - * Default values: authenticationProtocol = AuthMD5.ID; privacyProtocol = PrivDES.ID; - * - * @param address - * Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" - * @param username - * String containing username - * @param securityName - * the security name of the user (typically the user name). [required by snmp4j library] - * @param authenticationPassphrase - * the authentication pass phrase. If not null, authenticationProtocol must - * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 - * bytes. If the length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * @param privacyPassphrase - * the privacy pass phrase. If not null, privacyProtocol must also be not - * null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 bytes. If the - * length of authenticationPassphrase is less than 8 bytes an - * IllegalArgumentException is thrown. [required by snmp4j library] - * - * @throws ConnectionException - * @throws ArgumentSyntaxException - */ - - public SnmpDeviceV3(String address, String username, String securityName, String authenticationPassphrase, - String privacyPassphrase) throws ConnectionException, ArgumentSyntaxException { - super(address, authenticationPassphrase); - - this.username = username; - this.securityName = securityName; - authenticationProtocol = AuthMD5.ID; - this.authenticationPassphrase = authenticationPassphrase; - privacyProtocol = PrivDES.ID; - this.privacyPassphrase = privacyPassphrase; - } - - @Override - void setTarget() { - int securityLevel = -1; - if (authenticationPassphrase == null || authenticationPassphrase.trim().equals("")) { - // No Authentication and no Privacy - securityLevel = SecurityLevel.NOAUTH_NOPRIV; - } - else { - // With Authentication - if (privacyPassphrase == null || privacyPassphrase.trim().equals("")) { - // No Privacy - securityLevel = SecurityLevel.AUTH_NOPRIV; - } - else { - // With Privacy - securityLevel = SecurityLevel.AUTH_PRIV; - } - - } - snmp.getUSM().addUser( - new OctetString(username), - new UsmUser(new OctetString(securityName), authenticationProtocol, new OctetString( - authenticationPassphrase), privacyProtocol, new OctetString(privacyPassphrase))); - // create the target - target = new UserTarget(); - target.setAddress(targetAddress); - target.setRetries(retries); - target.setTimeout(timeout); - target.setVersion(SnmpConstants.version3); - target.setSecurityLevel(securityLevel); - target.setSecurityName(new OctetString(securityName)); - } - - public String getInterfaceAddress() { - return null; - } - - @Override - public String getDeviceAddress() { - return targetAddress.toString(); - } - - public String getSettings() { - String settings = SnmpDriverSettingVariableNames.SNMPVersion.toString() + "=" + SNMPVersion.V3 + ":" - + SnmpDriverSettingVariableNames.USERNAME + "=" + username + ":" - + SnmpDriverSettingVariableNames.SECURITYNAME + "=" + securityName + ":" - + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=" + authenticationPassphrase + ":" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=" + privacyPassphrase; - - return settings; - - } - - public Object getConnectionHandle() { - return this; - } + // private UserTarget target; // snmp v3 target + private final String username; + private final String securityName; + private final OID authenticationProtocol; + private final String authenticationPassphrase; + private final OID privacyProtocol; + private final String privacyPassphrase; + + /** + * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol + * + * @param address Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" + * @param username String containing username + * @param securityName the security name of the user (typically the user name). [required by snmp4j library] + * @param authenticationProtocol the authentication protocol ID to be associated with this user. If set to null, this + * user + * only supports unauthenticated messages. [required by snmp4j library] eg. AuthMD5.ID + * @param authenticationPassphrase the authentication pass phrase. If not null, authenticationProtocol must + * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 + * bytes. If the length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @param privacyProtocol the privacy protocol ID to be associated with this user. If set to null, this user only + * supports not encrypted messages. [required by snmp4j library] eg. PrivDES.ID + * @param privacyPassphrase the privacy pass phrase. If not null, privacyProtocol must also be not + * null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 bytes. If the + * length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @throws ConnectionException + * @throws ArgumentSyntaxException + */ + + public SnmpDeviceV3(String address, String username, String securityName, OID authenticationProtocol, String + authenticationPassphrase, OID privacyProtocol, String privacyPassphrase) throws ConnectionException, ArgumentSyntaxException { + super(address, authenticationPassphrase); + + this.username = username; + this.securityName = securityName; + this.authenticationProtocol = authenticationProtocol; + this.authenticationPassphrase = authenticationPassphrase; + this.privacyProtocol = privacyProtocol; + this.privacyPassphrase = privacyPassphrase; + } + + /** + * snmp constructor takes primary parameters in order to create snmp object. this implementation uses UDP protocol + * Default values: authenticationProtocol = AuthMD5.ID; privacyProtocol = PrivDES.ID; + * + * @param address Contains ip and port. accepted string "X.X.X.X/portNo" or "udp:X.X.X.X/portNo" + * @param username String containing username + * @param securityName the security name of the user (typically the user name). [required by snmp4j library] + * @param authenticationPassphrase the authentication pass phrase. If not null, authenticationProtocol must + * also be not null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 + * bytes. If the length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @param privacyPassphrase the privacy pass phrase. If not null, privacyProtocol must also be not + * null. RFC3414 §11.2 requires pass phrases to have a minimum length of 8 bytes. If the + * length of authenticationPassphrase is less than 8 bytes an + * IllegalArgumentException is thrown. [required by snmp4j library] + * @throws ConnectionException + * @throws ArgumentSyntaxException + */ + + public SnmpDeviceV3(String address, String username, String securityName, String authenticationPassphrase, String privacyPassphrase) + throws ConnectionException, ArgumentSyntaxException { + super(address, authenticationPassphrase); + + this.username = username; + this.securityName = securityName; + authenticationProtocol = AuthMD5.ID; + this.authenticationPassphrase = authenticationPassphrase; + privacyProtocol = PrivDES.ID; + this.privacyPassphrase = privacyPassphrase; + } + + @Override + void setTarget() { + int securityLevel = -1; + if (authenticationPassphrase == null || authenticationPassphrase.trim().equals("")) { + // No Authentication and no Privacy + securityLevel = SecurityLevel.NOAUTH_NOPRIV; + } else { + // With Authentication + if (privacyPassphrase == null || privacyPassphrase.trim().equals("")) { + // No Privacy + securityLevel = SecurityLevel.AUTH_NOPRIV; + } else { + // With Privacy + securityLevel = SecurityLevel.AUTH_PRIV; + } + + } + snmp.getUSM().addUser(new OctetString(username), + new UsmUser(new OctetString(securityName), authenticationProtocol, new OctetString(authenticationPassphrase), + privacyProtocol, new OctetString(privacyPassphrase))); + // create the target + target = new UserTarget(); + target.setAddress(targetAddress); + target.setRetries(retries); + target.setTimeout(timeout); + target.setVersion(SnmpConstants.version3); + target.setSecurityLevel(securityLevel); + target.setSecurityName(new OctetString(securityName)); + } + + public String getInterfaceAddress() { + return null; + } + + @Override + public String getDeviceAddress() { + return targetAddress.toString(); + } + + public String getSettings() { + String settings = SnmpDriverSettingVariableNames.SNMPVersion + .toString() + "=" + SNMPVersion.V3 + ":" + SnmpDriverSettingVariableNames.USERNAME + "=" + username + ":" + SnmpDriverSettingVariableNames.SECURITYNAME + "=" + securityName + ":" + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=" + authenticationPassphrase + ":" + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=" + privacyPassphrase; + + return settings; + + } + + public Object getConnectionHandle() { + return this; + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryEvent.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryEvent.java index 33b57d81..7683aad4 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryEvent.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryEvent.java @@ -20,43 +20,41 @@ */ package org.openmuc.framework.driver.snmp.implementation; -import java.util.EventObject; - import org.openmuc.framework.driver.snmp.implementation.SnmpDevice.SNMPVersion; import org.snmp4j.smi.Address; +import java.util.EventObject; + /** - * * @author Mehran Shakeri - * */ public class SnmpDiscoveryEvent extends EventObject { - /** - * - */ - private static final long serialVersionUID = 1382183246520560859L; - private final Address deviceAddress; - private final SNMPVersion snmpVersion; - private final String description; - - public SnmpDiscoveryEvent(Object source, Address address, SNMPVersion version, String description) { - super(source); - deviceAddress = address; - snmpVersion = version; - this.description = description; - } - - public Address getDeviceAddress() { - return deviceAddress; - } - - public SNMPVersion getSnmpVersion() { - return snmpVersion; - } - - public String getDescription() { - return description; - } + /** + * + */ + private static final long serialVersionUID = 1382183246520560859L; + private final Address deviceAddress; + private final SNMPVersion snmpVersion; + private final String description; + + public SnmpDiscoveryEvent(Object source, Address address, SNMPVersion version, String description) { + super(source); + deviceAddress = address; + snmpVersion = version; + this.description = description; + } + + public Address getDeviceAddress() { + return deviceAddress; + } + + public SNMPVersion getSnmpVersion() { + return snmpVersion; + } + + public String getDescription() { + return description; + } } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryListener.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryListener.java index ee5d7fb2..258a847e 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryListener.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpDiscoveryListener.java @@ -23,12 +23,11 @@ /** * In order to receive SNMP scanner result, this listener must be implemented. In case of finding new device, * onNewDeviceFound method will be called. Respective actions must be implemented in this callback function. - * + * * @author Mehran Shakeri - * */ public interface SnmpDiscoveryListener { - public void onNewDeviceFound(SnmpDiscoveryEvent e); + public void onNewDeviceFound(SnmpDiscoveryEvent e); } diff --git a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpTimeoutException.java b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpTimeoutException.java index 008309be..6ca72767 100644 --- a/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpTimeoutException.java +++ b/projects/driver/snmp/src/main/java/org/openmuc/framework/driver/snmp/implementation/SnmpTimeoutException.java @@ -22,16 +22,16 @@ public class SnmpTimeoutException extends Exception { - private static final long serialVersionUID = 1493311619722487397L; - private final String message; + private static final long serialVersionUID = 1493311619722487397L; + private final String message; - public SnmpTimeoutException(String message) { - this.message = message; - } + public SnmpTimeoutException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/driver/snmp/src/main/resources/OSGI-INF/components.xml b/projects/driver/snmp/src/main/resources/OSGI-INF/components.xml index 8e51ea35..4a95f0ff 100644 --- a/projects/driver/snmp/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/snmp/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannel.java b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannel.java index 6977bacb..a2e4947a 100644 --- a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannel.java +++ b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannel.java @@ -20,204 +20,197 @@ */ package org.openmuc.framework.driver.snmp.test; -import java.io.IOException; -import java.util.List; - import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; import org.openmuc.framework.data.ValueType; -import org.openmuc.framework.dataaccess.Channel; -import org.openmuc.framework.dataaccess.ChannelState; -import org.openmuc.framework.dataaccess.DataLoggerNotAvailableException; -import org.openmuc.framework.dataaccess.DeviceState; -import org.openmuc.framework.dataaccess.ReadRecordContainer; -import org.openmuc.framework.dataaccess.RecordListener; -import org.openmuc.framework.dataaccess.WriteValueContainer; +import org.openmuc.framework.dataaccess.*; + +import java.io.IOException; +import java.util.List; public class SnmpChannel implements Channel { - private String id; - private String address; - private String description; - private String unit; - private ValueType valueType; - private int samplingInterval; - private int samplingTimeOffset; - private String deviceAddress; - - SnmpChannel() { - } - - SnmpChannel(String deviceAddress, String address) { - this.address = address; - this.deviceAddress = deviceAddress; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getChannelAddress() { - return address; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public String getUnit() { - return unit; - } - - @Override - public ValueType getValueType() { - return valueType; - } - - @Override - public int getSamplingInterval() { - return samplingInterval; - } - - @Override - public int getSamplingTimeOffset() { - return samplingTimeOffset; - } - - @Override - public int getLoggingInterval() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int getLoggingTimeOffset() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getDriverName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDeviceAddress() { - return deviceAddress; - } - - @Override - public String getDeviceName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDeviceDescription() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ChannelState getChannelState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public DeviceState getDeviceState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void addListener(RecordListener listener) { - // TODO Auto-generated method stub - - } - - @Override - public void removeListener(RecordListener listener) { - // TODO Auto-generated method stub - - } - - @Override - public boolean isConnected() { - // TODO Auto-generated method stub - return false; - } - - @Override - public Record getLatestRecord() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setLatestRecord(Record record) { - // TODO Auto-generated method stub - - } - - @Override - public Flag write(Value value) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void write(List records) { - // TODO Auto-generated method stub - - } - - @Override - public WriteValueContainer getWriteContainer() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Record read() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ReadRecordContainer getReadContainer() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Record getLoggedRecord(long time) throws DataLoggerNotAvailableException, IOException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, - IOException { - // TODO Auto-generated method stub - return null; - } - - @Override - public double getScalingFactor() { - // TODO Auto-generated method stub - return 0; - } + private String id; + private String address; + private String description; + private String unit; + private ValueType valueType; + private int samplingInterval; + private int samplingTimeOffset; + private String deviceAddress; + + SnmpChannel() { + } + + SnmpChannel(String deviceAddress, String address) { + this.address = address; + this.deviceAddress = deviceAddress; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getChannelAddress() { + return address; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String getUnit() { + return unit; + } + + @Override + public ValueType getValueType() { + return valueType; + } + + @Override + public int getSamplingInterval() { + return samplingInterval; + } + + @Override + public int getSamplingTimeOffset() { + return samplingTimeOffset; + } + + @Override + public int getLoggingInterval() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getLoggingTimeOffset() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getDriverName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDeviceAddress() { + return deviceAddress; + } + + @Override + public String getDeviceName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDeviceDescription() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ChannelState getChannelState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public DeviceState getDeviceState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addListener(RecordListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeListener(RecordListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public boolean isConnected() { + // TODO Auto-generated method stub + return false; + } + + @Override + public Record getLatestRecord() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setLatestRecord(Record record) { + // TODO Auto-generated method stub + + } + + @Override + public Flag write(Value value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void write(List records) { + // TODO Auto-generated method stub + + } + + @Override + public WriteValueContainer getWriteContainer() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Record read() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ReadRecordContainer getReadContainer() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Record getLoggedRecord(long time) throws DataLoggerNotAvailableException, IOException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getLoggedRecords(long startTime) throws DataLoggerNotAvailableException, IOException { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getLoggedRecords(long startTime, long endTime) throws DataLoggerNotAvailableException, IOException { + // TODO Auto-generated method stub + return null; + } + + @Override + public double getScalingFactor() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannelRecordContainer.java b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannelRecordContainer.java index 20b96bca..ba749bc0 100644 --- a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannelRecordContainer.java +++ b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpChannelRecordContainer.java @@ -26,59 +26,59 @@ public class SnmpChannelRecordContainer implements ChannelRecordContainer { - private Record snmpRecord; - private SnmpChannel snmpChannel; + private Record snmpRecord; + private SnmpChannel snmpChannel; - SnmpChannelRecordContainer() { - } + SnmpChannelRecordContainer() { + } - SnmpChannelRecordContainer(SnmpChannel channel) { - snmpChannel = channel; - } + SnmpChannelRecordContainer(SnmpChannel channel) { + snmpChannel = channel; + } - SnmpChannelRecordContainer(Record record, SnmpChannel channel) { - snmpChannel = channel; - snmpRecord = record; - } + SnmpChannelRecordContainer(Record record, SnmpChannel channel) { + snmpChannel = channel; + snmpRecord = record; + } - @Override - public Record getRecord() { - return snmpRecord; - } + @Override + public Record getRecord() { + return snmpRecord; + } - @Override - public Channel getChannel() { - return snmpChannel; - } + @Override + public Channel getChannel() { + return snmpChannel; + } - @Override - public String getChannelAddress() { - return snmpChannel.getChannelAddress(); - } + @Override + public String getChannelAddress() { + return snmpChannel.getChannelAddress(); + } - @Override - public Object getChannelHandle() { - // TODO Auto-generated method stub - return null; - } + @Override + public Object getChannelHandle() { + // TODO Auto-generated method stub + return null; + } - @Override - public void setChannelHandle(Object handle) { - snmpChannel = (SnmpChannel) handle; - } + @Override + public void setChannelHandle(Object handle) { + snmpChannel = (SnmpChannel) handle; + } - @Override - public void setRecord(Record record) { - snmpRecord = new Record(record.getValue(), record.getTimestamp(), record.getFlag()); - } + @Override + public void setRecord(Record record) { + snmpRecord = new Record(record.getValue(), record.getTimestamp(), record.getFlag()); + } - @Override - public ChannelRecordContainer copy() { - SnmpChannelRecordContainer clone = new SnmpChannelRecordContainer(); - clone.setChannelHandle(snmpChannel); - clone.setRecord(snmpRecord); + @Override + public ChannelRecordContainer copy() { + SnmpChannelRecordContainer clone = new SnmpChannelRecordContainer(); + clone.setChannelHandle(snmpChannel); + clone.setRecord(snmpRecord); - return clone; - } + return clone; + } } diff --git a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpScannerExample.java b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpScannerExample.java index 4f9713b4..b6420249 100644 --- a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpScannerExample.java +++ b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpScannerExample.java @@ -31,50 +31,49 @@ public class SnmpScannerExample { - /** - * @param args - */ - public static void main(String[] args) { + /** + * @param args + */ + public static void main(String[] args) { - SnmpDriver myDriver = new SnmpDriver(); - String settings = SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=adminadmin:" - + SnmpDriverScanSettingVariableNames.STARTIP + "=192.168.1.0:" - + SnmpDriverScanSettingVariableNames.ENDIP + "=192.168.10.0"; + SnmpDriver myDriver = new SnmpDriver(); + String settings = SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=adminadmin:" + SnmpDriverScanSettingVariableNames + .STARTIP + "=192.168.1.0:" + SnmpDriverScanSettingVariableNames.ENDIP + "=192.168.10.0"; - class TestListener implements DriverDeviceScanListener { + class TestListener implements DriverDeviceScanListener { - @Override - public void scanProgressUpdate(int progress) { - } + @Override + public void scanProgressUpdate(int progress) { + } - @Override - public void deviceFound(DeviceScanInfo device) { - System.out.println("-----------------------------"); - System.out.println("New device found: "); - System.out.println("Address: " + device.getDeviceAddress()); - System.out.println("Description: " + device.getDescription()); - System.out.println("-----------------------------"); - } + @Override + public void deviceFound(DeviceScanInfo device) { + System.out.println("-----------------------------"); + System.out.println("New device found: "); + System.out.println("Address: " + device.getDeviceAddress()); + System.out.println("Description: " + device.getDescription()); + System.out.println("-----------------------------"); + } - } - ; - TestListener listener = new TestListener(); - try { - myDriver.scanForDevices(settings, listener); - Thread.sleep(100); - } catch (InterruptedException iex) { - System.out.println("Request cancelled: " + iex.getMessage()); + } + ; + TestListener listener = new TestListener(); + try { + myDriver.scanForDevices(settings, listener); + Thread.sleep(100); + } catch (InterruptedException iex) { + System.out.println("Request cancelled: " + iex.getMessage()); - } catch (ArgumentSyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ScanException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ScanInterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + } catch (ArgumentSyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ScanException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ScanInterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpTest.java b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpTest.java index 19293874..7d80551b 100644 --- a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpTest.java +++ b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/SnmpTest.java @@ -30,96 +30,93 @@ public class SnmpTest { - private static SnmpDriver snmpDriver; - private static String correctSetting; - - @BeforeClass - public static void beforeClass() { - snmpDriver = new SnmpDriver(); - correctSetting = SnmpDriverSettingVariableNames.USERNAME + "=username:" - + SnmpDriverSettingVariableNames.SECURITYNAME + "=securityname:" - + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=password:" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=privacy"; - } - - @Test(expected = ArgumentSyntaxException.class) - public void testInvalidSettingStringNumber() throws ConnectionException, ArgumentSyntaxException { - - String settings = SnmpDriverSettingVariableNames.SECURITYNAME + "=security:" - + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=pass:" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=pass"; - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testNullSettingStringNumber() throws ConnectionException, ArgumentSyntaxException { - - snmpDriver.connect("1.1.1.1/1", null); - snmpDriver.connect("1.1.1.1/1", null); - snmpDriver.connect("1.1.1.1/1", null); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testEmptySettingStringNumber() throws ConnectionException, ArgumentSyntaxException { - - snmpDriver.connect("1.1.1.1/1", ""); - snmpDriver.connect("1.1.1.1/1", ""); - snmpDriver.connect("1.1.1.1/1", ""); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testInvalidSettingStringFormat() throws ConnectionException, ArgumentSyntaxException { - - String settings = SnmpDriverSettingVariableNames.USERNAME + "=username&" - + SnmpDriverSettingVariableNames.SECURITYNAME + "=username:" - + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=pass:" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=pass"; - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - - settings = SnmpDriverSettingVariableNames.USERNAME + ":username&" + SnmpDriverSettingVariableNames.SECURITYNAME - + "=username:" + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=pass:" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=pass"; - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - snmpDriver.connect("1.1.1.1/1", settings); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testInvalidDeviceAddress() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect("1.1.1.1:1", correctSetting); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testNullDeviceAddress() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect(null, correctSetting); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testEmptyDeviceAddress() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect("", correctSetting); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testIncorrectSnmpVersoin() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect("1.1.1.1/1", correctSetting); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testNullSnmpVersoin() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect("1.1.1.1/1", correctSetting); - } - - @Test(expected = ArgumentSyntaxException.class) - public void testEmptySnmpVersoin() throws ConnectionException, ArgumentSyntaxException { - snmpDriver.connect("1.1.1.1/1", correctSetting); - } - - @AfterClass - public static void afterClass() { - snmpDriver = null; - } + private static SnmpDriver snmpDriver; + private static String correctSetting; + + @BeforeClass + public static void beforeClass() { + snmpDriver = new SnmpDriver(); + correctSetting = SnmpDriverSettingVariableNames.USERNAME + "=username:" + SnmpDriverSettingVariableNames.SECURITYNAME + + "=securityname:" + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=password:" + + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=privacy"; + } + + @Test(expected = ArgumentSyntaxException.class) + public void testInvalidSettingStringNumber() throws ConnectionException, ArgumentSyntaxException { + + String settings = SnmpDriverSettingVariableNames.SECURITYNAME + "=security:" + SnmpDriverSettingVariableNames + .AUTHENTICATIONPASSPHRASE + "=pass:" + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=pass"; + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testNullSettingStringNumber() throws ConnectionException, ArgumentSyntaxException { + + snmpDriver.connect("1.1.1.1/1", null); + snmpDriver.connect("1.1.1.1/1", null); + snmpDriver.connect("1.1.1.1/1", null); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testEmptySettingStringNumber() throws ConnectionException, ArgumentSyntaxException { + + snmpDriver.connect("1.1.1.1/1", ""); + snmpDriver.connect("1.1.1.1/1", ""); + snmpDriver.connect("1.1.1.1/1", ""); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testInvalidSettingStringFormat() throws ConnectionException, ArgumentSyntaxException { + + String settings = SnmpDriverSettingVariableNames.USERNAME + "=username&" + SnmpDriverSettingVariableNames.SECURITYNAME + + "=username:" + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=pass:" + SnmpDriverSettingVariableNames + .PRIVACYPASSPHRASE + "=pass"; + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + + settings = SnmpDriverSettingVariableNames.USERNAME + ":username&" + SnmpDriverSettingVariableNames.SECURITYNAME + "=username:" + + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=pass:" + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + + "=pass"; + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + snmpDriver.connect("1.1.1.1/1", settings); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testInvalidDeviceAddress() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect("1.1.1.1:1", correctSetting); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testNullDeviceAddress() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect(null, correctSetting); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testEmptyDeviceAddress() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect("", correctSetting); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testIncorrectSnmpVersoin() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect("1.1.1.1/1", correctSetting); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testNullSnmpVersoin() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect("1.1.1.1/1", correctSetting); + } + + @Test(expected = ArgumentSyntaxException.class) + public void testEmptySnmpVersoin() throws ConnectionException, ArgumentSyntaxException { + snmpDriver.connect("1.1.1.1/1", correctSetting); + } + + @AfterClass + public static void afterClass() { + snmpDriver = null; + } } diff --git a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/UsecaseExample.java b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/UsecaseExample.java index c1e20977..21abb3ff 100644 --- a/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/UsecaseExample.java +++ b/projects/driver/snmp/src/test/java/org/openmuc/framework/driver/snmp/test/UsecaseExample.java @@ -20,9 +20,6 @@ */ package org.openmuc.framework.driver.snmp.test; -import java.util.ArrayList; -import java.util.List; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.driver.snmp.SnmpDriver; import org.openmuc.framework.driver.snmp.SnmpDriver.SnmpDriverSettingVariableNames; @@ -31,49 +28,51 @@ import org.openmuc.framework.driver.spi.ChannelRecordContainer; import org.openmuc.framework.driver.spi.ConnectionException; +import java.util.ArrayList; +import java.util.List; + public class UsecaseExample { - /** - * @param args - */ - public static void main(String[] args) { + /** + * @param args + */ + public static void main(String[] args) { - try { + try { - SnmpDriver snmpDriver = new SnmpDriver(); - // SNMPVersion=V2c:COMMUNITY=root:SECURITYNAME=root:AUTHENTICATIONPASSPHRASE=adminadmin:PRIVACYPASSPHRASE=adminadmin - String settings = SnmpDriverSettingVariableNames.SNMPVersion + "=" + SNMPVersion.V2c + ":" - + SnmpDriverSettingVariableNames.USERNAME + "=root:" + SnmpDriverSettingVariableNames.SECURITYNAME - + "=root:" + SnmpDriverSettingVariableNames.AUTHENTICATIONPASSPHRASE + "=adminadmin:" - + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=adminadmin"; - System.out.println(settings); - SnmpDevice myDevice = (SnmpDevice) snmpDriver.connect("192.168.1.1/161", settings); + SnmpDriver snmpDriver = new SnmpDriver(); + // SNMPVersion=V2c:COMMUNITY=root:SECURITYNAME=root:AUTHENTICATIONPASSPHRASE=adminadmin:PRIVACYPASSPHRASE=adminadmin + String settings = SnmpDriverSettingVariableNames.SNMPVersion + "=" + SNMPVersion.V2c + ":" + SnmpDriverSettingVariableNames + .USERNAME + "=root:" + SnmpDriverSettingVariableNames.SECURITYNAME + "=root:" + SnmpDriverSettingVariableNames + .AUTHENTICATIONPASSPHRASE + "=adminadmin:" + SnmpDriverSettingVariableNames.PRIVACYPASSPHRASE + "=adminadmin"; + System.out.println(settings); + SnmpDevice myDevice = (SnmpDevice) snmpDriver.connect("192.168.1.1/161", settings); - List containers = new ArrayList(); + List containers = new ArrayList(); - SnmpChannel ch1 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.1.1.0"); - SnmpChannel ch2 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.25.1.1.0"); - SnmpChannel ch3 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.1.5.0"); - containers.add(new SnmpChannelRecordContainer(ch1)); - containers.add(new SnmpChannelRecordContainer(ch2)); - containers.add(new SnmpChannelRecordContainer(ch3)); + SnmpChannel ch1 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.1.1.0"); + SnmpChannel ch2 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.25.1.1.0"); + SnmpChannel ch3 = new SnmpChannel("192.168.1.1/161", "1.3.6.1.2.1.1.5.0"); + containers.add(new SnmpChannelRecordContainer(ch1)); + containers.add(new SnmpChannelRecordContainer(ch2)); + containers.add(new SnmpChannelRecordContainer(ch3)); - myDevice.read(containers, null, null); + myDevice.read(containers, null, null); - for (ChannelRecordContainer container : containers) { - if (container.getRecord() != null) { - System.out.println(container.getRecord().getValue()); - } - } + for (ChannelRecordContainer container : containers) { + if (container.getRecord() != null) { + System.out.println(container.getRecord().getValue()); + } + } - } catch (ConnectionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ArgumentSyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + } catch (ConnectionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ArgumentSyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - } + } } diff --git a/projects/driver/wmbus/build.gradle b/projects/driver/wmbus/build.gradle index 0cb6513f..14f9cfef 100644 --- a/projects/driver/wmbus/build.gradle +++ b/projects/driver/wmbus/build.gradle @@ -1,30 +1,29 @@ - configurations.create('embed') def jmbusversion = "2.1.0" dependencies { - compile group: 'org.openmuc', name: 'jmbus', version: jmbusversion - embed group: 'org.openmuc', name: 'jmbus', version: jmbusversion + compile group: 'org.openmuc', name: 'jmbus', version: jmbusversion + embed group: 'org.openmuc', name: 'jmbus', version: jmbusversion // compile files('dependencies/jmbus-' + jmbusversion + '.jar') // embed files('dependencies/jmbus-' + jmbusversion + '.jar') - compile project(':openmuc-core-spi') + compile project(':openmuc-core-spi') } jar { - manifest { - name = "OpenMUC Driver - wM-Bus" - instruction 'Bundle-ClassPath', '.,lib/jmbus-' + jmbusversion + '.jar' - instruction 'Import-Package', '!org.openmuc.jmbus*,gnu.io,javax.crypto,javax.crypto.spec,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Driver - wM-Bus" + instruction 'Bundle-ClassPath', '.,lib/jmbus-' + jmbusversion + '.jar' + instruction 'Import-Package', '!org.openmuc.jmbus*,gnu.io,javax.crypto,javax.crypto.spec,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusConnection.java b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusConnection.java index 84c0d46e..16d566fc 100644 --- a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusConnection.java +++ b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusConnection.java @@ -20,91 +20,84 @@ */ package org.openmuc.framework.driver.wmbus; -import java.util.ArrayList; -import java.util.List; - import org.openmuc.framework.config.ArgumentSyntaxException; import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.driver.spi.ChannelRecordContainer; -import org.openmuc.framework.driver.spi.ChannelValueContainer; -import org.openmuc.framework.driver.spi.Connection; -import org.openmuc.framework.driver.spi.ConnectionException; -import org.openmuc.framework.driver.spi.RecordsReceivedListener; +import org.openmuc.framework.driver.spi.*; import org.openmuc.jmbus.HexConverter; import org.openmuc.jmbus.SecondaryAddress; import org.openmuc.jmbus.WMBusSap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * Class representing an MBus Connection.
          * This class will bind to the local com-interface.
          - * */ public class WMBusConnection implements Connection { - private final static Logger logger = LoggerFactory.getLogger(WMBusConnection.class); - - private final SecondaryAddress secondaryAddress; - private final WMBusSerialInterface serialInterface; - private final WMBusSap wMBusSap; - private List containersToListenFor = new ArrayList(); - - public WMBusConnection(WMBusSap wMBusSap, SecondaryAddress secondaryAddress, String keyString, - WMBusSerialInterface serialInterface) throws ArgumentSyntaxException { - this.wMBusSap = wMBusSap; - this.serialInterface = serialInterface; - this.secondaryAddress = secondaryAddress; - - if (keyString != null) { - - byte[] keyAsBytes; - try { - keyAsBytes = HexConverter.getByteArrayFromShortHexString(keyString); - } catch (NumberFormatException e) { - serialInterface.connectionClosedIndication(secondaryAddress); - throw new ArgumentSyntaxException("The key could not be converted to a byte array."); - } - wMBusSap.setKey(secondaryAddress, keyAsBytes); - } - } - - @Override - public List scanForChannels(String settings) throws UnsupportedOperationException, - ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void disconnect() { - wMBusSap.removeKey(secondaryAddress); - - synchronized (serialInterface) { - serialInterface.connectionClosedIndication(secondaryAddress); - } - - } - - @Override - public Object read(List containers, Object containerListHandle, String samplingGroup) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - @Override - public void startListening(List containers, RecordsReceivedListener listener) - throws UnsupportedOperationException, ConnectionException { - containersToListenFor = containers; - serialInterface.listener = listener; - } - - @Override - public Object write(List containers, Object containerListHandle) - throws UnsupportedOperationException, ConnectionException { - throw new UnsupportedOperationException(); - } - - public List getContainersToListenFor() { - return containersToListenFor; - } + private final static Logger logger = LoggerFactory.getLogger(WMBusConnection.class); + + private final SecondaryAddress secondaryAddress; + private final WMBusSerialInterface serialInterface; + private final WMBusSap wMBusSap; + private List containersToListenFor = new ArrayList(); + + public WMBusConnection(WMBusSap wMBusSap, SecondaryAddress secondaryAddress, String keyString, WMBusSerialInterface serialInterface) + throws ArgumentSyntaxException { + this.wMBusSap = wMBusSap; + this.serialInterface = serialInterface; + this.secondaryAddress = secondaryAddress; + + if (keyString != null) { + + byte[] keyAsBytes; + try { + keyAsBytes = HexConverter.getByteArrayFromShortHexString(keyString); + } catch (NumberFormatException e) { + serialInterface.connectionClosedIndication(secondaryAddress); + throw new ArgumentSyntaxException("The key could not be converted to a byte array."); + } + wMBusSap.setKey(secondaryAddress, keyAsBytes); + } + } + + @Override + public List scanForChannels(String settings) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void disconnect() { + wMBusSap.removeKey(secondaryAddress); + + synchronized (serialInterface) { + serialInterface.connectionClosedIndication(secondaryAddress); + } + + } + + @Override + public Object read(List containers, Object containerListHandle, String samplingGroup) throws + UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + @Override + public void startListening(List containers, RecordsReceivedListener listener) throws + UnsupportedOperationException, ConnectionException { + containersToListenFor = containers; + serialInterface.listener = listener; + } + + @Override + public Object write(List containers, Object containerListHandle) throws UnsupportedOperationException, ConnectionException { + throw new UnsupportedOperationException(); + } + + public List getContainersToListenFor() { + return containersToListenFor; + } } diff --git a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusDriver.java b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusDriver.java index 97285143..db9b0fda 100644 --- a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusDriver.java +++ b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusDriver.java @@ -34,77 +34,77 @@ import org.slf4j.LoggerFactory; public class WMBusDriver implements DriverService { - private final static Logger logger = LoggerFactory.getLogger(WMBusDriver.class); - - private final static DriverInfo info = new DriverInfo("wmbus", // id - // description - "Wireless M-Bus is a protocol to read out meters and sensors.", - // device address - "Synopsis: :\nExample for : /dev/ttyS0 (Unix), COM1 (Windows)\n as a hex string", - // settings - "Synopsis: []\n", - // channel address - "Synopsis: :", - // device scan parameters - "N.A."); - - @Override - public DriverInfo getInfo() { - return info; - } - - @Override - public void scanForDevices(String settings, DriverDeviceScanListener listener) - throws UnsupportedOperationException, ArgumentSyntaxException, ScanException, ScanInterruptedException { - throw new UnsupportedOperationException(); - } - - @Override - public void interruptDeviceScan() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, - ConnectionException { - - String[] deviceAddressTokens = deviceAddress.trim().split(":"); - - if (deviceAddressTokens.length != 2) { - throw new ArgumentSyntaxException("The device address does not consist of two parameters."); - } - - String serialPortName = deviceAddressTokens[0]; - String secondaryAddressAsString = deviceAddressTokens[1].toLowerCase(); - SecondaryAddress secondaryAddress; - try { - secondaryAddress = SecondaryAddress.getFromWMBusLinkLayerHeader( - HexConverter.getByteArrayFromShortHexString(secondaryAddressAsString), 0); - } catch (NumberFormatException e) { - throw new ArgumentSyntaxException("The SecondaryAddress: " + secondaryAddressAsString - + " could not be converted to a byte array."); - } - - String[] settingsTokens = settings.trim().toLowerCase().split(" "); - - if (settingsTokens.length < 2 || settingsTokens.length > 3) { - throw new ArgumentSyntaxException("The device's settings parameters does not contain 2 or 3 parameters."); - } - - String transceiverString = settingsTokens[0]; - String modeString = settingsTokens[1]; - String keyString = null; - if (settingsTokens.length == 3) { - keyString = settingsTokens[2]; - } - - WMBusSerialInterface serialInterface; - - synchronized (this) { - serialInterface = WMBusSerialInterface.getInstance(serialPortName, transceiverString, modeString); - return serialInterface.connect(secondaryAddress, keyString); - } - - } + private final static Logger logger = LoggerFactory.getLogger(WMBusDriver.class); + + private final static DriverInfo info = new DriverInfo("wmbus", // id + // description + "Wireless M-Bus is a protocol to read out meters and sensors.", + // device address + "Synopsis: :\nExample for : " + + "/dev/ttyS0 (Unix), COM1 (Windows)\n as a hex string", + // settings + "Synopsis: []\n", + // channel address + "Synopsis: :", + // device scan parameters + "N.A."); + + @Override + public DriverInfo getInfo() { + return info; + } + + @Override + public void scanForDevices(String settings, DriverDeviceScanListener listener) throws UnsupportedOperationException, + ArgumentSyntaxException, ScanException, ScanInterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public void interruptDeviceScan() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public Connection connect(String deviceAddress, String settings) throws ArgumentSyntaxException, ConnectionException { + + String[] deviceAddressTokens = deviceAddress.trim().split(":"); + + if (deviceAddressTokens.length != 2) { + throw new ArgumentSyntaxException("The device address does not consist of two parameters."); + } + + String serialPortName = deviceAddressTokens[0]; + String secondaryAddressAsString = deviceAddressTokens[1].toLowerCase(); + SecondaryAddress secondaryAddress; + try { + secondaryAddress = SecondaryAddress + .getFromWMBusLinkLayerHeader(HexConverter.getByteArrayFromShortHexString(secondaryAddressAsString), 0); + } catch (NumberFormatException e) { + throw new ArgumentSyntaxException( + "The SecondaryAddress: " + secondaryAddressAsString + " could not be converted to a byte array."); + } + + String[] settingsTokens = settings.trim().toLowerCase().split(" "); + + if (settingsTokens.length < 2 || settingsTokens.length > 3) { + throw new ArgumentSyntaxException("The device's settings parameters does not contain 2 or 3 parameters."); + } + + String transceiverString = settingsTokens[0]; + String modeString = settingsTokens[1]; + String keyString = null; + if (settingsTokens.length == 3) { + keyString = settingsTokens[2]; + } + + WMBusSerialInterface serialInterface; + + synchronized (this) { + serialInterface = WMBusSerialInterface.getInstance(serialPortName, transceiverString, modeString); + return serialInterface.connect(secondaryAddress, keyString); + } + + } } diff --git a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusSerialInterface.java b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusSerialInterface.java index cbedf3ae..3db42b91 100644 --- a/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusSerialInterface.java +++ b/projects/driver/wmbus/src/main/java/org/openmuc/framework/driver/wmbus/WMBusSerialInterface.java @@ -20,305 +20,267 @@ */ package org.openmuc.framework.driver.wmbus; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.Value; +import org.openmuc.framework.data.*; import org.openmuc.framework.driver.spi.ChannelRecordContainer; import org.openmuc.framework.driver.spi.Connection; import org.openmuc.framework.driver.spi.ConnectionException; import org.openmuc.framework.driver.spi.RecordsReceivedListener; -import org.openmuc.jmbus.Bcd; -import org.openmuc.jmbus.DataRecord; -import org.openmuc.jmbus.DecodingException; -import org.openmuc.jmbus.HexConverter; -import org.openmuc.jmbus.SecondaryAddress; -import org.openmuc.jmbus.VariableDataStructure; -import org.openmuc.jmbus.WMBusDataMessage; -import org.openmuc.jmbus.WMBusListener; -import org.openmuc.jmbus.WMBusMode; -import org.openmuc.jmbus.WMBusSap; -import org.openmuc.jmbus.WMBusSapAmber; -import org.openmuc.jmbus.WMBusSapRadioCrafts; +import org.openmuc.jmbus.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.*; + /** * Class representing an MBus Connection.
          * This class will bind to the local com-interface.
          - * */ public class WMBusSerialInterface { - private final static Logger logger = LoggerFactory.getLogger(WMBusSerialInterface.class); - - private final static Map interfaces = new HashMap(); - private final HashMap connectionsBySecondaryAddress = new HashMap(); - RecordsReceivedListener listener; - - private final WMBusSap wMBusSap; - private final String serialPortName; - private final String transceiverString; - private final String modeString; - - public class Receiver implements WMBusListener { - - @Override - public void discardedBytes(byte[] bytes) { - if (logger.isDebugEnabled()) { - logger.debug("received bytes that will be discarded: " + HexConverter.getHexStringFromByteArray(bytes)); - } - } - - @Override - public void newMessage(WMBusDataMessage message) { - - try { - message.decode(); - } catch (DecodingException e) { - if (logger.isDebugEnabled()) { - logger.debug("Unable to decode header of received message: " + message, e); - } - return; - } - - synchronized (this) { - WMBusConnection connection = connectionsBySecondaryAddress.get(message.getSecondaryAddress() - .getHashCode()); - - if (connection == null) { - if (logger.isTraceEnabled()) { - logger.trace("WMBus: connection is null, from device: {} with HashCode: {}", message - .getSecondaryAddress().getDeviceId().toString(), message.getSecondaryAddress() - .getHashCode()); - } - return; - } - - List channelContainers = connection.getContainersToListenFor(); - - if (channelContainers.size() == 0) { - if (logger.isTraceEnabled()) { - logger.trace("WMBus: channelContainers.size == 0, from device: " - + message.getSecondaryAddress().getDeviceId().toString()); - } - return; - } - - VariableDataStructure variableDataStructure = message.getVariableDataResponse(); - - try { - variableDataStructure.decode(); - } catch (DecodingException e) { - if (logger.isWarnEnabled()) { - logger.warn("Unable to decode header of variable data response or received message: {}", - message, e); - } - return; - } - - List dataRecords = message.getVariableDataResponse().getDataRecords(); - String[] dibvibs = new String[dataRecords.size()]; - - int i = 0; - for (DataRecord dataRecord : dataRecords) { - dibvibs[i++] = HexConverter.getShortHexStringFromByteArray(dataRecord.getDIB()) + ':' - + HexConverter.getShortHexStringFromByteArray(dataRecord.getVIB()); - } - - List containersReceived = new ArrayList(); - - long timestamp = System.currentTimeMillis(); - - for (ChannelRecordContainer container : channelContainers) { - i = 0; - for (DataRecord dataRecord : dataRecords) { - - if (dibvibs[i++].equalsIgnoreCase(container.getChannelAddress())) { - - try { - dataRecord.decode(); - } catch (DecodingException e) { - if (logger.isWarnEnabled()) { - logger.warn( - "Unable to parse received data record with : = " + dibvibs[i], e); - } - continue; - } - Value value = null; - switch (dataRecord.getDataValueType()) { - case DATE: - value = new StringValue(((Date) dataRecord.getDataValue()).toString()); - container.setRecord(new Record(value, timestamp)); - break; - case STRING: - value = new StringValue((String) dataRecord.getDataValue()); - container.setRecord(new Record(value, timestamp)); - break; - case DOUBLE: - value = new DoubleValue(dataRecord.getScaledDataValue()); - container.setRecord(new Record(value, timestamp)); - break; - case LONG: - if (dataRecord.getMultiplierExponent() == 0) { - value = new LongValue((Long) dataRecord.getDataValue()); - container.setRecord(new Record(value, timestamp)); - } - else { - value = new DoubleValue(dataRecord.getScaledDataValue()); - container.setRecord(new Record(value, timestamp)); - } - break; - case BCD: - if (dataRecord.getMultiplierExponent() == 0) { - value = new LongValue(((Bcd) dataRecord.getDataValue()).longValue()); - container.setRecord(new Record(value, timestamp)); - } - else { - value = new DoubleValue(((Bcd) dataRecord.getDataValue()).longValue() - * Math.pow(10, dataRecord.getMultiplierExponent())); - container.setRecord(new Record(value, timestamp)); - } - break; - case NONE: - if (logger.isWarnEnabled()) { - logger.warn("Received data record with : = " + dibvibs[i] - + " has value type NONE."); - } - continue; - } - if (logger.isTraceEnabled()) { - logger.trace("WMBus: Value from channel {}", container.getChannel().getId() + " is:" - + value.toString()); - } - containersReceived.add(container); - - break; - - } - - } - - } - - listener.newRecords(containersReceived); - - } - - } - - @Override - public void stoppedListening(IOException e) { - WMBusSerialInterface.this.stoppedListening(); - } - - } - - public static WMBusSerialInterface getInstance(String serialPortName, String transceiverString, String modeString) - throws ConnectionException, ArgumentSyntaxException { - WMBusSerialInterface serialInterface; - - synchronized (interfaces) { - serialInterface = interfaces.get(serialPortName); - - if (serialInterface != null) { - if (!serialInterface.modeString.equals(modeString) - || !serialInterface.transceiverString.equals(transceiverString)) { - throw new ConnectionException( - "Connections serial interface is already in use with a different transceiver or mode"); - } - } - else { - serialInterface = new WMBusSerialInterface(serialPortName, transceiverString, modeString); - interfaces.put(serialPortName, serialInterface); - } - } - - return serialInterface; - - } - - private WMBusSerialInterface(String serialPortName, String transceiverString, String modeString) - throws ArgumentSyntaxException, ConnectionException { - - this.serialPortName = serialPortName; - this.transceiverString = transceiverString; - this.modeString = modeString; - - WMBusMode mode = null; - - if (modeString.equalsIgnoreCase("s")) { - mode = WMBusMode.S; - } - else if (modeString.equalsIgnoreCase("t")) { - mode = WMBusMode.T; - } - else { - throw new ArgumentSyntaxException( - "The wireless M-Bus mode is not correctly specified in the device's parameters string. Should be S or T but is: " - + modeString); - } - - if (transceiverString.equals("amber")) { - wMBusSap = new WMBusSapAmber(serialPortName, mode, new Receiver()); - } - else if (transceiverString.equals("rc")) { - wMBusSap = new WMBusSapRadioCrafts(serialPortName, mode, new Receiver()); - } - else { - throw new ArgumentSyntaxException( - "The type of transceiver is not correctly specified in the device's parameters string. Should be amber or rc but is: " - + transceiverString); - } - - try { - wMBusSap.open(); - } catch (IOException e) { - throw new ConnectionException("Failed to open serial interface", e); - } - } - - public void connectionClosedIndication(SecondaryAddress secondaryAddress) { - connectionsBySecondaryAddress.remove(secondaryAddress.getHashCode()); - if (connectionsBySecondaryAddress.size() == 0) { - close(); - } - } - - public void close() { - synchronized (interfaces) { - wMBusSap.close(); - interfaces.remove(serialPortName); - } - } - - public Connection connect(SecondaryAddress secondaryAddress, String keyString) throws ArgumentSyntaxException { - WMBusConnection connection = new WMBusConnection(wMBusSap, secondaryAddress, keyString, this); - if (logger.isTraceEnabled()) { - logger.trace("WMBus: connect device with ID " + secondaryAddress.getDeviceId().toString() - + " and HashCode " + secondaryAddress.getHashCode()); - } - connectionsBySecondaryAddress.put(secondaryAddress.getHashCode(), connection); - return connection; - } - - public void stoppedListening() { - synchronized (interfaces) { - interfaces.remove(serialPortName); - } - synchronized (this) { - for (WMBusConnection connection : connectionsBySecondaryAddress.values()) { - listener.connectionInterrupted("wmbus", connection); - } - connectionsBySecondaryAddress.clear(); - } - } + private final static Logger logger = LoggerFactory.getLogger(WMBusSerialInterface.class); + + private final static Map interfaces = new HashMap(); + private final HashMap connectionsBySecondaryAddress = new HashMap(); + RecordsReceivedListener listener; + + private final WMBusSap wMBusSap; + private final String serialPortName; + private final String transceiverString; + private final String modeString; + + public class Receiver implements WMBusListener { + + @Override + public void discardedBytes(byte[] bytes) { + if (logger.isDebugEnabled()) { + logger.debug("received bytes that will be discarded: " + HexConverter.getHexStringFromByteArray(bytes)); + } + } + + @Override + public void newMessage(WMBusDataMessage message) { + + try { + message.decode(); + } catch (DecodingException e) { + if (logger.isDebugEnabled()) { + logger.debug("Unable to decode header of received message: " + message, e); + } + return; + } + + synchronized (this) { + WMBusConnection connection = connectionsBySecondaryAddress.get(message.getSecondaryAddress().getHashCode()); + + if (connection == null) { + if (logger.isTraceEnabled()) { + logger.trace("WMBus: connection is null, from device: {} with HashCode: {}", + message.getSecondaryAddress().getDeviceId().toString(), message.getSecondaryAddress().getHashCode()); + } + return; + } + + List channelContainers = connection.getContainersToListenFor(); + + if (channelContainers.size() == 0) { + if (logger.isTraceEnabled()) { + logger.trace("WMBus: channelContainers.size == 0, from device: " + message.getSecondaryAddress().getDeviceId() + .toString()); + } + return; + } + + VariableDataStructure variableDataStructure = message.getVariableDataResponse(); + + try { + variableDataStructure.decode(); + } catch (DecodingException e) { + if (logger.isWarnEnabled()) { + logger.warn("Unable to decode header of variable data response or received message: {}", message, e); + } + return; + } + + List dataRecords = message.getVariableDataResponse().getDataRecords(); + String[] dibvibs = new String[dataRecords.size()]; + + int i = 0; + for (DataRecord dataRecord : dataRecords) { + dibvibs[i++] = HexConverter.getShortHexStringFromByteArray(dataRecord.getDIB()) + ':' + HexConverter + .getShortHexStringFromByteArray(dataRecord.getVIB()); + } + + List containersReceived = new ArrayList(); + + long timestamp = System.currentTimeMillis(); + + for (ChannelRecordContainer container : channelContainers) { + i = 0; + for (DataRecord dataRecord : dataRecords) { + + if (dibvibs[i++].equalsIgnoreCase(container.getChannelAddress())) { + + try { + dataRecord.decode(); + } catch (DecodingException e) { + if (logger.isWarnEnabled()) { + logger.warn("Unable to parse received data record with : = " + dibvibs[i], e); + } + continue; + } + Value value = null; + switch (dataRecord.getDataValueType()) { + case DATE: + value = new StringValue(((Date) dataRecord.getDataValue()).toString()); + container.setRecord(new Record(value, timestamp)); + break; + case STRING: + value = new StringValue((String) dataRecord.getDataValue()); + container.setRecord(new Record(value, timestamp)); + break; + case DOUBLE: + value = new DoubleValue(dataRecord.getScaledDataValue()); + container.setRecord(new Record(value, timestamp)); + break; + case LONG: + if (dataRecord.getMultiplierExponent() == 0) { + value = new LongValue((Long) dataRecord.getDataValue()); + container.setRecord(new Record(value, timestamp)); + } else { + value = new DoubleValue(dataRecord.getScaledDataValue()); + container.setRecord(new Record(value, timestamp)); + } + break; + case BCD: + if (dataRecord.getMultiplierExponent() == 0) { + value = new LongValue(((Bcd) dataRecord.getDataValue()).longValue()); + container.setRecord(new Record(value, timestamp)); + } else { + value = new DoubleValue(((Bcd) dataRecord.getDataValue()).longValue() * Math + .pow(10, dataRecord.getMultiplierExponent())); + container.setRecord(new Record(value, timestamp)); + } + break; + case NONE: + if (logger.isWarnEnabled()) { + logger.warn("Received data record with : = " + dibvibs[i] + " has value type NONE."); + } + continue; + } + if (logger.isTraceEnabled()) { + logger.trace("WMBus: Value from channel {}", container.getChannel().getId() + " is:" + value.toString()); + } + containersReceived.add(container); + + break; + + } + + } + + } + + listener.newRecords(containersReceived); + + } + + } + + @Override + public void stoppedListening(IOException e) { + WMBusSerialInterface.this.stoppedListening(); + } + + } + + public static WMBusSerialInterface getInstance(String serialPortName, String transceiverString, String modeString) throws + ConnectionException, ArgumentSyntaxException { + WMBusSerialInterface serialInterface; + + synchronized (interfaces) { + serialInterface = interfaces.get(serialPortName); + + if (serialInterface != null) { + if (!serialInterface.modeString.equals(modeString) || !serialInterface.transceiverString.equals(transceiverString)) { + throw new ConnectionException("Connections serial interface is already in use with a different transceiver or mode"); + } + } else { + serialInterface = new WMBusSerialInterface(serialPortName, transceiverString, modeString); + interfaces.put(serialPortName, serialInterface); + } + } + + return serialInterface; + + } + + private WMBusSerialInterface(String serialPortName, String transceiverString, String modeString) throws ArgumentSyntaxException, ConnectionException { + + this.serialPortName = serialPortName; + this.transceiverString = transceiverString; + this.modeString = modeString; + + WMBusMode mode = null; + + if (modeString.equalsIgnoreCase("s")) { + mode = WMBusMode.S; + } else if (modeString.equalsIgnoreCase("t")) { + mode = WMBusMode.T; + } else { + throw new ArgumentSyntaxException( + "The wireless M-Bus mode is not correctly specified in the device's parameters string. Should be S or T but is: " + modeString); + } + + if (transceiverString.equals("amber")) { + wMBusSap = new WMBusSapAmber(serialPortName, mode, new Receiver()); + } else if (transceiverString.equals("rc")) { + wMBusSap = new WMBusSapRadioCrafts(serialPortName, mode, new Receiver()); + } else { + throw new ArgumentSyntaxException( + "The type of transceiver is not correctly specified in the device's parameters string. Should be amber or rc but is: " + transceiverString); + } + + try { + wMBusSap.open(); + } catch (IOException e) { + throw new ConnectionException("Failed to open serial interface", e); + } + } + + public void connectionClosedIndication(SecondaryAddress secondaryAddress) { + connectionsBySecondaryAddress.remove(secondaryAddress.getHashCode()); + if (connectionsBySecondaryAddress.size() == 0) { + close(); + } + } + + public void close() { + synchronized (interfaces) { + wMBusSap.close(); + interfaces.remove(serialPortName); + } + } + + public Connection connect(SecondaryAddress secondaryAddress, String keyString) throws ArgumentSyntaxException { + WMBusConnection connection = new WMBusConnection(wMBusSap, secondaryAddress, keyString, this); + if (logger.isTraceEnabled()) { + logger.trace("WMBus: connect device with ID " + secondaryAddress.getDeviceId().toString() + " and HashCode " + secondaryAddress + .getHashCode()); + } + connectionsBySecondaryAddress.put(secondaryAddress.getHashCode(), connection); + return connection; + } + + public void stoppedListening() { + synchronized (interfaces) { + interfaces.remove(serialPortName); + } + synchronized (this) { + for (WMBusConnection connection : connectionsBySecondaryAddress.values()) { + listener.connectionInterrupted("wmbus", connection); + } + connectionsBySecondaryAddress.clear(); + } + } } diff --git a/projects/driver/wmbus/src/main/resources/OSGI-INF/components.xml b/projects/driver/wmbus/src/main/resources/OSGI-INF/components.xml index 32a2a207..64d87def 100644 --- a/projects/driver/wmbus/src/main/resources/OSGI-INF/components.xml +++ b/projects/driver/wmbus/src/main/resources/OSGI-INF/components.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/projects/driver/wmbus/src/test/java/org/openmuc/wmbus/test/WMBusObjectLocatorTest.java b/projects/driver/wmbus/src/test/java/org/openmuc/wmbus/test/WMBusObjectLocatorTest.java index fe39efeb..8a244810 100644 --- a/projects/driver/wmbus/src/test/java/org/openmuc/wmbus/test/WMBusObjectLocatorTest.java +++ b/projects/driver/wmbus/src/test/java/org/openmuc/wmbus/test/WMBusObjectLocatorTest.java @@ -22,29 +22,29 @@ public class WMBusObjectLocatorTest { - // @Test - // public void mbusStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); - // - // byte[] difs = locator.getDifs(); - // - // Assert.assertEquals(1, difs.length); - // Assert.assertEquals((byte) 4, difs[0]); - // - // byte[] vifs = locator.getVifs(); - // - // Assert.assertEquals(2, vifs.length); - // Assert.assertEquals((byte) 0x94, vifs[0]); - // Assert.assertEquals((byte) 0x3a, vifs[1]); - // - // } - // - // @Test - // public void obisStyle() { - // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); - // - // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); - // } + // @Test + // public void mbusStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("mbus:04/943a"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_MBUS, locator.getType()); + // + // byte[] difs = locator.getDifs(); + // + // Assert.assertEquals(1, difs.length); + // Assert.assertEquals((byte) 4, difs[0]); + // + // byte[] vifs = locator.getVifs(); + // + // Assert.assertEquals(2, vifs.length); + // Assert.assertEquals((byte) 0x94, vifs[0]); + // Assert.assertEquals((byte) 0x3a, vifs[1]); + // + // } + // + // @Test + // public void obisStyle() { + // MBusObjectLocator locator = new MBusObjectLocator("1.7.0"); + // + // Assert.assertEquals(MBusObjectLocator.TYPE_OBIS, locator.getType()); + // } } diff --git a/projects/server/restws/build.gradle b/projects/server/restws/build.gradle index 8dd56ef9..d22b57ff 100644 --- a/projects/server/restws/build.gradle +++ b/projects/server/restws/build.gradle @@ -1,23 +1,23 @@ configurations.create('embed') dependencies { - compile project(':openmuc-core-api') - compile group: 'org.apache.felix', name: 'javax.servlet', version: '1.0.0' - compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1' - embed group: 'com.google.code.gson', name: 'gson', version: '2.3.1' + compile project(':openmuc-core-api') + compile group: 'org.apache.felix', name: 'javax.servlet', version: '1.0.0' + compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1' + embed group: 'com.google.code.gson', name: 'gson', version: '2.3.1' } jar { - manifest { - name = "OpenMUC Server - RESTful Web Service" - instruction 'Bundle-ClassPath', '.,lib/gson-2.3.1.jar' - instruction 'Import-Package', '!com.google.gson.*,*' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC Server - RESTful Web Service" + instruction 'Bundle-ClassPath', '.,lib/gson-2.3.1.jar' + instruction 'Import-Package', '!com.google.gson.*,*' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/Const.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/Const.java index b516af65..4bc22e16 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/Const.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/Const.java @@ -22,38 +22,38 @@ public class Const { - public final static String REST = "/rest/"; - public final static String CHANNELS = "channels"; - public final static String DEVICES = "devices"; - public final static String DRIVERS = "drivers"; - public final static String USERS = "users"; - public final static String RECORDS = "records"; + public final static String REST = "/rest/"; + public final static String CHANNELS = "channels"; + public final static String DEVICES = "devices"; + public final static String DRIVERS = "drivers"; + public final static String USERS = "users"; + public final static String RECORDS = "records"; - public final static String ALIAS_CHANNELS = "/rest/channels"; - public final static String ALIAS_DEVICES = "/rest/devices"; - public final static String ALIAS_DRIVERS = "/rest/drivers"; - public final static String ALIAS_USERS = "/rest/users"; - public final static String ALIAS_CONTROLS = "/rest/controlls"; + public final static String ALIAS_CHANNELS = "/rest/channels"; + public final static String ALIAS_DEVICES = "/rest/devices"; + public final static String ALIAS_DRIVERS = "/rest/drivers"; + public final static String ALIAS_USERS = "/rest/users"; + public final static String ALIAS_CONTROLS = "/rest/controlls"; - public final static String RUNNING = "running"; - public final static String STATE = "state"; - public final static String RECORD = "record"; - public final static String LATESTRECORD = "latestRecord"; - public final static String ID = "id"; - public final static String FLAG = "flag"; - public final static String CONFIGS = "configs"; - public final static String SCAN = "scan"; - public final static String WRITE = "write"; - public final static String HISTORY = "history"; - public final static String SETTINGS = "settings"; - public final static String TYPE = "type"; - public final static String DEVICEADDRESS = "deviceAddress"; - public final static String DESCRIPTION = "description"; - public final static String CHANNELADDRESS = "channelAddress"; - public final static String VALUETYPE = "valueType"; - public final static String VALUETYPELENGTH = "valuetypeLength"; - public final static String GROUPS = "groups"; + public final static String RUNNING = "running"; + public final static String STATE = "state"; + public final static String RECORD = "record"; + public final static String LATESTRECORD = "latestRecord"; + public final static String ID = "id"; + public final static String FLAG = "flag"; + public final static String CONFIGS = "configs"; + public final static String SCAN = "scan"; + public final static String WRITE = "write"; + public final static String HISTORY = "history"; + public final static String SETTINGS = "settings"; + public final static String TYPE = "type"; + public final static String DEVICEADDRESS = "deviceAddress"; + public final static String DESCRIPTION = "description"; + public final static String CHANNELADDRESS = "channelAddress"; + public final static String VALUETYPE = "valueType"; + public final static String VALUETYPELENGTH = "valuetypeLength"; + public final static String GROUPS = "groups"; - public final static String DEVICE = "device"; - public final static String DRIVER = "driver"; + public final static String DEVICE = "device"; + public final static String DRIVER = "driver"; } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/FromJson.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/FromJson.java index 0378e855..79e584c5 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/FromJson.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/FromJson.java @@ -20,359 +20,324 @@ */ package org.openmuc.framework.lib.json; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.data.BooleanValue; -import org.openmuc.framework.data.ByteArrayValue; -import org.openmuc.framework.data.ByteValue; -import org.openmuc.framework.data.DoubleValue; -import org.openmuc.framework.data.FloatValue; -import org.openmuc.framework.data.IntValue; -import org.openmuc.framework.data.LongValue; -import org.openmuc.framework.data.Record; -import org.openmuc.framework.data.ShortValue; -import org.openmuc.framework.data.StringValue; -import org.openmuc.framework.data.Value; -import org.openmuc.framework.data.ValueType; +import com.google.gson.*; +import org.openmuc.framework.config.*; +import org.openmuc.framework.data.*; import org.openmuc.framework.dataaccess.DeviceState; import org.openmuc.framework.lib.json.exceptions.MissingJsonObjectException; import org.openmuc.framework.lib.json.exceptions.RestConfigIsNotCorrectException; -import org.openmuc.framework.lib.json.restObjects.RestChannel; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfig; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfig; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfig; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestRecord; -import org.openmuc.framework.lib.json.restObjects.RestUserConfig; -import org.openmuc.framework.lib.json.restObjects.RestValue; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; +import org.openmuc.framework.lib.json.restObjects.*; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class FromJson { - private final Gson gson; - private final JsonObject jsonObject; + private final Gson gson; + private final JsonObject jsonObject; - public FromJson(String jsonString) { + public FromJson(String jsonString) { - gson = new Gson(); - jsonObject = gson.fromJson(jsonString, JsonObject.class); - } + gson = new Gson(); + jsonObject = gson.fromJson(jsonString, JsonObject.class); + } - public Gson getGson() { + public Gson getGson() { - return gson; - } + return gson; + } - public JsonObject getJsonObject() { + public JsonObject getJsonObject() { - return jsonObject; - } + return jsonObject; + } - public Record getRecord(ValueType valueType) throws ClassCastException { + public Record getRecord(ValueType valueType) throws ClassCastException { - Record record = null; - JsonElement jse = jsonObject.get(Const.RECORD); + Record record = null; + JsonElement jse = jsonObject.get(Const.RECORD); - if (!jse.isJsonNull()) { - record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); - } - return record; - } + if (!jse.isJsonNull()) { + record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); + } + return record; + } - public ArrayList getRecordArrayList(ValueType valueType) throws ClassCastException { + public ArrayList getRecordArrayList(ValueType valueType) throws ClassCastException { - ArrayList recordList = new ArrayList(); + ArrayList recordList = new ArrayList(); - JsonElement jse = jsonObject.get(Const.RECORDS); - if (jse != null && jse.isJsonArray()) { - JsonArray jsa = jse.getAsJsonArray(); + JsonElement jse = jsonObject.get(Const.RECORDS); + if (jse != null && jse.isJsonArray()) { + JsonArray jsa = jse.getAsJsonArray(); - Iterator iteratorJsonArray = jsa.iterator(); - while (iteratorJsonArray.hasNext()) { - recordList.add(getRecord(valueType)); - } - } - if (recordList.size() == 0) { - recordList = null; - } - return recordList; - } + Iterator iteratorJsonArray = jsa.iterator(); + while (iteratorJsonArray.hasNext()) { + recordList.add(getRecord(valueType)); + } + } + if (recordList.size() == 0) { + recordList = null; + } + return recordList; + } - public Value getValue(ValueType valueType) throws ClassCastException { + public Value getValue(ValueType valueType) throws ClassCastException { - Value value = null; - JsonElement jse = jsonObject.get(Const.RECORD); + Value value = null; + JsonElement jse = jsonObject.get(Const.RECORD); - if (!jse.isJsonNull()) { - Record record = getRecord(valueType); - if (record != null) { - value = record.getValue(); - } - } - return value; - } + if (!jse.isJsonNull()) { + Record record = getRecord(valueType); + if (record != null) { + value = record.getValue(); + } + } + return value; + } - public boolean isRunning() { + public boolean isRunning() { - return jsonObject.get(Const.RUNNING).getAsBoolean(); - } + return jsonObject.get(Const.RUNNING).getAsBoolean(); + } - public DeviceState getDeviceState() { + public DeviceState getDeviceState() { - DeviceState ret = null; - JsonElement jse = jsonObject.get(Const.STATE); + DeviceState ret = null; + JsonElement jse = jsonObject.get(Const.STATE); - if (!jse.isJsonNull()) { - ret = gson.fromJson(jse, DeviceState.class); - } - return ret; - } + if (!jse.isJsonNull()) { + ret = gson.fromJson(jse, DeviceState.class); + } + return ret; + } - public void setChannelConfig(ChannelConfig channelConfig, String id) throws JsonSyntaxException, - IdCollisionException, RestConfigIsNotCorrectException, MissingJsonObjectException { + public void setChannelConfig(ChannelConfig channelConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { - JsonElement jse = jsonObject.get(Const.CONFIGS); + JsonElement jse = jsonObject.get(Const.CONFIGS); - if (!jse.isJsonNull()) { - RestChannelConfigMapper.setChannelConfig(channelConfig, gson.fromJson(jse, RestChannelConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } + if (!jse.isJsonNull()) { + RestChannelConfigMapper.setChannelConfig(channelConfig, gson.fromJson(jse, RestChannelConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } - public void setDeviceConfig(DeviceConfig deviceConfig, String id) throws JsonSyntaxException, IdCollisionException, - RestConfigIsNotCorrectException, MissingJsonObjectException { + public void setDeviceConfig(DeviceConfig deviceConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { - JsonElement jse = jsonObject.get(Const.CONFIGS); + JsonElement jse = jsonObject.get(Const.CONFIGS); - if (!jse.isJsonNull()) { - RestDeviceConfigMapper.setDeviceConfig(deviceConfig, gson.fromJson(jse, RestDeviceConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } - - public void setDriverConfig(DriverConfig driverConfig, String id) throws JsonSyntaxException, IdCollisionException, - RestConfigIsNotCorrectException, MissingJsonObjectException { - - JsonElement jse = jsonObject.get(Const.CONFIGS); - - if (!jse.isJsonNull()) { - RestDriverConfigMapper.setDriverConfig(driverConfig, gson.fromJson(jse, RestDriverConfig.class), id); - } - else { - throw new MissingJsonObjectException(); - } - } - - public ArrayList getStringArrayList(String listName) { - - ArrayList resultList = new ArrayList(); - - JsonElement jse = jsonObject.get(listName); - if (jse != null && jse.isJsonArray()) { - JsonArray jsa = jse.getAsJsonArray(); - - Iterator iteratorJsonArray = jsa.iterator(); - while (iteratorJsonArray.hasNext()) { - resultList.add(iteratorJsonArray.next().toString()); - } - } - if (resultList.size() == 0) { - resultList = null; - } - return resultList; - } - - public String[] getStringArray(String listName) { - - String stringArray[] = null; - - JsonElement jse = jsonObject.get(listName); - if (!jse.isJsonNull() && jse.isJsonArray()) { - stringArray = gson.fromJson(jse, String[].class); - } - return stringArray; - } - - public ArrayList getRestChannelArrayList() throws ClassCastException { - - ArrayList recordList = new ArrayList(); - JsonElement jse = jsonObject.get("records"); - JsonArray jsa; - - if (!jse.isJsonNull() && jse.isJsonArray()) { - - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - - while (jseIterator.hasNext()) { - RestChannel rc = new RestChannel(); - JsonObject jsoIterated = jseIterator.next().getAsJsonObject(); - rc.setId(jsoIterated.get(Const.ID).getAsString()); - rc.setType(gson.fromJson(jsoIterated.get(Const.TYPE), ValueType.class)); // TODO: need valueType in json - // or something else - // otherwise null pointer - // exception - rc.setRecord(getRecord(jsoIterated, rc.getType())); - - recordList.add(rc); - } - } - if (recordList.size() == 0) { - return null; - } - return recordList; - } - - public RestUserConfig getRestUserConfig() { - - JsonObject jso = jsonObject.get(Const.CONFIGS).getAsJsonObject(); - return gson.fromJson(jso, RestUserConfig.class); - } - - public List getDeviceScanInfoList() { - - List returnValue = new ArrayList(); - JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? - JsonArray jsa; - - if (jse.isJsonArray()) { - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - while (jseIterator.hasNext()) { - - JsonObject jso = jseIterator.next().getAsJsonObject(); - // String id = jso.get(Const.ID).getAsString(); - String deviceAddress = jso.get(Const.DEVICEADDRESS).getAsString(); - String settings = jso.get(Const.SETTINGS).getAsString(); - String description = jso.get(Const.DESCRIPTION).getAsString(); - returnValue.add(new DeviceScanInfo(deviceAddress, settings, description)); - } - } - else { - returnValue = null; - } - return returnValue; - } - - public List getChannelScanInfoList() { - - List returnValue = new ArrayList(); - JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? - JsonArray jsa; - - if (jse.isJsonArray()) { - jsa = jse.getAsJsonArray(); - Iterator jseIterator = jsa.iterator(); - while (jseIterator.hasNext()) { - - JsonObject jso = jseIterator.next().getAsJsonObject(); - String channelAddress = jso.get(Const.CHANNELADDRESS).getAsString(); - ValueType valueType = ValueType.valueOf(jso.get(Const.VALUETYPE).getAsString()); - int valueTypeLength = jso.get(Const.VALUETYPELENGTH).getAsInt(); - String description = jso.get(Const.DESCRIPTION).getAsString(); - returnValue.add(new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength)); - } - } - else { - returnValue = null; - } - return returnValue; - } - - private Record getRecord(JsonObject jso, ValueType valueType) throws ClassCastException { - - Record record = null; - JsonElement jse = jso.get(Const.RECORD); - - if (jse != null && !jse.isJsonNull()) { - record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); - } - return record; - } - - private Record getRecord(RestRecord rrc, ValueType type) throws ClassCastException { - - Object value = rrc.getValue(); - Value retValue = null; - if (value != null) { - retValue = getValue(type, value); - } - return new Record(retValue, rrc.getTimestamp(), rrc.getFlag()); - } - - private Value getValue(ValueType type, Object value) throws ClassCastException { - // TODO: check all value types, if it is really a float, double, ... - - if (value.getClass().isInstance(new RestValue())) { - value = ((RestValue) value).getValue(); - } - Value retValue = null; - switch (type) { - case FLOAT: - FloatValue fvalue = new FloatValue(((Double) value).floatValue()); - retValue = fvalue; - break; - case DOUBLE: - DoubleValue dValue = new DoubleValue((Double) value); - retValue = dValue; - break; - case SHORT: - ShortValue shValue = new ShortValue(((Double) value).shortValue()); - retValue = shValue; - break; - case INTEGER: - IntValue iValue = new IntValue(((Double) value).intValue()); - retValue = iValue; - break; - case LONG: - LongValue lValue = new LongValue(((Double) value).longValue()); - retValue = lValue; - break; - case BYTE: - ByteValue byValue = new ByteValue(((Double) value).byteValue()); - retValue = byValue; - break; - case BOOLEAN: - BooleanValue boValue = new BooleanValue((Boolean) value); - retValue = boValue; - break; - case BYTE_ARRAY: - @SuppressWarnings("unchecked") - ArrayList arrayList = ((ArrayList) value); - byte[] byteArray = new byte[arrayList.size()]; - for (int i = 0; i < arrayList.size(); ++i) { - byteArray[i] = arrayList.get(i).byteValue(); - } - ByteArrayValue baValue = new ByteArrayValue(byteArray); - retValue = baValue; - break; - case STRING: - StringValue stValue = new StringValue((String) value); - retValue = stValue; - break; - default: - break; - } - return retValue; - } + if (!jse.isJsonNull()) { + RestDeviceConfigMapper.setDeviceConfig(deviceConfig, gson.fromJson(jse, RestDeviceConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } + + public void setDriverConfig(DriverConfig driverConfig, String id) throws JsonSyntaxException, IdCollisionException, + RestConfigIsNotCorrectException, MissingJsonObjectException { + + JsonElement jse = jsonObject.get(Const.CONFIGS); + + if (!jse.isJsonNull()) { + RestDriverConfigMapper.setDriverConfig(driverConfig, gson.fromJson(jse, RestDriverConfig.class), id); + } else { + throw new MissingJsonObjectException(); + } + } + + public ArrayList getStringArrayList(String listName) { + + ArrayList resultList = new ArrayList(); + + JsonElement jse = jsonObject.get(listName); + if (jse != null && jse.isJsonArray()) { + JsonArray jsa = jse.getAsJsonArray(); + + Iterator iteratorJsonArray = jsa.iterator(); + while (iteratorJsonArray.hasNext()) { + resultList.add(iteratorJsonArray.next().toString()); + } + } + if (resultList.size() == 0) { + resultList = null; + } + return resultList; + } + + public String[] getStringArray(String listName) { + + String stringArray[] = null; + + JsonElement jse = jsonObject.get(listName); + if (!jse.isJsonNull() && jse.isJsonArray()) { + stringArray = gson.fromJson(jse, String[].class); + } + return stringArray; + } + + public ArrayList getRestChannelArrayList() throws ClassCastException { + + ArrayList recordList = new ArrayList(); + JsonElement jse = jsonObject.get("records"); + JsonArray jsa; + + if (!jse.isJsonNull() && jse.isJsonArray()) { + + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + + while (jseIterator.hasNext()) { + RestChannel rc = new RestChannel(); + JsonObject jsoIterated = jseIterator.next().getAsJsonObject(); + rc.setId(jsoIterated.get(Const.ID).getAsString()); + rc.setType(gson.fromJson(jsoIterated.get(Const.TYPE), ValueType.class)); // TODO: need valueType in json + // or something else + // otherwise null pointer + // exception + rc.setRecord(getRecord(jsoIterated, rc.getType())); + + recordList.add(rc); + } + } + if (recordList.size() == 0) { + return null; + } + return recordList; + } + + public RestUserConfig getRestUserConfig() { + + JsonObject jso = jsonObject.get(Const.CONFIGS).getAsJsonObject(); + return gson.fromJson(jso, RestUserConfig.class); + } + + public List getDeviceScanInfoList() { + + List returnValue = new ArrayList(); + JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? + JsonArray jsa; + + if (jse.isJsonArray()) { + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + while (jseIterator.hasNext()) { + + JsonObject jso = jseIterator.next().getAsJsonObject(); + // String id = jso.get(Const.ID).getAsString(); + String deviceAddress = jso.get(Const.DEVICEADDRESS).getAsString(); + String settings = jso.get(Const.SETTINGS).getAsString(); + String description = jso.get(Const.DESCRIPTION).getAsString(); + returnValue.add(new DeviceScanInfo(deviceAddress, settings, description)); + } + } else { + returnValue = null; + } + return returnValue; + } + + public List getChannelScanInfoList() { + + List returnValue = new ArrayList(); + JsonElement jse = jsonObject.get(Const.CHANNELS); // TODO: another name? + JsonArray jsa; + + if (jse.isJsonArray()) { + jsa = jse.getAsJsonArray(); + Iterator jseIterator = jsa.iterator(); + while (jseIterator.hasNext()) { + + JsonObject jso = jseIterator.next().getAsJsonObject(); + String channelAddress = jso.get(Const.CHANNELADDRESS).getAsString(); + ValueType valueType = ValueType.valueOf(jso.get(Const.VALUETYPE).getAsString()); + int valueTypeLength = jso.get(Const.VALUETYPELENGTH).getAsInt(); + String description = jso.get(Const.DESCRIPTION).getAsString(); + returnValue.add(new ChannelScanInfo(channelAddress, description, valueType, valueTypeLength)); + } + } else { + returnValue = null; + } + return returnValue; + } + + private Record getRecord(JsonObject jso, ValueType valueType) throws ClassCastException { + + Record record = null; + JsonElement jse = jso.get(Const.RECORD); + + if (jse != null && !jse.isJsonNull()) { + record = getRecord(gson.fromJson(jse, RestRecord.class), valueType); + } + return record; + } + + private Record getRecord(RestRecord rrc, ValueType type) throws ClassCastException { + + Object value = rrc.getValue(); + Value retValue = null; + if (value != null) { + retValue = getValue(type, value); + } + return new Record(retValue, rrc.getTimestamp(), rrc.getFlag()); + } + + private Value getValue(ValueType type, Object value) throws ClassCastException { + // TODO: check all value types, if it is really a float, double, ... + + if (value.getClass().isInstance(new RestValue())) { + value = ((RestValue) value).getValue(); + } + Value retValue = null; + switch (type) { + case FLOAT: + FloatValue fvalue = new FloatValue(((Double) value).floatValue()); + retValue = fvalue; + break; + case DOUBLE: + DoubleValue dValue = new DoubleValue((Double) value); + retValue = dValue; + break; + case SHORT: + ShortValue shValue = new ShortValue(((Double) value).shortValue()); + retValue = shValue; + break; + case INTEGER: + IntValue iValue = new IntValue(((Double) value).intValue()); + retValue = iValue; + break; + case LONG: + LongValue lValue = new LongValue(((Double) value).longValue()); + retValue = lValue; + break; + case BYTE: + ByteValue byValue = new ByteValue(((Double) value).byteValue()); + retValue = byValue; + break; + case BOOLEAN: + BooleanValue boValue = new BooleanValue((Boolean) value); + retValue = boValue; + break; + case BYTE_ARRAY: + @SuppressWarnings("unchecked") + ArrayList arrayList = ((ArrayList) value); + byte[] byteArray = new byte[arrayList.size()]; + for (int i = 0; i < arrayList.size(); ++i) { + byteArray[i] = arrayList.get(i).byteValue(); + } + ByteArrayValue baValue = new ByteArrayValue(byteArray); + retValue = baValue; + break; + case STRING: + StringValue stValue = new StringValue((String) value); + retValue = stValue; + break; + default: + break; + } + return retValue; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/ToJson.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/ToJson.java index 62cb3557..f0ede080 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/ToJson.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/ToJson.java @@ -20,270 +20,256 @@ */ package org.openmuc.framework.lib.json; -import java.util.List; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverConfig; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; import org.openmuc.framework.data.ValueType; import org.openmuc.framework.dataaccess.Channel; import org.openmuc.framework.dataaccess.DeviceState; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfig; -import org.openmuc.framework.lib.json.restObjects.RestChannelConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfig; -import org.openmuc.framework.lib.json.restObjects.RestDeviceConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfig; -import org.openmuc.framework.lib.json.restObjects.RestDriverConfigMapper; -import org.openmuc.framework.lib.json.restObjects.RestRecord; -import org.openmuc.framework.lib.json.restObjects.RestUserConfig; +import org.openmuc.framework.lib.json.restObjects.*; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import java.util.List; public class ToJson { - private final Gson gson; - private final JsonObject jsonObject; + private final Gson gson; + private final JsonObject jsonObject; - public ToJson() { + public ToJson() { - gson = new Gson(); - jsonObject = new JsonObject(); - } + gson = new Gson(); + jsonObject = new JsonObject(); + } - public JsonObject getJsonObject() { + public JsonObject getJsonObject() { - return jsonObject; - } + return jsonObject; + } - public void addJsonObject(String propertyName, JsonObject jsonObject) { + public void addJsonObject(String propertyName, JsonObject jsonObject) { - this.jsonObject.add(propertyName, jsonObject); - } + this.jsonObject.add(propertyName, jsonObject); + } - @Override - public String toString() { - return jsonObject.toString(); - } + @Override + public String toString() { + return jsonObject.toString(); + } - public void addRecord(Record record, ValueType valueType) throws ClassCastException { + public void addRecord(Record record, ValueType valueType) throws ClassCastException { - jsonObject.add(Const.RECORD, getRecordAsJsonElement(record, valueType)); - } + jsonObject.add(Const.RECORD, getRecordAsJsonElement(record, valueType)); + } - public void addRecordList(List recordList, ValueType valueType) throws ClassCastException { + public void addRecordList(List recordList, ValueType valueType) throws ClassCastException { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Record record : recordList) { - jsa.add(getRecordAsJsonElement(record, valueType)); - } - jsonObject.add(Const.RECORDS, jsa); - } + for (Record record : recordList) { + jsa.add(getRecordAsJsonElement(record, valueType)); + } + jsonObject.add(Const.RECORDS, jsa); + } - public void addChannelRecordList(List channels) throws ClassCastException { + public void addChannelRecordList(List channels) throws ClassCastException { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Channel channel : channels) { - jsa.add(channelRecordToJson(channel)); - } - jsonObject.add(Const.RECORDS, jsa); - } + for (Channel channel : channels) { + jsa.add(channelRecordToJson(channel)); + } + jsonObject.add(Const.RECORDS, jsa); + } - public void addDeviceState(DeviceState deviceState) { + public void addDeviceState(DeviceState deviceState) { - jsonObject.addProperty(Const.STATE, deviceState.name()); - } + jsonObject.addProperty(Const.STATE, deviceState.name()); + } - public void addBoolean(String propertyName, boolean value) { + public void addBoolean(String propertyName, boolean value) { - jsonObject.addProperty(propertyName, value); - } + jsonObject.addProperty(propertyName, value); + } - public void addStringList(String propertyName, List stringList) { + public void addStringList(String propertyName, List stringList) { - jsonObject.add(propertyName, gson.toJsonTree(stringList).getAsJsonArray()); - } + jsonObject.add(propertyName, gson.toJsonTree(stringList).getAsJsonArray()); + } - public void addDriverList(List driverConfigList) { + public void addDriverList(List driverConfigList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (DriverConfig driverConfig : driverConfigList) { - jsa.add(gson.toJsonTree(driverConfig.getId())); - } - jsonObject.add(Const.DRIVERS, jsa); - } + for (DriverConfig driverConfig : driverConfigList) { + jsa.add(gson.toJsonTree(driverConfig.getId())); + } + jsonObject.add(Const.DRIVERS, jsa); + } - public void addDeviceList(List deviceConfigList) { + public void addDeviceList(List deviceConfigList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (DeviceConfig deviceConfig : deviceConfigList) { - jsa.add(gson.toJsonTree(deviceConfig.getId())); - } - jsonObject.add(Const.DEVICES, jsa); - } + for (DeviceConfig deviceConfig : deviceConfigList) { + jsa.add(gson.toJsonTree(deviceConfig.getId())); + } + jsonObject.add(Const.DEVICES, jsa); + } - public void addChannelList(List channelList) { + public void addChannelList(List channelList) { - JsonArray jsa = new JsonArray(); + JsonArray jsa = new JsonArray(); - for (Channel channelConfig : channelList) { - jsa.add(gson.toJsonTree(channelConfig.getId())); - } - jsonObject.add(Const.CHANNELS, jsa); - } + for (Channel channelConfig : channelList) { + jsa.add(gson.toJsonTree(channelConfig.getId())); + } + jsonObject.add(Const.CHANNELS, jsa); + } - public void addDriverConfig(DriverConfig config) { + public void addDriverConfig(DriverConfig config) { - RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject()); - } + RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject()); + } - public void addDeviceConfig(DeviceConfig config) { + public void addDeviceConfig(DeviceConfig config) { - RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject()); - } + RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject()); + } - public void addChannelConfig(ChannelConfig config) { + public void addChannelConfig(ChannelConfig config) { - RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject()); - } + RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject()); + } - public void addDeviceScanInfoList(List deviceScanInfoList) { + public void addDeviceScanInfoList(List deviceScanInfoList) { - JsonArray jsa = new JsonArray(); - for (DeviceScanInfo deviceScanInfo : deviceScanInfoList) { - JsonObject jso = new JsonObject(); - jso.addProperty(Const.ID, deviceScanInfo.getId()); - jso.addProperty(Const.DEVICEADDRESS, deviceScanInfo.getDeviceAddress()); - jso.addProperty(Const.SETTINGS, deviceScanInfo.getSettings()); - jso.addProperty(Const.DESCRIPTION, deviceScanInfo.getDescription()); - jsa.add(jso); - } - jsonObject.add(Const.DEVICES, jsa); - } + JsonArray jsa = new JsonArray(); + for (DeviceScanInfo deviceScanInfo : deviceScanInfoList) { + JsonObject jso = new JsonObject(); + jso.addProperty(Const.ID, deviceScanInfo.getId()); + jso.addProperty(Const.DEVICEADDRESS, deviceScanInfo.getDeviceAddress()); + jso.addProperty(Const.SETTINGS, deviceScanInfo.getSettings()); + jso.addProperty(Const.DESCRIPTION, deviceScanInfo.getDescription()); + jsa.add(jso); + } + jsonObject.add(Const.DEVICES, jsa); + } - public void addChannelScanInfoList(List channelScanInfoList) { - - JsonArray jsa = new JsonArray(); - for (ChannelScanInfo channelScanInfo : channelScanInfoList) { - JsonObject jso = new JsonObject(); - jso.addProperty(Const.CHANNELADDRESS, channelScanInfo.getChannelAddress()); - jso.addProperty(Const.VALUETYPE, channelScanInfo.getValueType().name()); - jso.addProperty(Const.VALUETYPELENGTH, channelScanInfo.getValueTypeLength()); - jso.addProperty(Const.DESCRIPTION, channelScanInfo.getDescription()); - jsa.add(jso); - } - jsonObject.add(Const.CHANNELS, jsa); - } - - public void addRestUserConfig(RestUserConfig restUserConfig) { - - jsonObject.add(Const.CONFIGS, gson.toJsonTree(restUserConfig, RestUserConfig.class).getAsJsonObject()); - } - - public static JsonObject getDriverConfigAsJsonObject(DriverConfig config) { - - RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject(); - } - - public static JsonObject getDeviceConfigAsJsonObject(DeviceConfig config) { - - RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject(); - } - - public static JsonObject getChannelConfigAsJsonObject(ChannelConfig config) { - - RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); - Gson gson = new Gson(); - return gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject(); - } - - private JsonObject channelRecordToJson(Channel channel) throws ClassCastException { - - JsonObject jso = new JsonObject(); - - jso.addProperty(Const.ID, channel.getId()); - jso.add(Const.RECORD, getRecordAsJsonElement(channel.getLatestRecord(), channel.getValueType())); - return jso; - } - - private JsonElement getRecordAsJsonElement(Record record, ValueType valueType) throws ClassCastException { - - return gson.toJsonTree(getRestRecord(record, valueType), RestRecord.class); - } - - private RestRecord getRestRecord(Record rc, ValueType type) throws ClassCastException { - - RestRecord rrc = new RestRecord(); - rrc.setFlag(rc.getFlag()); - rrc.setTimestamp(rc.getTimestamp()); - Value value = rc.getValue(); - - if (rc.getFlag() != Flag.VALID) { - rrc.setValue(null); - } - else { - setRestRecordValue(type, value, rrc); - } - return rrc; - } - - private void setRestRecordValue(ValueType valueType, Value value, RestRecord rrc) throws ClassCastException { - - if (value == null) { - rrc.setValue(null); - } - else { - switch (valueType) { - case FLOAT: - rrc.setValue(value.asFloat()); - break; - case DOUBLE: - rrc.setValue(value.asDouble()); - break; - case SHORT: - rrc.setValue(value.asShort()); - break; - case INTEGER: - rrc.setValue(value.asInt()); - break; - case LONG: - rrc.setValue(value.asLong()); - break; - case BYTE: - rrc.setValue(value.asByte()); - break; - case BOOLEAN: - rrc.setValue(value.asBoolean()); - break; - case BYTE_ARRAY: - rrc.setValue(value.asByteArray()); - break; - case STRING: - rrc.setValue(value.asString()); - break; - default: - rrc.setValue(null); - break; - } - } - } + public void addChannelScanInfoList(List channelScanInfoList) { + + JsonArray jsa = new JsonArray(); + for (ChannelScanInfo channelScanInfo : channelScanInfoList) { + JsonObject jso = new JsonObject(); + jso.addProperty(Const.CHANNELADDRESS, channelScanInfo.getChannelAddress()); + jso.addProperty(Const.VALUETYPE, channelScanInfo.getValueType().name()); + jso.addProperty(Const.VALUETYPELENGTH, channelScanInfo.getValueTypeLength()); + jso.addProperty(Const.DESCRIPTION, channelScanInfo.getDescription()); + jsa.add(jso); + } + jsonObject.add(Const.CHANNELS, jsa); + } + + public void addRestUserConfig(RestUserConfig restUserConfig) { + + jsonObject.add(Const.CONFIGS, gson.toJsonTree(restUserConfig, RestUserConfig.class).getAsJsonObject()); + } + + public static JsonObject getDriverConfigAsJsonObject(DriverConfig config) { + + RestDriverConfig restConfig = RestDriverConfigMapper.getRestDriverConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestDriverConfig.class).getAsJsonObject(); + } + + public static JsonObject getDeviceConfigAsJsonObject(DeviceConfig config) { + + RestDeviceConfig restConfig = RestDeviceConfigMapper.getRestDeviceConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestDeviceConfig.class).getAsJsonObject(); + } + + public static JsonObject getChannelConfigAsJsonObject(ChannelConfig config) { + + RestChannelConfig restConfig = RestChannelConfigMapper.getRestChannelConfig(config); + Gson gson = new Gson(); + return gson.toJsonTree(restConfig, RestChannelConfig.class).getAsJsonObject(); + } + + private JsonObject channelRecordToJson(Channel channel) throws ClassCastException { + + JsonObject jso = new JsonObject(); + + jso.addProperty(Const.ID, channel.getId()); + jso.add(Const.RECORD, getRecordAsJsonElement(channel.getLatestRecord(), channel.getValueType())); + return jso; + } + + private JsonElement getRecordAsJsonElement(Record record, ValueType valueType) throws ClassCastException { + + return gson.toJsonTree(getRestRecord(record, valueType), RestRecord.class); + } + + private RestRecord getRestRecord(Record rc, ValueType type) throws ClassCastException { + + RestRecord rrc = new RestRecord(); + rrc.setFlag(rc.getFlag()); + rrc.setTimestamp(rc.getTimestamp()); + Value value = rc.getValue(); + + if (rc.getFlag() != Flag.VALID) { + rrc.setValue(null); + } else { + setRestRecordValue(type, value, rrc); + } + return rrc; + } + + private void setRestRecordValue(ValueType valueType, Value value, RestRecord rrc) throws ClassCastException { + + if (value == null) { + rrc.setValue(null); + } else { + switch (valueType) { + case FLOAT: + rrc.setValue(value.asFloat()); + break; + case DOUBLE: + rrc.setValue(value.asDouble()); + break; + case SHORT: + rrc.setValue(value.asShort()); + break; + case INTEGER: + rrc.setValue(value.asInt()); + break; + case LONG: + rrc.setValue(value.asLong()); + break; + case BYTE: + rrc.setValue(value.asByte()); + break; + case BOOLEAN: + rrc.setValue(value.asBoolean()); + break; + case BYTE_ARRAY: + rrc.setValue(value.asByteArray()); + break; + case STRING: + rrc.setValue(value.asString()); + break; + default: + rrc.setValue(null); + break; + } + } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java index 1698b073..61edb70c 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/MissingJsonObjectException.java @@ -22,21 +22,21 @@ public class MissingJsonObjectException extends Exception { - /** - * - */ - private static final long serialVersionUID = 3245778161912001429L; - private String message = "Searched JsonObject is missing. "; + /** + * + */ + private static final long serialVersionUID = 3245778161912001429L; + private String message = "Searched JsonObject is missing. "; - public MissingJsonObjectException() { - } + public MissingJsonObjectException() { + } - public MissingJsonObjectException(String message) { - this.message = message; - } + public MissingJsonObjectException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java index 0ae115df..ec8e7d9e 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/exceptions/RestConfigIsNotCorrectException.java @@ -22,23 +22,23 @@ public class RestConfigIsNotCorrectException extends Exception { - /** - * - */ - private static final long serialVersionUID = 8768653196104942337L; + /** + * + */ + private static final long serialVersionUID = 8768653196104942337L; - private String message = "Something was wrong in the json config message. "; + private String message = "Something was wrong in the json config message. "; - public RestConfigIsNotCorrectException() { - } + public RestConfigIsNotCorrectException() { + } - public RestConfigIsNotCorrectException(String message) { - this.message = message; - } + public RestConfigIsNotCorrectException(String message) { + this.message = message; + } - @Override - public String getMessage() { - return message; - } + @Override + public String getMessage() { + return message; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java index a80e174f..0d9a6a8b 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannel.java @@ -25,32 +25,32 @@ public class RestChannel { - private String id; - private ValueType type; - private Record record; + private String id; + private ValueType type; + private Record record; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public ValueType getType() { - return type; - } + public ValueType getType() { + return type; + } - public void setType(ValueType type) { - this.type = type; - } + public void setType(ValueType type) { + this.type = type; + } - public Record getRecord() { - return record; - } + public Record getRecord() { + return record; + } - public void setRecord(Record record) { - this.record = record; - } + public void setRecord(Record record) { + this.record = record; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java index b2ba5bc3..f4a0fd0d 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfig.java @@ -20,155 +20,155 @@ */ package org.openmuc.framework.lib.json.restObjects; -import java.util.List; - import org.openmuc.framework.config.ServerMapping; import org.openmuc.framework.data.ValueType; +import java.util.List; + public class RestChannelConfig { - private String id = null; - private String channelAddress = null; - private String description = null; - private String unit = null; - private ValueType valueType = null; - private Integer valueTypeLength = null; - private Double scalingFactor = null; - private Double valueOffset = null; - private Boolean listening = null; - private Integer samplingInterval = null; - private Integer samplingTimeOffset = null; - private String samplingGroup = null; - private Integer loggingInterval = null; - private Integer loggingTimeOffset = null; - private Boolean disabled = null; - private List serverMappings = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getChannelAddress() { - return channelAddress; - } - - public void setChannelAddress(String channelAddress) { - this.channelAddress = channelAddress; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public ValueType getValueType() { - return valueType; - } - - public void setValueType(ValueType valueType) { - this.valueType = valueType; - } - - public Integer getValueTypeLength() { - return valueTypeLength; - } - - public void setValueTypeLength(Integer valueTypeLength) { - this.valueTypeLength = valueTypeLength; - } - - public Double getScalingFactor() { - return scalingFactor; - } - - public void setScalingFactor(Double scalingFactor) { - this.scalingFactor = scalingFactor; - } - - public Double getValueOffset() { - return valueOffset; - } - - public void setValueOffset(Double valueOffset) { - this.valueOffset = valueOffset; - } - - public Boolean isListening() { - return listening; - } - - public void setListening(Boolean listening) { - this.listening = listening; - } - - public Integer getSamplingInterval() { - return samplingInterval; - } - - public void setSamplingInterval(Integer samplingInterval) { - this.samplingInterval = samplingInterval; - } - - public Integer getSamplingTimeOffset() { - return samplingTimeOffset; - } - - public void setSamplingTimeOffset(Integer samplingTimeOffset) { - this.samplingTimeOffset = samplingTimeOffset; - } - - public String getSamplingGroup() { - return samplingGroup; - } - - public void setSamplingGroup(String samplingGroup) { - this.samplingGroup = samplingGroup; - } - - public Integer getLoggingInterval() { - return loggingInterval; - } + private String id = null; + private String channelAddress = null; + private String description = null; + private String unit = null; + private ValueType valueType = null; + private Integer valueTypeLength = null; + private Double scalingFactor = null; + private Double valueOffset = null; + private Boolean listening = null; + private Integer samplingInterval = null; + private Integer samplingTimeOffset = null; + private String samplingGroup = null; + private Integer loggingInterval = null; + private Integer loggingTimeOffset = null; + private Boolean disabled = null; + private List serverMappings = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getChannelAddress() { + return channelAddress; + } + + public void setChannelAddress(String channelAddress) { + this.channelAddress = channelAddress; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public ValueType getValueType() { + return valueType; + } + + public void setValueType(ValueType valueType) { + this.valueType = valueType; + } + + public Integer getValueTypeLength() { + return valueTypeLength; + } + + public void setValueTypeLength(Integer valueTypeLength) { + this.valueTypeLength = valueTypeLength; + } + + public Double getScalingFactor() { + return scalingFactor; + } + + public void setScalingFactor(Double scalingFactor) { + this.scalingFactor = scalingFactor; + } + + public Double getValueOffset() { + return valueOffset; + } + + public void setValueOffset(Double valueOffset) { + this.valueOffset = valueOffset; + } + + public Boolean isListening() { + return listening; + } + + public void setListening(Boolean listening) { + this.listening = listening; + } + + public Integer getSamplingInterval() { + return samplingInterval; + } + + public void setSamplingInterval(Integer samplingInterval) { + this.samplingInterval = samplingInterval; + } + + public Integer getSamplingTimeOffset() { + return samplingTimeOffset; + } + + public void setSamplingTimeOffset(Integer samplingTimeOffset) { + this.samplingTimeOffset = samplingTimeOffset; + } + + public String getSamplingGroup() { + return samplingGroup; + } + + public void setSamplingGroup(String samplingGroup) { + this.samplingGroup = samplingGroup; + } + + public Integer getLoggingInterval() { + return loggingInterval; + } - public void setLoggingInterval(Integer loggingInterval) { - this.loggingInterval = loggingInterval; - } + public void setLoggingInterval(Integer loggingInterval) { + this.loggingInterval = loggingInterval; + } - public Integer getLoggingTimeOffset() { - return loggingTimeOffset; - } + public Integer getLoggingTimeOffset() { + return loggingTimeOffset; + } - public void setLoggingTimeOffset(Integer loggingTimeOffset) { - this.loggingTimeOffset = loggingTimeOffset; - } + public void setLoggingTimeOffset(Integer loggingTimeOffset) { + this.loggingTimeOffset = loggingTimeOffset; + } - public Boolean isDisabled() { - return disabled; - } + public Boolean isDisabled() { + return disabled; + } - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } - public List getServerMappings() { - return serverMappings; - } + public List getServerMappings() { + return serverMappings; + } - public void setServerMappings(List serverMappings) { - this.serverMappings = serverMappings; - } + public void setServerMappings(List serverMappings) { + this.serverMappings = serverMappings; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java index 8d698f57..b643ea2a 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestChannelConfigMapper.java @@ -26,59 +26,57 @@ public class RestChannelConfigMapper { - public static RestChannelConfig getRestChannelConfig(ChannelConfig cc) { + public static RestChannelConfig getRestChannelConfig(ChannelConfig cc) { - RestChannelConfig rcc = new RestChannelConfig(); - rcc.setChannelAddress(cc.getChannelAddress()); - rcc.setDescription(cc.getDescription()); - rcc.setDisabled(cc.isDisabled()); - rcc.setId(cc.getId()); - rcc.setListening(cc.isListening()); - rcc.setLoggingInterval(cc.getLoggingInterval()); - rcc.setLoggingTimeOffset(cc.getLoggingTimeOffset()); - rcc.setSamplingGroup(cc.getSamplingGroup()); - rcc.setSamplingInterval(cc.getSamplingInterval()); - rcc.setSamplingTimeOffset(cc.getSamplingTimeOffset()); - rcc.setScalingFactor(cc.getScalingFactor()); - // rcc.setServerMappings(cc.getServerMappings()); - rcc.setUnit(cc.getUnit()); - rcc.setValueOffset(cc.getValueOffset()); - rcc.setValueType(cc.getValueType()); - rcc.setValueTypeLength(cc.getValueTypeLength()); - return rcc; - } + RestChannelConfig rcc = new RestChannelConfig(); + rcc.setChannelAddress(cc.getChannelAddress()); + rcc.setDescription(cc.getDescription()); + rcc.setDisabled(cc.isDisabled()); + rcc.setId(cc.getId()); + rcc.setListening(cc.isListening()); + rcc.setLoggingInterval(cc.getLoggingInterval()); + rcc.setLoggingTimeOffset(cc.getLoggingTimeOffset()); + rcc.setSamplingGroup(cc.getSamplingGroup()); + rcc.setSamplingInterval(cc.getSamplingInterval()); + rcc.setSamplingTimeOffset(cc.getSamplingTimeOffset()); + rcc.setScalingFactor(cc.getScalingFactor()); + // rcc.setServerMappings(cc.getServerMappings()); + rcc.setUnit(cc.getUnit()); + rcc.setValueOffset(cc.getValueOffset()); + rcc.setValueType(cc.getValueType()); + rcc.setValueTypeLength(cc.getValueTypeLength()); + return rcc; + } - public static void setChannelConfig(ChannelConfig cc, RestChannelConfig rcc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setChannelConfig(ChannelConfig cc, RestChannelConfig rcc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (cc == null) { - throw new RestConfigIsNotCorrectException("ChannelConfig is null!"); - } - else { - if (rcc != null) { - if (rcc.getId() != null && !rcc.getId().equals("") && !idFromUrl.equals(rcc.getId())) { - cc.setId(rcc.getId()); - } - cc.setChannelAddress(rcc.getChannelAddress()); - cc.setDescription(rcc.getDescription()); - cc.setDisabled(rcc.isDisabled()); - cc.setListening(rcc.isListening()); - cc.setLoggingInterval(rcc.getLoggingInterval()); - cc.setLoggingTimeOffset(rcc.getLoggingTimeOffset()); - cc.setSamplingGroup(rcc.getSamplingGroup()); - cc.setSamplingInterval(rcc.getSamplingInterval()); - cc.setSamplingTimeOffset(rcc.getSamplingTimeOffset()); - cc.setScalingFactor(rcc.getScalingFactor()); - // cc.setServerMappings(rcc.getServerMappings()); - cc.setUnit(rcc.getUnit()); - cc.setValueOffset(rcc.getValueOffset()); - cc.setValueType(rcc.getValueType()); - cc.setValueTypeLength(rcc.getValueTypeLength()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } - } + if (cc == null) { + throw new RestConfigIsNotCorrectException("ChannelConfig is null!"); + } else { + if (rcc != null) { + if (rcc.getId() != null && !rcc.getId().equals("") && !idFromUrl.equals(rcc.getId())) { + cc.setId(rcc.getId()); + } + cc.setChannelAddress(rcc.getChannelAddress()); + cc.setDescription(rcc.getDescription()); + cc.setDisabled(rcc.isDisabled()); + cc.setListening(rcc.isListening()); + cc.setLoggingInterval(rcc.getLoggingInterval()); + cc.setLoggingTimeOffset(rcc.getLoggingTimeOffset()); + cc.setSamplingGroup(rcc.getSamplingGroup()); + cc.setSamplingInterval(rcc.getSamplingInterval()); + cc.setSamplingTimeOffset(rcc.getSamplingTimeOffset()); + cc.setScalingFactor(rcc.getScalingFactor()); + // cc.setServerMappings(rcc.getServerMappings()); + cc.setUnit(rcc.getUnit()); + cc.setValueOffset(rcc.getValueOffset()); + cc.setValueType(rcc.getValueType()); + cc.setValueTypeLength(rcc.getValueTypeLength()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java index 65b3e304..14977147 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfig.java @@ -22,70 +22,70 @@ public class RestDeviceConfig { - private String id; - private String description = null; - private String deviceAddress = null; - private String settings = null; - private Integer samplingTimeout = null; - private Integer connectRetryInterval = null; - private Boolean disabled = null; - - // Device device = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDeviceAddress() { - return deviceAddress; - } - - public void setDeviceAddress(String deviceAddress) { - this.deviceAddress = deviceAddress; - } - - public String getSettings() { - return settings; - } - - public void setSettings(String settings) { - this.settings = settings; - } - - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - public void setSamplingTimeout(Integer samplingTimeout) { - this.samplingTimeout = samplingTimeout; - } - - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - public void setConnectRetryInterval(Integer connectRetryInterval) { - this.connectRetryInterval = connectRetryInterval; - } - - public Boolean getDisabled() { - return disabled; - } - - public void isDisabled(Boolean disabled) { - this.disabled = disabled; - } + private String id; + private String description = null; + private String deviceAddress = null; + private String settings = null; + private Integer samplingTimeout = null; + private Integer connectRetryInterval = null; + private Boolean disabled = null; + + // Device device = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDeviceAddress() { + return deviceAddress; + } + + public void setDeviceAddress(String deviceAddress) { + this.deviceAddress = deviceAddress; + } + + public String getSettings() { + return settings; + } + + public void setSettings(String settings) { + this.settings = settings; + } + + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + public void setSamplingTimeout(Integer samplingTimeout) { + this.samplingTimeout = samplingTimeout; + } + + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + public void setConnectRetryInterval(Integer connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + } + + public Boolean getDisabled() { + return disabled; + } + + public void isDisabled(Boolean disabled) { + this.disabled = disabled; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java index e205f00c..d7668f3f 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDeviceConfigMapper.java @@ -26,42 +26,40 @@ public class RestDeviceConfigMapper { - public static RestDeviceConfig getRestDeviceConfig(DeviceConfig dc) { + public static RestDeviceConfig getRestDeviceConfig(DeviceConfig dc) { - RestDeviceConfig rdc = new RestDeviceConfig(); - rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); - rdc.setDescription(dc.getDescription()); - rdc.setDeviceAddress(dc.getDeviceAddress()); - rdc.isDisabled(dc.isDisabled()); - rdc.setId(dc.getId()); - rdc.setSamplingTimeout(dc.getSamplingTimeout()); - rdc.setSettings(dc.getSettings()); - return rdc; - } + RestDeviceConfig rdc = new RestDeviceConfig(); + rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); + rdc.setDescription(dc.getDescription()); + rdc.setDeviceAddress(dc.getDeviceAddress()); + rdc.isDisabled(dc.isDisabled()); + rdc.setId(dc.getId()); + rdc.setSamplingTimeout(dc.getSamplingTimeout()); + rdc.setSettings(dc.getSettings()); + return rdc; + } - public static void setDeviceConfig(DeviceConfig dc, RestDeviceConfig rdc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setDeviceConfig(DeviceConfig dc, RestDeviceConfig rdc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (dc == null) { - throw new RestConfigIsNotCorrectException("DriverConfig is null!"); - } - else { + if (dc == null) { + throw new RestConfigIsNotCorrectException("DriverConfig is null!"); + } else { - if (rdc != null) { - if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { - dc.setId(rdc.getId()); - } - dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); - dc.setDescription(rdc.getDescription()); - dc.setDeviceAddress(rdc.getDeviceAddress()); - dc.setDisabled(rdc.getDisabled()); - dc.setSamplingTimeout(rdc.getSamplingTimeout()); - dc.setSettings(rdc.getSettings()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } + if (rdc != null) { + if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { + dc.setId(rdc.getId()); + } + dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); + dc.setDescription(rdc.getDescription()); + dc.setDeviceAddress(rdc.getDeviceAddress()); + dc.setDisabled(rdc.getDisabled()); + dc.setSamplingTimeout(rdc.getSamplingTimeout()); + dc.setSettings(rdc.getSettings()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } - } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java index d2b03ef0..1e77ebe0 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfig.java @@ -22,40 +22,40 @@ public class RestDriverConfig { - private String id = ""; - private Integer samplingTimeout = null; - private Integer connectRetryInterval = null; - private Boolean disabled = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Integer getSamplingTimeout() { - return samplingTimeout; - } - - public void setSamplingTimeout(Integer samplingTimeout) { - this.samplingTimeout = samplingTimeout; - } - - public Integer getConnectRetryInterval() { - return connectRetryInterval; - } - - public void setConnectRetryInterval(Integer connectRetryInterval) { - this.connectRetryInterval = connectRetryInterval; - } - - public Boolean isDisabled() { - return disabled; - } - - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } + private String id = ""; + private Integer samplingTimeout = null; + private Integer connectRetryInterval = null; + private Boolean disabled = null; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Integer getSamplingTimeout() { + return samplingTimeout; + } + + public void setSamplingTimeout(Integer samplingTimeout) { + this.samplingTimeout = samplingTimeout; + } + + public Integer getConnectRetryInterval() { + return connectRetryInterval; + } + + public void setConnectRetryInterval(Integer connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + } + + public Boolean isDisabled() { + return disabled; + } + + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java index 3544d767..fc80fdff 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestDriverConfigMapper.java @@ -26,35 +26,33 @@ public class RestDriverConfigMapper { - public static RestDriverConfig getRestDriverConfig(DriverConfig dc) { + public static RestDriverConfig getRestDriverConfig(DriverConfig dc) { - RestDriverConfig rdc = new RestDriverConfig(); - rdc.setId(dc.getId()); - rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); - rdc.setDisabled(dc.isDisabled()); - rdc.setSamplingTimeout(dc.getSamplingTimeout()); - return rdc; - } + RestDriverConfig rdc = new RestDriverConfig(); + rdc.setId(dc.getId()); + rdc.setConnectRetryInterval(dc.getConnectRetryInterval()); + rdc.setDisabled(dc.isDisabled()); + rdc.setSamplingTimeout(dc.getSamplingTimeout()); + return rdc; + } - public static void setDriverConfig(DriverConfig dc, RestDriverConfig rdc, String idFromUrl) - throws IdCollisionException, RestConfigIsNotCorrectException { + public static void setDriverConfig(DriverConfig dc, RestDriverConfig rdc, String idFromUrl) throws IdCollisionException, + RestConfigIsNotCorrectException { - if (dc == null) { - throw new RestConfigIsNotCorrectException("DriverConfig is null!"); - } - else { - if (rdc != null) { - if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { - dc.setId(rdc.getId()); - } - dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); - dc.setDisabled(rdc.isDisabled()); - dc.setSamplingTimeout(rdc.getSamplingTimeout()); - } - else { - throw new RestConfigIsNotCorrectException(); - } - } + if (dc == null) { + throw new RestConfigIsNotCorrectException("DriverConfig is null!"); + } else { + if (rdc != null) { + if (rdc.getId() != null && !rdc.getId().equals("") && !idFromUrl.equals(rdc.getId())) { + dc.setId(rdc.getId()); + } + dc.setConnectRetryInterval(rdc.getConnectRetryInterval()); + dc.setDisabled(rdc.isDisabled()); + dc.setSamplingTimeout(rdc.getSamplingTimeout()); + } else { + throw new RestConfigIsNotCorrectException(); + } + } - } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java index 6d89c92f..4809c46f 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestRecord.java @@ -24,32 +24,32 @@ public class RestRecord { - private Long timestamp; - private Flag flag; - private Object value; + private Long timestamp; + private Flag flag; + private Object value; - public Long getTimestamp() { - return timestamp; - } + public Long getTimestamp() { + return timestamp; + } - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } - public Flag getFlag() { - return flag; - } + public Flag getFlag() { + return flag; + } - public void setFlag(Flag flag) { - this.flag = flag; - } + public void setFlag(Flag flag) { + this.flag = flag; + } - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestUserConfig.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestUserConfig.java index a5e8d32f..fc4524cd 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestUserConfig.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestUserConfig.java @@ -22,50 +22,50 @@ public class RestUserConfig { - private String id; - private String password; - private String oldPassword; - private String[] groups; - private String description; + private String id; + private String password; + private String oldPassword; + private String[] groups; + private String description; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - public String getOldPassword() { - return oldPassword; - } + public String getOldPassword() { + return oldPassword; + } - public void setOldPassword(String oldPassword) { - this.oldPassword = oldPassword; - } + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } - public String[] getGroups() { - return groups; - } + public String[] getGroups() { + return groups; + } - public void setGroups(String[] groups) { - this.groups = groups; - } + public void setGroups(String[] groups) { + this.groups = groups; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java index 781b0d85..9c491389 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/lib/json/restObjects/RestValue.java @@ -22,14 +22,14 @@ public class RestValue { - private Object value; + private Object value; - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/RestServer.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/RestServer.java index ad722501..9bf77c48 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/RestServer.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/RestServer.java @@ -35,98 +35,97 @@ public final class RestServer { - private final static Logger logger = LoggerFactory.getLogger(RestServer.class); + private final static Logger logger = LoggerFactory.getLogger(RestServer.class); - private static DataAccessService dataAccessService; - private static AuthenticationService authenticationService; - private static ConfigService configService; - private static HttpService httpService; + private static DataAccessService dataAccessService; + private static AuthenticationService authenticationService; + private static ConfigService configService; + private static HttpService httpService; - private final ChannelResourceServlet chRServlet = new ChannelResourceServlet(); - private final DeviceResourceServlet devRServlet = new DeviceResourceServlet(); - private final DriverResourceServlet drvRServlet = new DriverResourceServlet(); - private final UserServlet userServlet = new UserServlet(); + private final ChannelResourceServlet chRServlet = new ChannelResourceServlet(); + private final DeviceResourceServlet devRServlet = new DeviceResourceServlet(); + private final DriverResourceServlet drvRServlet = new DriverResourceServlet(); + private final UserServlet userServlet = new UserServlet(); - // private final ControlsServlet controlsServlet = new ControlsServlet(); + // private final ControlsServlet controlsServlet = new ControlsServlet(); - protected void activate(ComponentContext context) throws Exception { + protected void activate(ComponentContext context) throws Exception { - logger.info("Activating REST Server"); + logger.info("Activating REST Server"); - SecurityHandler securityHandler = new SecurityHandler(context.getBundleContext().getBundle(), - authenticationService); + SecurityHandler securityHandler = new SecurityHandler(context.getBundleContext().getBundle(), authenticationService); - httpService.registerServlet(Const.ALIAS_CHANNELS, chRServlet, null, securityHandler); - httpService.registerServlet(Const.ALIAS_DEVICES, devRServlet, null, securityHandler); - httpService.registerServlet(Const.ALIAS_DRIVERS, drvRServlet, null, securityHandler); - httpService.registerServlet(Const.ALIAS_USERS, userServlet, null, securityHandler); - // httpService.registerServlet(Const.ALIAS_CONTROLS, controlsServlet, null, securityHandler); - } + httpService.registerServlet(Const.ALIAS_CHANNELS, chRServlet, null, securityHandler); + httpService.registerServlet(Const.ALIAS_DEVICES, devRServlet, null, securityHandler); + httpService.registerServlet(Const.ALIAS_DRIVERS, drvRServlet, null, securityHandler); + httpService.registerServlet(Const.ALIAS_USERS, userServlet, null, securityHandler); + // httpService.registerServlet(Const.ALIAS_CONTROLS, controlsServlet, null, securityHandler); + } - protected void deactivate(ComponentContext context) { + protected void deactivate(ComponentContext context) { - logger.info("Deactivating REST Server"); + logger.info("Deactivating REST Server"); - httpService.unregister(Const.ALIAS_CHANNELS); - httpService.unregister(Const.ALIAS_DEVICES); - httpService.unregister(Const.ALIAS_DRIVERS); - httpService.unregister(Const.ALIAS_USERS); - // httpService.unregister(Const.ALIAS_CONTROLS); - } + httpService.unregister(Const.ALIAS_CHANNELS); + httpService.unregister(Const.ALIAS_DEVICES); + httpService.unregister(Const.ALIAS_DRIVERS); + httpService.unregister(Const.ALIAS_USERS); + // httpService.unregister(Const.ALIAS_CONTROLS); + } - protected void setConfigService(ConfigService configService) { + protected void setConfigService(ConfigService configService) { - RestServer.configService = configService; - } + RestServer.configService = configService; + } - protected void unsetConfigService(ConfigService configService) { + protected void unsetConfigService(ConfigService configService) { - RestServer.configService = null; - } + RestServer.configService = null; + } - protected void setAuthenticationService(AuthenticationService authenticationService) { + protected void setAuthenticationService(AuthenticationService authenticationService) { - RestServer.authenticationService = authenticationService; - } + RestServer.authenticationService = authenticationService; + } - protected void unsetAuthenticationService(AuthenticationService authenticationService) { + protected void unsetAuthenticationService(AuthenticationService authenticationService) { - RestServer.authenticationService = null; - } + RestServer.authenticationService = null; + } - protected void setHttpService(HttpService httpService) { + protected void setHttpService(HttpService httpService) { - RestServer.httpService = httpService; - } + RestServer.httpService = httpService; + } - protected void unsetHttpService(HttpService httpService) { + protected void unsetHttpService(HttpService httpService) { - RestServer.httpService = null; - } + RestServer.httpService = null; + } - protected void setDataAccessService(DataAccessService dataAccessService) { + protected void setDataAccessService(DataAccessService dataAccessService) { - RestServer.dataAccessService = dataAccessService; - } + RestServer.dataAccessService = dataAccessService; + } - protected void unsetDataAccessService(DataAccessService dataAccessService) { + protected void unsetDataAccessService(DataAccessService dataAccessService) { - RestServer.dataAccessService = null; - } + RestServer.dataAccessService = null; + } - public static DataAccessService getDataAccessService() { + public static DataAccessService getDataAccessService() { - return RestServer.dataAccessService; - } + return RestServer.dataAccessService; + } - public static ConfigService getConfigService() { + public static ConfigService getConfigService() { - return RestServer.configService; - } + return RestServer.configService; + } - public static AuthenticationService getAuthenticationService() { + public static AuthenticationService getAuthenticationService() { - return RestServer.authenticationService; - } + return RestServer.authenticationService; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/SecurityHandler.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/SecurityHandler.java index 9f569e32..b3feff08 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/SecurityHandler.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/SecurityHandler.java @@ -20,60 +20,59 @@ */ package org.openmuc.framework.server.restws; -import java.io.IOException; -import java.net.URL; +import org.openmuc.framework.authentication.AuthenticationService; +import org.osgi.framework.Bundle; +import org.osgi.service.http.HttpContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.DatatypeConverter; - -import org.openmuc.framework.authentication.AuthenticationService; -import org.osgi.framework.Bundle; -import org.osgi.service.http.HttpContext; +import java.io.IOException; +import java.net.URL; public class SecurityHandler implements HttpContext { - Bundle contextBundle; - AuthenticationService authService; + Bundle contextBundle; + AuthenticationService authService; - public SecurityHandler(Bundle contextBundle, AuthenticationService authService) { - this.contextBundle = contextBundle; - this.authService = authService; - } + public SecurityHandler(Bundle contextBundle, AuthenticationService authService) { + this.contextBundle = contextBundle; + this.authService = authService; + } - @Override - public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { - if (request.getScheme().equals("https")) { - if (!authenticated(request)) { - response.setHeader("WWW-Authenticate", "BASIC realm=\"private area\""); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return false; - } - } - return true; - } + @Override + public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { + if (request.getScheme().equals("https")) { + if (!authenticated(request)) { + response.setHeader("WWW-Authenticate", "BASIC realm=\"private area\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + return false; + } + } + return true; + } - private boolean authenticated(HttpServletRequest request) { - String authzHeader = request.getHeader("Authorization"); - if (authzHeader == null) { - return false; - } - String usernameAndPassword = new String(DatatypeConverter.parseBase64Binary(authzHeader.substring(6))); + private boolean authenticated(HttpServletRequest request) { + String authzHeader = request.getHeader("Authorization"); + if (authzHeader == null) { + return false; + } + String usernameAndPassword = new String(DatatypeConverter.parseBase64Binary(authzHeader.substring(6))); - int userNameIndex = usernameAndPassword.indexOf(":"); - String username = usernameAndPassword.substring(0, userNameIndex); - String password = usernameAndPassword.substring(userNameIndex + 1); - return authService.login(username, password); - } + int userNameIndex = usernameAndPassword.indexOf(":"); + String username = usernameAndPassword.substring(0, userNameIndex); + String password = usernameAndPassword.substring(userNameIndex + 1); + return authService.login(username, password); + } - @Override - public URL getResource(String name) { - return contextBundle.getResource(name); - } + @Override + public URL getResource(String name) { + return contextBundle.getResource(name); + } - @Override - public String getMimeType(String name) { - return null; - } + @Override + public String getMimeType(String name) { + return null; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ChannelResourceServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ChannelResourceServlet.java index 89fc4aa9..6071b81d 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ChannelResourceServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ChannelResourceServlet.java @@ -20,20 +20,10 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ConfigService; -import org.openmuc.framework.config.ConfigWriteException; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.RootConfig; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.openmuc.framework.config.*; import org.openmuc.framework.data.Flag; import org.openmuc.framework.data.Record; import org.openmuc.framework.data.Value; @@ -48,424 +38,391 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class ChannelResourceServlet extends GenericServlet { - private static final long serialVersionUID = -702876016040151438L; - private final static Logger logger = LoggerFactory.getLogger(ChannelResourceServlet.class); - - private DataAccessService dataAccess; - private ConfigService configService; - private RootConfig rootConfig; - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String channelID, fromParameter, untilParameter, configField; - String pathInfo = pathAndQueryString[0]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - - response.setStatus(HttpServletResponse.SC_OK); - - ToJson json = new ToJson(); - - if (pathInfo.equals("/")) { - doGetAllChannels(json); - } - else { - channelID = pathInfoArray[0].replace("/", ""); - if (pathInfoArray.length == 1) { - doGetSpecificChannel(json, channelID, response); - } - else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - doGetConfigs(json, channelID, response); - } - else if (pathInfoArray.length == 3 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - configField = pathInfoArray[2]; - doGetConfigField(json, channelID, configField, response); - } - else if (pathInfoArray.length == 2 && pathInfoArray[1].startsWith(Const.HISTORY)) { - fromParameter = request.getParameter("from"); - untilParameter = request.getParameter("until"); - doGetHistory(json, channelID, fromParameter, untilParameter, response); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - sendJson(json, response); - } - } - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String channelID = pathInfoArray[0].replace("/", ""); - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfoArray.length == 1) { - setAndWriteChannelConfig(channelID, response, json, false); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - - } - } - - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String channelID = pathInfoArray[0].replace("/", ""); - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfoArray.length < 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - else { - ChannelConfig channelConfig = rootConfig.getChannel(channelID); - - if (channelConfig != null) { - - if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - setAndWriteChannelConfig(channelID, response, json, true); - } - else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.LATESTRECORD)) { - doSetRecord(channelID, response, json); - } - else if (pathInfoArray.length == 1) { - doWriteChannel(channelID, response, json); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested channel is not available.", " Channel = ", channelID); - } - } - } - } - - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[0]; - String channelId; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - ChannelConfig channelConfig; - - channelId = pathInfoArray[0].replace("/", ""); - channelConfig = rootConfig.getChannel(channelId); - - if (pathInfoArray.length != 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available", " Path Info = ", request.getPathInfo()); - } - else if (channelConfig == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Channel \"" - + channelId + "\" does not exist."); - } - else { - try { - channelConfig.delete(); - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - - if (rootConfig.getDriver(channelId) == null) { - response.setStatus(HttpServletResponse.SC_OK); - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - logger, "Not able to delete channel ", channelId); - } - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to write into config."); - e.printStackTrace(); - } - } - } - } - - private void doGetConfigField(ToJson json, String channelID, String configField, HttpServletResponse response) - throws IOException { - - ChannelConfig channelConfig = rootConfig.getChannel(channelID); - - if (channelConfig != null) { - JsonObject jsoConfigAll = ToJson.getChannelConfigAsJsonObject(channelConfig); - if (jsoConfigAll == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Could not find JSON object \"configs\""); - } - else { - JsonElement jseConfigField = jsoConfigAll.get(configField); - - if (jseConfigField == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest config field is not available.", " configField = ", configField); - } - else { - JsonObject jso = new JsonObject(); - jso.add(configField, jseConfigField); - json.addJsonObject(Const.CONFIGS, jso); - } - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest channel is not available.", " ChannelID = ", channelID); - } - } - - private void doGetConfigs(ToJson json, String channelID, HttpServletResponse response) throws IOException { - - ChannelConfig channelConfig = rootConfig.getChannel(channelID); - - if (channelConfig != null) { - json.addChannelConfig(channelConfig); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest channel is not available.", " ChannelID = ", channelID); - } - } - - private void doGetHistory(ToJson json, String channelID, String fromParameter, String untilParameter, - HttpServletResponse response) { - long fromTimeStamp = 0, untilTimeStamp = 0; - - List channelIDs = dataAccess.getAllIds(); - List records = null; - - if (channelIDs.contains(channelID)) { - Channel channel = dataAccess.getChannel(channelID); - - try { - fromTimeStamp = Long.parseLong(fromParameter); - untilTimeStamp = Long.parseLong(untilParameter); - } catch (NumberFormatException ex) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_BAD_REQUEST, logger, - "From/To value is not a long number."); - } - - try { - records = channel.getLoggedRecords(fromTimeStamp, untilTimeStamp); - } catch (DataLoggerNotAvailableException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - e.getMessage()); - } catch (IOException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); - } - json.addRecordList(records, channel.getValueType()); - } - } - - private boolean setAndWriteChannelConfig(String channelID, HttpServletResponse response, FromJson json, - boolean isHTTPPut) { - - boolean ok = false; - - try { - if (isHTTPPut) { - ok = setAndWriteHttpPutChannelConfig(channelID, response, json); - } - else { - ok = setAndWriteHttpPostChannelConfig(channelID, response, json); - } - } catch (JsonSyntaxException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, - "JSON syntax is wrong."); - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Could not write channel \"", channelID, "\"."); - e.printStackTrace(); - } catch (RestConfigIsNotCorrectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "Not correct formed channel config json.", " JSON = ", json.getJsonObject().toString()); - } catch (Error e) { - ServletLib - .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, e.getMessage()); - } catch (MissingJsonObjectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); - } catch (IllegalStateException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); - } - return ok; - } - - private boolean setAndWriteHttpPutChannelConfig(String channelID, HttpServletResponse response, FromJson json) - throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, - MissingJsonObjectException, IllegalStateException { - - boolean ok = false; - - ChannelConfig channelConfig = rootConfig.getChannel(channelID); - if (channelConfig != null) { - try { - json.setChannelConfig(channelConfig, channelID); - - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - } catch (IdCollisionException e) { - - } - response.setStatus(HttpServletResponse.SC_OK); - ok = true; - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to access to channel ", channelID); - } - return ok; - } - - private boolean setAndWriteHttpPostChannelConfig(String channelID, HttpServletResponse response, FromJson json) - throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, Error, - MissingJsonObjectException, IllegalStateException { - - boolean ok = false; - DeviceConfig deviceConfig; - - ChannelConfig channelConfig = rootConfig.getChannel(channelID); - - JsonObject jso = json.getJsonObject(); - String deviceID = jso.get(Const.DEVICE).getAsString(); - - if (deviceID != null) { - deviceConfig = rootConfig.getDevice(deviceID); - } - else { - throw new Error("No device ID in JSON"); - } - - if (deviceConfig == null) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Device does not exists: ", deviceID); - } - else if (channelConfig != null) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Channel already exists: ", channelID); - } - else { - try { - channelConfig = deviceConfig.addChannel(channelID); - json.setChannelConfig(channelConfig, channelID); - - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - } catch (IdCollisionException e) { - } - response.setStatus(HttpServletResponse.SC_OK); - ok = true; - } - return ok; - } - - private void doGetSpecificChannel(ToJson json, String chId, HttpServletResponse response) throws IOException { - - Channel channel = dataAccess.getChannel(chId); - if (channel != null) { - Record record = channel.getLatestRecord(); - json.addRecord(record, channel.getValueType()); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest channel is not available, ChannelID = " + chId); - } - } - - private void doGetAllChannels(ToJson json) { - - List ids = dataAccess.getAllIds(); - List channels = new ArrayList(ids.size()); - - for (String id : ids) { - channels.add(dataAccess.getChannel(id)); - - } - json.addChannelRecordList(channels); - } - - private void doSetRecord(String channelID, HttpServletResponse response, FromJson json) throws ClassCastException { - - Channel channel = dataAccess.getChannel(channelID); - Record record = json.getRecord(channel.getValueType()); - - if (record.getFlag() == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "No flag setted."); - } - else if (record.getValue() == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "No value setted."); - } - else { - Long timestamp = record.getTimestamp(); - if (timestamp == null) { - timestamp = System.currentTimeMillis(); - } - Record rec = new Record(record.getValue(), timestamp, record.getFlag()); - channel.setLatestRecord(rec); - } - } - - private void doWriteChannel(String channelID, HttpServletResponse response, FromJson json) { - - Channel channel = dataAccess.getChannel(channelID); - - Value value = json.getValue(channel.getValueType()); - Flag flag = channel.write(value); - - if (flag != Flag.VALID) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, - "Problems by writing to channel. Flag = " + flag.toString()); - } - } + private static final long serialVersionUID = -702876016040151438L; + private final static Logger logger = LoggerFactory.getLogger(ChannelResourceServlet.class); + + private DataAccessService dataAccess; + private ConfigService configService; + private RootConfig rootConfig; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String channelID, fromParameter, untilParameter, configField; + String pathInfo = pathAndQueryString[0]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + + response.setStatus(HttpServletResponse.SC_OK); + + ToJson json = new ToJson(); + + if (pathInfo.equals("/")) { + doGetAllChannels(json); + } else { + channelID = pathInfoArray[0].replace("/", ""); + if (pathInfoArray.length == 1) { + doGetSpecificChannel(json, channelID, response); + } else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + doGetConfigs(json, channelID, response); + } else if (pathInfoArray.length == 3 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + configField = pathInfoArray[2]; + doGetConfigField(json, channelID, configField, response); + } else if (pathInfoArray.length == 2 && pathInfoArray[1].startsWith(Const.HISTORY)) { + fromParameter = request.getParameter("from"); + untilParameter = request.getParameter("until"); + doGetHistory(json, channelID, fromParameter, untilParameter, response); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + sendJson(json, response); + } + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String channelID = pathInfoArray[0].replace("/", ""); + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfoArray.length == 1) { + setAndWriteChannelConfig(channelID, response, json, false); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + + } + } + + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String channelID = pathInfoArray[0].replace("/", ""); + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfoArray.length < 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } else { + ChannelConfig channelConfig = rootConfig.getChannel(channelID); + + if (channelConfig != null) { + + if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + setAndWriteChannelConfig(channelID, response, json, true); + } else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.LATESTRECORD)) { + doSetRecord(channelID, response, json); + } else if (pathInfoArray.length == 1) { + doWriteChannel(channelID, response, json); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", + request.getPathInfo()); + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested channel is not available.", " Channel = ", channelID); + } + } + } + } + + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[0]; + String channelId; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + ChannelConfig channelConfig; + + channelId = pathInfoArray[0].replace("/", ""); + channelConfig = rootConfig.getChannel(channelId); + + if (pathInfoArray.length != 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available", " Path Info = ", request.getPathInfo()); + } else if (channelConfig == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Channel \"" + channelId + "\" does not exist."); + } else { + try { + channelConfig.delete(); + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + + if (rootConfig.getDriver(channelId) == null) { + response.setStatus(HttpServletResponse.SC_OK); + } else { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to delete channel ", channelId); + } + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to write into config."); + e.printStackTrace(); + } + } + } + } + + private void doGetConfigField(ToJson json, String channelID, String configField, HttpServletResponse response) throws IOException { + + ChannelConfig channelConfig = rootConfig.getChannel(channelID); + + if (channelConfig != null) { + JsonObject jsoConfigAll = ToJson.getChannelConfigAsJsonObject(channelConfig); + if (jsoConfigAll == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Could not find JSON object \"configs\""); + } else { + JsonElement jseConfigField = jsoConfigAll.get(configField); + + if (jseConfigField == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest config field is not available.", " configField = ", configField); + } else { + JsonObject jso = new JsonObject(); + jso.add(configField, jseConfigField); + json.addJsonObject(Const.CONFIGS, jso); + } + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest channel is not available.", " ChannelID = ", channelID); + } + } + + private void doGetConfigs(ToJson json, String channelID, HttpServletResponse response) throws IOException { + + ChannelConfig channelConfig = rootConfig.getChannel(channelID); + + if (channelConfig != null) { + json.addChannelConfig(channelConfig); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest channel is not available.", " ChannelID = ", channelID); + } + } + + private void doGetHistory(ToJson json, String channelID, String fromParameter, String untilParameter, HttpServletResponse response) { + long fromTimeStamp = 0, untilTimeStamp = 0; + + List channelIDs = dataAccess.getAllIds(); + List records = null; + + if (channelIDs.contains(channelID)) { + Channel channel = dataAccess.getChannel(channelID); + + try { + fromTimeStamp = Long.parseLong(fromParameter); + untilTimeStamp = Long.parseLong(untilParameter); + } catch (NumberFormatException ex) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_BAD_REQUEST, logger, + "From/To value is not a long number."); + } + + try { + records = channel.getLoggedRecords(fromTimeStamp, untilTimeStamp); + } catch (DataLoggerNotAvailableException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, e.getMessage()); + } catch (IOException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); + } + json.addRecordList(records, channel.getValueType()); + } + } + + private boolean setAndWriteChannelConfig(String channelID, HttpServletResponse response, FromJson json, boolean isHTTPPut) { + + boolean ok = false; + + try { + if (isHTTPPut) { + ok = setAndWriteHttpPutChannelConfig(channelID, response, json); + } else { + ok = setAndWriteHttpPostChannelConfig(channelID, response, json); + } + } catch (JsonSyntaxException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, "JSON syntax is wrong."); + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Could not write channel \"", channelID, + "\"."); + e.printStackTrace(); + } catch (RestConfigIsNotCorrectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, + "Not correct formed channel config json.", " JSON = ", json.getJsonObject().toString()); + } catch (Error e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, e.getMessage()); + } catch (MissingJsonObjectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); + } catch (IllegalStateException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); + } + return ok; + } + + private boolean setAndWriteHttpPutChannelConfig(String channelID, HttpServletResponse response, FromJson json) throws + JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, MissingJsonObjectException, IllegalStateException { + + boolean ok = false; + + ChannelConfig channelConfig = rootConfig.getChannel(channelID); + if (channelConfig != null) { + try { + json.setChannelConfig(channelConfig, channelID); + + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + } catch (IdCollisionException e) { + + } + response.setStatus(HttpServletResponse.SC_OK); + ok = true; + } else { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to access to channel ", channelID); + } + return ok; + } + + private boolean setAndWriteHttpPostChannelConfig(String channelID, HttpServletResponse response, FromJson json) throws + JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, Error, MissingJsonObjectException, + IllegalStateException { + + boolean ok = false; + DeviceConfig deviceConfig; + + ChannelConfig channelConfig = rootConfig.getChannel(channelID); + + JsonObject jso = json.getJsonObject(); + String deviceID = jso.get(Const.DEVICE).getAsString(); + + if (deviceID != null) { + deviceConfig = rootConfig.getDevice(deviceID); + } else { + throw new Error("No device ID in JSON"); + } + + if (deviceConfig == null) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Device does not exists: ", deviceID); + } else if (channelConfig != null) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Channel already exists: ", channelID); + } else { + try { + channelConfig = deviceConfig.addChannel(channelID); + json.setChannelConfig(channelConfig, channelID); + + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + } catch (IdCollisionException e) { + } + response.setStatus(HttpServletResponse.SC_OK); + ok = true; + } + return ok; + } + + private void doGetSpecificChannel(ToJson json, String chId, HttpServletResponse response) throws IOException { + + Channel channel = dataAccess.getChannel(chId); + if (channel != null) { + Record record = channel.getLatestRecord(); + json.addRecord(record, channel.getValueType()); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest channel is not available, ChannelID = " + chId); + } + } + + private void doGetAllChannels(ToJson json) { + + List ids = dataAccess.getAllIds(); + List channels = new ArrayList(ids.size()); + + for (String id : ids) { + channels.add(dataAccess.getChannel(id)); + + } + json.addChannelRecordList(channels); + } + + private void doSetRecord(String channelID, HttpServletResponse response, FromJson json) throws ClassCastException { + + Channel channel = dataAccess.getChannel(channelID); + Record record = json.getRecord(channel.getValueType()); + + if (record.getFlag() == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, "No flag setted."); + } else if (record.getValue() == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, "No value setted."); + } else { + Long timestamp = record.getTimestamp(); + if (timestamp == null) { + timestamp = System.currentTimeMillis(); + } + Record rec = new Record(record.getValue(), timestamp, record.getFlag()); + channel.setLatestRecord(rec); + } + } + + private void doWriteChannel(String channelID, HttpServletResponse response, FromJson json) { + + Channel channel = dataAccess.getChannel(channelID); + + Value value = json.getValue(channel.getValueType()); + Flag flag = channel.write(value); + + if (flag != Flag.VALID) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, + "Problems by writing to channel. Flag = " + flag.toString()); + } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ControlsServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ControlsServlet.java index f171c967..8ed249fd 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ControlsServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ControlsServlet.java @@ -20,119 +20,112 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.openmuc.framework.lib.json.FromJson; import org.openmuc.framework.lib.json.ToJson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + public class ControlsServlet extends GenericServlet { - private static final long serialVersionUID = -5635380730045771853L; - private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); + private static final long serialVersionUID = -5635380730045771853L; + private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - if (pathAndQueryString != null) { + if (pathAndQueryString != null) { - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - ToJson json = new ToJson(); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + ToJson json = new ToJson(); - if (pathInfo.equals("/")) { + if (pathInfo.equals("/")) { - } - else { - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + } else { + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - if (pathInfoArray.length == 1) { + if (pathInfoArray.length == 1) { - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); - } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); + } - } - sendJson(json, response); - } - } + } + sendJson(json, response); + } + } - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - if (pathAndQueryString != null) { + if (pathAndQueryString != null) { - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - new FromJson(ServletLib.getJsonText(request)); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + new FromJson(ServletLib.getJsonText(request)); - if (pathInfo.equals("/")) { + if (pathInfo.equals("/")) { - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - if (pathAndQueryString != null) { + if (pathAndQueryString != null) { - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - new FromJson(ServletLib.getJsonText(request)); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + new FromJson(ServletLib.getJsonText(request)); - if (pathInfo.equals("/")) { + if (pathInfo.equals("/")) { - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - if (pathAndQueryString != null) { + if (pathAndQueryString != null) { - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - new FromJson(ServletLib.getJsonText(request)); + new FromJson(ServletLib.getJsonText(request)); - if (pathInfo.equals("/")) { + if (pathInfo.equals("/")) { - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest path is not available.", + " Rest Path = ", request.getPathInfo()); + } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DeviceResourceServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DeviceResourceServlet.java index 64ca0103..d34e00c3 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DeviceResourceServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DeviceResourceServlet.java @@ -20,26 +20,10 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ChannelScanInfo; -import org.openmuc.framework.config.ConfigService; -import org.openmuc.framework.config.ConfigWriteException; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.DriverNotAvailableException; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.RootConfig; -import org.openmuc.framework.config.ScanException; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.openmuc.framework.config.*; import org.openmuc.framework.dataaccess.Channel; import org.openmuc.framework.dataaccess.DataAccessService; import org.openmuc.framework.dataaccess.DeviceState; @@ -51,403 +35,376 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; public class DeviceResourceServlet extends GenericServlet { - private static final long serialVersionUID = 4619892734239871891L; - private final static Logger logger = LoggerFactory.getLogger(DeviceResourceServlet.class); - - private DataAccessService dataAccess; - private ConfigService configService; - private RootConfig rootConfig; - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String deviceID, configField; - String pathInfo = pathAndQueryString[0]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - List deviceList = doGetDeviceList(); - - response.setStatus(HttpServletResponse.SC_OK); - - ToJson json = new ToJson(); - - if (pathInfo.equals("/")) { - json.addStringList(Const.DEVICES, deviceList); - } - else { - deviceID = pathInfoArray[0].replace("/", ""); - - if (deviceList.contains(deviceID)) { - - List deviceChannelList = doGetDeviceChannelList(deviceID); - DeviceState deviceState = configService.getDeviceState(deviceID); - - if (pathInfoArray.length == 1) { - json.addChannelRecordList(deviceChannelList); - json.addDeviceState(deviceState); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.STATE)) { - json.addDeviceState(deviceState); - } - else if (pathInfoArray.length > 1 && pathInfoArray[1].equals(Const.CHANNELS)) { - json.addChannelList(deviceChannelList); - json.addDeviceState(deviceState); - } - else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - doGetConfigs(json, deviceID, response); - } - else if (pathInfoArray.length == 3 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - configField = pathInfoArray[2]; - doGetConfigField(json, deviceID, configField, response); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.SCAN)) { - String settings = request.getParameter(Const.SETTINGS); - List channelScanInfoList = scanForAllChannels(deviceID, settings, response); - json.addChannelScanInfoList(channelScanInfoList); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest device is not available, DeviceID = " + deviceID); - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest device is not available, DeviceID = " + deviceID); - } - } - sendJson(json, response); - } - } - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String deviceID = pathInfoArray[0].replace("/", ""); - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfoArray.length == 1) { - setAndWriteDeviceConfig(deviceID, response, json, false); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - - } - } - - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String deviceID = pathInfoArray[0].replace("/", ""); - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfoArray.length < 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - else { - - DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); - - if (deviceConfig != null && pathInfoArray.length == 2 - && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - setAndWriteDeviceConfig(deviceID, response, json, true); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } - } - - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[0]; - String deviceID = null; - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - - deviceID = pathInfoArray[0].replace("/", ""); - DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); - - if (pathInfoArray.length != 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available", " Path Info = ", request.getPathInfo()); - } - else if (deviceConfig == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Device \"" - + deviceID + "\" does not exist."); - } - else { - try { - deviceConfig.delete(); - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - - if (rootConfig.getDriver(deviceID) == null) { - response.setStatus(HttpServletResponse.SC_OK); - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - logger, "Not able to delete driver ", deviceID); - } - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to write into config."); - e.printStackTrace(); - } - } - } - } - - private List scanForAllChannels(String deviceID, String settings, HttpServletResponse response) { - - List channelList = new ArrayList(); - List scannedDevicesList; - - try { - scannedDevicesList = configService.scanForChannels(deviceID, settings); - - for (ChannelScanInfo scannedDevice : scannedDevicesList) { - channelList.add(scannedDevice); - } - - } catch (UnsupportedOperationException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Device does not support scanning.", " deviceId = ", deviceID); - } catch (DriverNotAvailableException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest device is not available.", " deviceId = ", deviceID); - } catch (ArgumentSyntaxException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "Argument syntax was wrong.", " deviceId = ", deviceID, " Settings = ", settings); - } catch (ScanException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Error while scan device channels", " deviceId = ", deviceID, " Settings = ", settings); - } - return channelList; - } - - private List doGetDeviceChannelList(String deviceID) { - - List deviceChannelList = new ArrayList(); - Collection channelConfig; - - channelConfig = rootConfig.getDevice(deviceID).getChannels(); - for (ChannelConfig chCf : channelConfig) { - deviceChannelList.add(dataAccess.getChannel(chCf.getId())); - } - return deviceChannelList; - } - - private List doGetDeviceList() { - - List deviceList = new ArrayList(); - - Collection driverConfig; - driverConfig = rootConfig.getDrivers(); - - Collection deviceConfig = new ArrayList(); - - for (DriverConfig drvCfg : driverConfig) { - String driverId = drvCfg.getId(); - deviceConfig.addAll(rootConfig.getDriver(driverId).getDevices()); - } - for (DeviceConfig devCfg : deviceConfig) { - deviceList.add(devCfg.getId()); - } - return deviceList; - } - - private void doGetConfigField(ToJson json, String deviceID, String configField, HttpServletResponse response) - throws IOException { - - DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); - - if (deviceConfig != null) { - JsonObject jsoConfigAll = ToJson.getDeviceConfigAsJsonObject(deviceConfig); - if (jsoConfigAll == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Could not find JSON object \"configs\""); - } - else { - JsonElement jseConfigField = jsoConfigAll.get(configField); - - if (jseConfigField == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest config field is not available.", " configField = ", configField); - } - else { - JsonObject jso = new JsonObject(); - jso.add(configField, jseConfigField); - json.addJsonObject(Const.CONFIGS, jso); - } - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest channel is not available.", " ChannelID = ", deviceID); - } - } - - private void doGetConfigs(ToJson json, String deviceID, HttpServletResponse response) throws IOException { - - DeviceConfig deviceConfig; - deviceConfig = rootConfig.getDevice(deviceID); - - if (deviceConfig != null) { - json.addDeviceConfig(deviceConfig); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest device is not available.", " DeviceID = ", deviceID); - } - } - - private boolean setAndWriteDeviceConfig(String deviceID, HttpServletResponse response, FromJson json, - boolean isHTTPPut) { - - boolean ok = false; - - try { - if (isHTTPPut) { - ok = setAndWriteHttpPutDeviceConfig(deviceID, response, json); - } - else { - ok = setAndWriteHttpPostDeviceConfig(deviceID, response, json); - } - } catch (JsonSyntaxException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, - "JSON syntax is wrong."); - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Could not write device \"", deviceID, "\"."); - e.printStackTrace(); - } catch (RestConfigIsNotCorrectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "Not correct formed device config json.", " JSON = ", json.getJsonObject().toString()); - } catch (Error e) { - ServletLib - .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, e.getMessage()); - } catch (MissingJsonObjectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); - e.printStackTrace(); - } catch (IllegalStateException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); - } - return ok; - } - - private boolean setAndWriteHttpPutDeviceConfig(String deviceID, HttpServletResponse response, FromJson json) - throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, - MissingJsonObjectException, IllegalStateException { - - boolean ok = false; - - DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); - if (deviceConfig != null) { - try { - json.setDeviceConfig(deviceConfig, deviceID); - } catch (IdCollisionException e) { - } - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - response.setStatus(HttpServletResponse.SC_OK); - ok = true; - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to access to device ", deviceID); - } - return ok; - } - - private boolean setAndWriteHttpPostDeviceConfig(String deviceID, HttpServletResponse response, FromJson json) - throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, Error, - MissingJsonObjectException, IllegalStateException { - - boolean ok = false; - DriverConfig driverConfig; - - DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); - - JsonObject jso = json.getJsonObject(); - String driverID = jso.get(Const.DRIVER).getAsString(); - - if (driverID != null) { - driverConfig = rootConfig.getDriver(driverID); - } - else { - throw new Error("No driver ID in JSON"); - } - - if (driverConfig == null) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Driver does not exists: ", driverID); - } - else if (deviceConfig != null) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Device already exists: ", deviceID); - } - else { - try { - deviceConfig = driverConfig.addDevice(deviceID); - json.setDeviceConfig(deviceConfig, deviceID); - } catch (IdCollisionException e) { - } - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - response.setStatus(HttpServletResponse.SC_OK); - ok = true; - } - return ok; - } + private static final long serialVersionUID = 4619892734239871891L; + private final static Logger logger = LoggerFactory.getLogger(DeviceResourceServlet.class); + + private DataAccessService dataAccess; + private ConfigService configService; + private RootConfig rootConfig; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String deviceID, configField; + String pathInfo = pathAndQueryString[0]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + List deviceList = doGetDeviceList(); + + response.setStatus(HttpServletResponse.SC_OK); + + ToJson json = new ToJson(); + + if (pathInfo.equals("/")) { + json.addStringList(Const.DEVICES, deviceList); + } else { + deviceID = pathInfoArray[0].replace("/", ""); + + if (deviceList.contains(deviceID)) { + + List deviceChannelList = doGetDeviceChannelList(deviceID); + DeviceState deviceState = configService.getDeviceState(deviceID); + + if (pathInfoArray.length == 1) { + json.addChannelRecordList(deviceChannelList); + json.addDeviceState(deviceState); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.STATE)) { + json.addDeviceState(deviceState); + } else if (pathInfoArray.length > 1 && pathInfoArray[1].equals(Const.CHANNELS)) { + json.addChannelList(deviceChannelList); + json.addDeviceState(deviceState); + } else if (pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + doGetConfigs(json, deviceID, response); + } else if (pathInfoArray.length == 3 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + configField = pathInfoArray[2]; + doGetConfigField(json, deviceID, configField, response); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.SCAN)) { + String settings = request.getParameter(Const.SETTINGS); + List channelScanInfoList = scanForAllChannels(deviceID, settings, response); + json.addChannelScanInfoList(channelScanInfoList); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest device is not available, DeviceID = " + deviceID); + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest device is not available, DeviceID = " + deviceID); + } + } + sendJson(json, response); + } + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String deviceID = pathInfoArray[0].replace("/", ""); + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfoArray.length == 1) { + setAndWriteDeviceConfig(deviceID, response, json, false); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + + } + } + + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String deviceID = pathInfoArray[0].replace("/", ""); + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfoArray.length < 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } else { + + DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); + + if (deviceConfig != null && pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + setAndWriteDeviceConfig(deviceID, response, json, true); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } + } + + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[0]; + String deviceID = null; + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + + deviceID = pathInfoArray[0].replace("/", ""); + DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); + + if (pathInfoArray.length != 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available", " Path Info = ", request.getPathInfo()); + } else if (deviceConfig == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Device \"" + deviceID + "\" does not exist."); + } else { + try { + deviceConfig.delete(); + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + + if (rootConfig.getDriver(deviceID) == null) { + response.setStatus(HttpServletResponse.SC_OK); + } else { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to delete driver ", deviceID); + } + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to write into config."); + e.printStackTrace(); + } + } + } + } + + private List scanForAllChannels(String deviceID, String settings, HttpServletResponse response) { + + List channelList = new ArrayList(); + List scannedDevicesList; + + try { + scannedDevicesList = configService.scanForChannels(deviceID, settings); + + for (ChannelScanInfo scannedDevice : scannedDevicesList) { + channelList.add(scannedDevice); + } + + } catch (UnsupportedOperationException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Device does not support scanning.", " deviceId = ", deviceID); + } catch (DriverNotAvailableException e) { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest device is not available.", + " deviceId = ", deviceID); + } catch (ArgumentSyntaxException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, "Argument syntax was wrong.", + " deviceId = ", deviceID, " Settings = ", settings); + } catch (ScanException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Error while scan device channels", " deviceId = ", deviceID, " Settings = ", settings); + } + return channelList; + } + + private List doGetDeviceChannelList(String deviceID) { + + List deviceChannelList = new ArrayList(); + Collection channelConfig; + + channelConfig = rootConfig.getDevice(deviceID).getChannels(); + for (ChannelConfig chCf : channelConfig) { + deviceChannelList.add(dataAccess.getChannel(chCf.getId())); + } + return deviceChannelList; + } + + private List doGetDeviceList() { + + List deviceList = new ArrayList(); + + Collection driverConfig; + driverConfig = rootConfig.getDrivers(); + + Collection deviceConfig = new ArrayList(); + + for (DriverConfig drvCfg : driverConfig) { + String driverId = drvCfg.getId(); + deviceConfig.addAll(rootConfig.getDriver(driverId).getDevices()); + } + for (DeviceConfig devCfg : deviceConfig) { + deviceList.add(devCfg.getId()); + } + return deviceList; + } + + private void doGetConfigField(ToJson json, String deviceID, String configField, HttpServletResponse response) throws IOException { + + DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); + + if (deviceConfig != null) { + JsonObject jsoConfigAll = ToJson.getDeviceConfigAsJsonObject(deviceConfig); + if (jsoConfigAll == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Could not find JSON object \"configs\""); + } else { + JsonElement jseConfigField = jsoConfigAll.get(configField); + + if (jseConfigField == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest config field is not available.", " configField = ", configField); + } else { + JsonObject jso = new JsonObject(); + jso.add(configField, jseConfigField); + json.addJsonObject(Const.CONFIGS, jso); + } + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest channel is not available.", " ChannelID = ", deviceID); + } + } + + private void doGetConfigs(ToJson json, String deviceID, HttpServletResponse response) throws IOException { + + DeviceConfig deviceConfig; + deviceConfig = rootConfig.getDevice(deviceID); + + if (deviceConfig != null) { + json.addDeviceConfig(deviceConfig); + } else { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest device is not available.", + " DeviceID = ", deviceID); + } + } + + private boolean setAndWriteDeviceConfig(String deviceID, HttpServletResponse response, FromJson json, boolean isHTTPPut) { + + boolean ok = false; + + try { + if (isHTTPPut) { + ok = setAndWriteHttpPutDeviceConfig(deviceID, response, json); + } else { + ok = setAndWriteHttpPostDeviceConfig(deviceID, response, json); + } + } catch (JsonSyntaxException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, "JSON syntax is wrong."); + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Could not write device \"", deviceID, + "\"."); + e.printStackTrace(); + } catch (RestConfigIsNotCorrectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, + "Not correct formed device config json.", " JSON = ", json.getJsonObject().toString()); + } catch (Error e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, e.getMessage()); + } catch (MissingJsonObjectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); + e.printStackTrace(); + } catch (IllegalStateException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); + } + return ok; + } + + private boolean setAndWriteHttpPutDeviceConfig(String deviceID, HttpServletResponse response, FromJson json) throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, MissingJsonObjectException, IllegalStateException { + + boolean ok = false; + + DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); + if (deviceConfig != null) { + try { + json.setDeviceConfig(deviceConfig, deviceID); + } catch (IdCollisionException e) { + } + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + response.setStatus(HttpServletResponse.SC_OK); + ok = true; + } else { + ServletLib + .sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, "Not able to access to device ", + deviceID); + } + return ok; + } + + private boolean setAndWriteHttpPostDeviceConfig(String deviceID, HttpServletResponse response, FromJson json) throws JsonSyntaxException, ConfigWriteException, RestConfigIsNotCorrectException, Error, MissingJsonObjectException, IllegalStateException { + + boolean ok = false; + DriverConfig driverConfig; + + DeviceConfig deviceConfig = rootConfig.getDevice(deviceID); + + JsonObject jso = json.getJsonObject(); + String driverID = jso.get(Const.DRIVER).getAsString(); + + if (driverID != null) { + driverConfig = rootConfig.getDriver(driverID); + } else { + throw new Error("No driver ID in JSON"); + } + + if (driverConfig == null) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Driver does not exists: ", driverID); + } else if (deviceConfig != null) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Device already exists: ", deviceID); + } else { + try { + deviceConfig = driverConfig.addDevice(deviceID); + json.setDeviceConfig(deviceConfig, deviceID); + } catch (IdCollisionException e) { + } + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + response.setStatus(HttpServletResponse.SC_OK); + ok = true; + } + return ok; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DriverResourceServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DriverResourceServlet.java index 018800a9..e2986032 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DriverResourceServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/DriverResourceServlet.java @@ -20,27 +20,10 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openmuc.framework.config.ArgumentSyntaxException; -import org.openmuc.framework.config.ChannelConfig; -import org.openmuc.framework.config.ConfigService; -import org.openmuc.framework.config.ConfigWriteException; -import org.openmuc.framework.config.DeviceConfig; -import org.openmuc.framework.config.DeviceScanInfo; -import org.openmuc.framework.config.DriverConfig; -import org.openmuc.framework.config.DriverNotAvailableException; -import org.openmuc.framework.config.IdCollisionException; -import org.openmuc.framework.config.RootConfig; -import org.openmuc.framework.config.ScanException; -import org.openmuc.framework.config.ScanInterruptedException; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.openmuc.framework.config.*; import org.openmuc.framework.dataaccess.Channel; import org.openmuc.framework.dataaccess.DataAccessService; import org.openmuc.framework.lib.json.Const; @@ -51,378 +34,361 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; public class DriverResourceServlet extends GenericServlet { - private static final long serialVersionUID = -2223282905555493215L; - private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); - - private DataAccessService dataAccess; - private ConfigService configService; - private RootConfig rootConfig; - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - - List driversList = new ArrayList(); - Collection driverConfigList = rootConfig.getDrivers(); - - for (DriverConfig drv : driverConfigList) { - driversList.add(drv.getId()); - } - - ToJson json = new ToJson(); - - if (pathInfo.equals("/")) { - json.addStringList(Const.DRIVERS, driversList); - } - else { - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String driverID = pathInfoArray[0].replace("/", ""); - - List driverChannelsList; - List driverDevicesList = new ArrayList(); - - if (driversList.contains(driverID)) { - - Collection channelConfigList = new ArrayList(); - Collection deviceConfigList; - DriverConfig drv = rootConfig.getDriver(driverID); - - deviceConfigList = drv.getDevices(); - setDriverDevicesListAndChannelConfigList(driverDevicesList, channelConfigList, deviceConfigList); - driverChannelsList = getDriverChannelList(channelConfigList); - - response.setStatus(HttpServletResponse.SC_OK); - boolean driverIsRunning = configService.getIdsOfRunningDrivers().contains(driverID); - - if (pathInfoArray.length > 1) { - if (pathInfoArray[1].equalsIgnoreCase(Const.CHANNELS)) { - json.addChannelList(driverChannelsList); - json.addBoolean(Const.RUNNING, driverIsRunning); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.RUNNING)) { - json.addBoolean(Const.RUNNING, driverIsRunning); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.DEVICES)) { - json.addStringList(Const.DEVICES, driverDevicesList); - json.addBoolean(Const.RUNNING, driverIsRunning); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.SCAN)) { - String settings = request.getParameter(Const.SETTINGS); - List deviceScanInfoList = scanForAllDrivers(driverID, settings, response); - json.addDeviceScanInfoList(deviceScanInfoList); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS) && pathInfoArray.length == 2) { - doGetConfigs(json, driverID, response); - } - else if (pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS) && pathInfoArray.length == 3) { - doGetConfigField(json, driverID, pathInfoArray[2], response); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); - } - } - else if (pathInfoArray.length == 1) { - json.addChannelRecordList(driverChannelsList); - json.addBoolean(Const.RUNNING, driverIsRunning); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); - } - - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest driver is not available.", " driverID = ", driverID); - } - } - sendJson(json, response); - } - } - - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String driverID = pathInfoArray[0].replace("/", ""); - - String json = ServletLib.getJsonText(request); - - if (pathInfoArray.length < 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - else { - DriverConfig driverConfig = rootConfig.getDriver(driverID); - - if (driverConfig != null && pathInfoArray.length == 2 - && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { - setAndWriteDriverConfig(driverID, response, json, true); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } - } - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - String driverID = pathInfoArray[0].replace("/", ""); - - String json = ServletLib.getJsonText(request); - - if (pathInfoArray.length != 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - else { - try { - rootConfig.addDriver(driverID); - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - - setAndWriteDriverConfig(driverID, response, json, false); - - } catch (IdCollisionException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, "Driver \"" - + driverID + "\" already exist"); - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Could not write driver \"", driverID, "\"."); - e.printStackTrace(); - } - } - } - } - - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - this.dataAccess = handleDataAccessService(null); - this.configService = handleConfigService(null); - this.rootConfig = handleRootConfig(null); - - String pathInfo = pathAndQueryString[0]; - String driverID = null; - - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - driverID = pathInfoArray[0].replace("/", ""); - - DriverConfig driverConfig = rootConfig.getDriver(driverID); - - if (pathInfoArray.length != 1) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available", " Path Info = ", request.getPathInfo()); - } - else if (driverConfig == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Driver \"" - + driverID + "\" does not exist."); - } - else { - try { - driverConfig.delete(); - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - - if (rootConfig.getDriver(driverID) == null) { - response.setStatus(HttpServletResponse.SC_OK); - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - logger, "Not able to delete driver ", driverID); - } - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to write into config."); - e.printStackTrace(); - } - } - } - } - - private boolean setAndWriteDriverConfig(String driverID, HttpServletResponse response, String json, - boolean isHTTPPut) { - - boolean ok = false; - - try { - DriverConfig driverConfig = rootConfig.getDriver(driverID); - if (driverConfig != null) { - try { - FromJson fromJson = new FromJson(json); - fromJson.setDriverConfig(driverConfig, driverID); - } catch (IdCollisionException e) { - - } - configService.setConfig(rootConfig); - configService.writeConfigToFile(); - response.setStatus(HttpServletResponse.SC_OK); - ok = true; - } - else { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Not able to access to driver ", driverID); - } - } catch (JsonSyntaxException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, - "JSON syntax is wrong."); - } catch (MissingJsonObjectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); - } catch (ConfigWriteException e) { - ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, - "Could not write driver \"", driverID, "\"."); - e.printStackTrace(); - } catch (RestConfigIsNotCorrectException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "Not correct formed driver config json.", " JSON = ", json); - } catch (IllegalStateException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); - } - return ok; - } - - private void doGetConfigs(ToJson json, String drvId, HttpServletResponse response) throws IOException { - - DriverConfig driverConfig = rootConfig.getDriver(drvId); - - if (driverConfig != null) { - json.addDriverConfig(driverConfig); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest driver is not available.", " driverID = ", drvId); - } - } - - private void doGetConfigField(ToJson json, String drvId, String configField, HttpServletResponse response) - throws IOException { - - DriverConfig driverConfig = rootConfig.getDriver(drvId); - - if (driverConfig != null) { - JsonObject jsoConfigAll = ToJson.getDriverConfigAsJsonObject(driverConfig); - if (jsoConfigAll == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Could not find JSON object \"configs\""); - } - else { - JsonElement jseConfigField = jsoConfigAll.get(configField); - - if (jseConfigField == null) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest config field is not available.", " configField = ", configField); - } - else { - JsonObject jso = new JsonObject(); - jso.add(configField, jseConfigField); - json.addJsonObject(Const.CONFIGS, jso); - } - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest driver is not available.", " driverID = ", drvId); - } - } - - private List scanForAllDrivers(String driverID, String settings, HttpServletResponse response) { - - List deviceList = new ArrayList(); - List scannedDevicesList; - - try { - scannedDevicesList = configService.scanForDevices(driverID, settings); - - for (DeviceScanInfo scannedDevice : scannedDevicesList) { - deviceList.add(scannedDevice); - } - - } catch (UnsupportedOperationException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Driver does not support scanning.", " driverID = ", driverID); - } catch (DriverNotAvailableException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest driver is not available.", " driverID = ", driverID); - } catch (ArgumentSyntaxException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, - "Argument syntax was wrong.", " driverID = ", driverID, " Settings = ", settings); - } catch (ScanException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Error while scan driver devices", " driverID = ", driverID, " Settings = ", settings); - } catch (ScanInterruptedException e) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, - "Scan interrupt occured", " driverID = ", driverID, " Settings = ", settings); - } - - return deviceList; - } - - private List getDriverChannelList(Collection channelConfig) { - - List driverChannels = new ArrayList(); - - for (ChannelConfig chCf : channelConfig) { - driverChannels.add(dataAccess.getChannel(chCf.getId())); - } - - return driverChannels; - } - - private void setDriverDevicesListAndChannelConfigList(List driverDevices, - Collection channelConfig, Collection deviceConfig) { - - for (DeviceConfig dvCf : deviceConfig) { - driverDevices.add(dvCf.getId()); - channelConfig.addAll(dvCf.getChannels()); - } - } + private static final long serialVersionUID = -2223282905555493215L; + private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); + + private DataAccessService dataAccess; + private ConfigService configService; + private RootConfig rootConfig; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + + List driversList = new ArrayList(); + Collection driverConfigList = rootConfig.getDrivers(); + + for (DriverConfig drv : driverConfigList) { + driversList.add(drv.getId()); + } + + ToJson json = new ToJson(); + + if (pathInfo.equals("/")) { + json.addStringList(Const.DRIVERS, driversList); + } else { + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String driverID = pathInfoArray[0].replace("/", ""); + + List driverChannelsList; + List driverDevicesList = new ArrayList(); + + if (driversList.contains(driverID)) { + + Collection channelConfigList = new ArrayList(); + Collection deviceConfigList; + DriverConfig drv = rootConfig.getDriver(driverID); + + deviceConfigList = drv.getDevices(); + setDriverDevicesListAndChannelConfigList(driverDevicesList, channelConfigList, deviceConfigList); + driverChannelsList = getDriverChannelList(channelConfigList); + + response.setStatus(HttpServletResponse.SC_OK); + boolean driverIsRunning = configService.getIdsOfRunningDrivers().contains(driverID); + + if (pathInfoArray.length > 1) { + if (pathInfoArray[1].equalsIgnoreCase(Const.CHANNELS)) { + json.addChannelList(driverChannelsList); + json.addBoolean(Const.RUNNING, driverIsRunning); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.RUNNING)) { + json.addBoolean(Const.RUNNING, driverIsRunning); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.DEVICES)) { + json.addStringList(Const.DEVICES, driverDevicesList); + json.addBoolean(Const.RUNNING, driverIsRunning); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.SCAN)) { + String settings = request.getParameter(Const.SETTINGS); + List deviceScanInfoList = scanForAllDrivers(driverID, settings, response); + json.addDeviceScanInfoList(deviceScanInfoList); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS) && pathInfoArray.length == 2) { + doGetConfigs(json, driverID, response); + } else if (pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS) && pathInfoArray.length == 3) { + doGetConfigField(json, driverID, pathInfoArray[2], response); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Path Info = ", + request.getPathInfo()); + } + } else if (pathInfoArray.length == 1) { + json.addChannelRecordList(driverChannelsList); + json.addBoolean(Const.RUNNING, driverIsRunning); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Path Info = ", + request.getPathInfo()); + } + + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest driver is not available.", " driverID = ", driverID); + } + } + sendJson(json, response); + } + } + + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String driverID = pathInfoArray[0].replace("/", ""); + + String json = ServletLib.getJsonText(request); + + if (pathInfoArray.length < 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } else { + DriverConfig driverConfig = rootConfig.getDriver(driverID); + + if (driverConfig != null && pathInfoArray.length == 2 && pathInfoArray[1].equalsIgnoreCase(Const.CONFIGS)) { + setAndWriteDriverConfig(driverID, response, json, true); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + String driverID = pathInfoArray[0].replace("/", ""); + + String json = ServletLib.getJsonText(request); + + if (pathInfoArray.length != 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } else { + try { + rootConfig.addDriver(driverID); + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + + setAndWriteDriverConfig(driverID, response, json, false); + + } catch (IdCollisionException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, + "Driver \"" + driverID + "\" already exist"); + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Could not write driver \"", + driverID, "\"."); + e.printStackTrace(); + } + } + } + } + + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + this.dataAccess = handleDataAccessService(null); + this.configService = handleConfigService(null); + this.rootConfig = handleRootConfig(null); + + String pathInfo = pathAndQueryString[0]; + String driverID = null; + + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + driverID = pathInfoArray[0].replace("/", ""); + + DriverConfig driverConfig = rootConfig.getDriver(driverID); + + if (pathInfoArray.length != 1) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available", " Path Info = ", request.getPathInfo()); + } else if (driverConfig == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Driver \"" + driverID + "\" does not exist."); + } else { + try { + driverConfig.delete(); + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + + if (rootConfig.getDriver(driverID) == null) { + response.setStatus(HttpServletResponse.SC_OK); + } else { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to delete driver ", driverID); + } + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to write into config."); + e.printStackTrace(); + } + } + } + } + + private boolean setAndWriteDriverConfig(String driverID, HttpServletResponse response, String json, boolean isHTTPPut) { + + boolean ok = false; + + try { + DriverConfig driverConfig = rootConfig.getDriver(driverID); + if (driverConfig != null) { + try { + FromJson fromJson = new FromJson(json); + fromJson.setDriverConfig(driverConfig, driverID); + } catch (IdCollisionException e) { + + } + configService.setConfig(rootConfig); + configService.writeConfigToFile(); + response.setStatus(HttpServletResponse.SC_OK); + ok = true; + } else { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Not able to access to driver ", driverID); + } + } catch (JsonSyntaxException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, "JSON syntax is wrong."); + } catch (MissingJsonObjectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, e.getMessage()); + } catch (ConfigWriteException e) { + ServletLib.sendHTTPErrorAndLogErr(response, HttpServletResponse.SC_CONFLICT, logger, "Could not write driver \"", driverID, + "\"."); + e.printStackTrace(); + } catch (RestConfigIsNotCorrectException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, + "Not correct formed driver config json.", " JSON = ", json); + } catch (IllegalStateException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_CONFLICT, logger, e.getMessage()); + } + return ok; + } + + private void doGetConfigs(ToJson json, String drvId, HttpServletResponse response) throws IOException { + + DriverConfig driverConfig = rootConfig.getDriver(drvId); + + if (driverConfig != null) { + json.addDriverConfig(driverConfig); + } else { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest driver is not available.", + " driverID = ", drvId); + } + } + + private void doGetConfigField(ToJson json, String drvId, String configField, HttpServletResponse response) throws IOException { + + DriverConfig driverConfig = rootConfig.getDriver(drvId); + + if (driverConfig != null) { + JsonObject jsoConfigAll = ToJson.getDriverConfigAsJsonObject(driverConfig); + if (jsoConfigAll == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Could not find JSON object \"configs\""); + } else { + JsonElement jseConfigField = jsoConfigAll.get(configField); + + if (jseConfigField == null) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest config field is not available.", " configField = ", configField); + } else { + JsonObject jso = new JsonObject(); + jso.add(configField, jseConfigField); + json.addJsonObject(Const.CONFIGS, jso); + } + } + } else { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest driver is not available.", + " driverID = ", drvId); + } + } + + private List scanForAllDrivers(String driverID, String settings, HttpServletResponse response) { + + List deviceList = new ArrayList(); + List scannedDevicesList; + + try { + scannedDevicesList = configService.scanForDevices(driverID, settings); + + for (DeviceScanInfo scannedDevice : scannedDevicesList) { + deviceList.add(scannedDevice); + } + + } catch (UnsupportedOperationException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Driver does not support scanning.", " driverID = ", driverID); + } catch (DriverNotAvailableException e) { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest driver is not available.", + " driverID = ", driverID); + } catch (ArgumentSyntaxException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_ACCEPTABLE, logger, "Argument syntax was wrong.", + " driverID = ", driverID, " Settings = ", settings); + } catch (ScanException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, + "Error while scan driver devices", " driverID = ", driverID, " Settings = ", settings); + } catch (ScanInterruptedException e) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, logger, "Scan interrupt occured", + " driverID = ", driverID, " Settings = ", settings); + } + + return deviceList; + } + + private List getDriverChannelList(Collection channelConfig) { + + List driverChannels = new ArrayList(); + + for (ChannelConfig chCf : channelConfig) { + driverChannels.add(dataAccess.getChannel(chCf.getId())); + } + + return driverChannels; + } + + private void setDriverDevicesListAndChannelConfigList(List driverDevices, Collection channelConfig, Collection deviceConfig) { + + for (DeviceConfig dvCf : deviceConfig) { + driverDevices.add(dvCf.getId()); + channelConfig.addAll(dvCf.getChannels()); + } + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/GenericServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/GenericServlet.java index 4910aff2..1057d632 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/GenericServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/GenericServlet.java @@ -20,15 +20,6 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.Charset; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.openmuc.framework.authentication.AuthenticationService; import org.openmuc.framework.config.ConfigChangeListener; import org.openmuc.framework.config.ConfigService; @@ -39,122 +30,130 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.Charset; + public abstract class GenericServlet extends HttpServlet implements ConfigChangeListener { - private final static Logger logger = LoggerFactory.getLogger(GenericServlet.class); - private static final long serialVersionUID = 4041357804530863512L; - private static final Charset CHARSET = Charset.forName("UTF-8"); + private final static Logger logger = LoggerFactory.getLogger(GenericServlet.class); + private static final long serialVersionUID = 4041357804530863512L; + private static final Charset CHARSET = Charset.forName("UTF-8"); - private static DataAccessService dataAccess; - private static ConfigService configService; - private static AuthenticationService authenticationService; - private static RootConfig rootConfig; + private static DataAccessService dataAccess; + private static ConfigService configService; + private static AuthenticationService authenticationService; + private static RootConfig rootConfig; - @Override - public void init() throws ServletException { + @Override + public void init() throws ServletException { - handleDataAccessService(RestServer.getDataAccessService()); - handleConfigService(RestServer.getConfigService()); - handleRootConfig(configService.getConfig(this)); - handleAuthenticationService(RestServer.getAuthenticationService()); - } + handleDataAccessService(RestServer.getDataAccessService()); + handleConfigService(RestServer.getConfigService()); + handleRootConfig(configService.getConfig(this)); + handleAuthenticationService(RestServer.getAuthenticationService()); + } - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - } + } - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - } + } - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - } + } - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - } + } - @Override - public void destroy() { + @Override + public void destroy() { - } + } - @Override - public void configurationChanged() { + @Override + public void configurationChanged() { - } + } - void sendJson(ToJson json, HttpServletResponse response) throws ServletException, IOException { + void sendJson(ToJson json, HttpServletResponse response) throws ServletException, IOException { - OutputStream outStream = response.getOutputStream(); - String jsonString = json.toString(); - outStream.write(jsonString.getBytes(CHARSET)); - outStream.flush(); - outStream.close(); - } + OutputStream outStream = response.getOutputStream(); + String jsonString = json.toString(); + outStream.write(jsonString.getBytes(CHARSET)); + outStream.flush(); + outStream.close(); + } - String[] checkIfItIsACorrectRest(HttpServletRequest request, HttpServletResponse response, Logger logger) { + String[] checkIfItIsACorrectRest(HttpServletRequest request, HttpServletResponse response, Logger logger) { - String pathAndQueryString[] = new String[2]; + String pathAndQueryString[] = new String[2]; - String pathInfo = request.getPathInfo(); - String queryStr = request.getQueryString(); + String pathInfo = request.getPathInfo(); + String queryStr = request.getQueryString(); - if (pathInfo == null) { - pathInfo = "/"; - } - if (queryStr == null) { - queryStr = ""; - } + if (pathInfo == null) { + pathInfo = "/"; + } + if (queryStr == null) { + queryStr = ""; + } /* Accept only "application/json" and null. Null is a browser request. */ - if (request.getContentType() != null && !request.getContentType().equals("application/json")) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, logger, - "Requested rest was not a json media type. Requsted media type is: " + request.getContentType()); - pathAndQueryString = null; - } - else { - pathAndQueryString[0] = pathInfo; - pathAndQueryString[1] = queryStr; - } - return pathAndQueryString; - } - - synchronized DataAccessService handleDataAccessService(DataAccessService dataAccessService) { - - if (dataAccessService != null) { - dataAccess = dataAccessService; - } - return dataAccess; - } - - synchronized ConfigService handleConfigService(ConfigService configServ) { - - if (configServ != null) { - configService = configServ; - } - return configService; - } - - synchronized AuthenticationService handleAuthenticationService(AuthenticationService authServ) { - - if (authServ != null) { - authenticationService = authServ; - } - return authenticationService; - } - - synchronized RootConfig handleRootConfig(RootConfig rootConf) { - - if (rootConf != null) { - rootConfig = rootConf; - } - return rootConfig; - } + if (request.getContentType() != null && !request.getContentType().equals("application/json")) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, logger, + "Requested rest was not a json media type. Requsted media type is: " + request + .getContentType()); + pathAndQueryString = null; + } else { + pathAndQueryString[0] = pathInfo; + pathAndQueryString[1] = queryStr; + } + return pathAndQueryString; + } + + synchronized DataAccessService handleDataAccessService(DataAccessService dataAccessService) { + + if (dataAccessService != null) { + dataAccess = dataAccessService; + } + return dataAccess; + } + + synchronized ConfigService handleConfigService(ConfigService configServ) { + + if (configServ != null) { + configService = configServ; + } + return configService; + } + + synchronized AuthenticationService handleAuthenticationService(AuthenticationService authServ) { + + if (authServ != null) { + authenticationService = authServ; + } + return authenticationService; + } + + synchronized RootConfig handleRootConfig(RootConfig rootConf) { + + if (rootConf != null) { + rootConfig = rootConf; + } + return rootConfig; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ServletLib.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ServletLib.java index 500ffa62..58adc0cd 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ServletLib.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/ServletLib.java @@ -20,130 +20,125 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.BufferedReader; -import java.io.IOException; +import org.slf4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; +import java.io.BufferedReader; +import java.io.IOException; public class ServletLib { - protected final static int PATH_ARRAY_NR = 0; - protected final static int QUERRY_ARRAY_NR = 1; - - protected static String buildString(BufferedReader br) { - StringBuilder text = new StringBuilder(); - String line; - try { - while ((line = br.readLine()) != null) { - text.append(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - return text.toString(); - } - - /** - * Only the first String will be sended over HTTP response. - * - * @param response - * @param errorCode - * @param logger - * @param msg - */ - protected static void sendHTTPErrorAndLogWarn(HttpServletResponse response, int errorCode, Logger logger, - String... msg) { - - try { - response.sendError(errorCode, msg[0]); - } catch (IOException e) { - logger.error("Could not send HTTP Error message."); - e.printStackTrace(); - } - StringBuilder warnMessage = new StringBuilder(); - for (String m : msg) { - warnMessage.append(m); - } - logger.warn(warnMessage.toString()); - } - - /** - * Only the first String will be sended over HTTP response. - * - * @param response - * @param errorCode - * @param logger - * @param msg - */ - protected static void sendHTTPErrorAndLogDebug(HttpServletResponse response, int errorCode, Logger logger, - String... msg) { - - try { - response.sendError(errorCode, msg[0]); - } catch (IOException e) { - logger.error("Could not send HTTP Error message."); - e.printStackTrace(); - } - StringBuilder warnMessage = new StringBuilder(); - for (String m : msg) { - warnMessage.append(m); - } - logger.debug(warnMessage.toString()); - } - - /** - * Logger and HTTP response are the same message. - * - * @param response - * @param errorCode - * @param logger - * @param msg - */ - protected static void sendHTTPErrorAndLogErr(HttpServletResponse response, int errorCode, Logger logger, - String... msg) { - - try { - StringBuilder sbErrMessage = new StringBuilder(); - for (String m : msg) { - sbErrMessage.append(m); - } - String errMessage = sbErrMessage.toString(); - response.sendError(errorCode, errMessage); - logger.error(errMessage); - } catch (IOException e) { - logger.error("Could not send HTTP Error message."); - e.printStackTrace(); - } - - } - - protected static String getJsonText(HttpServletRequest request) throws IOException { - - String jsonText = ""; - jsonText = ServletLib.buildString(request.getReader()); - return jsonText; - } - - protected static String[] getPathInfoArray(String pathInfo) { - - String returnValue[]; - - if (pathInfo.length() > 1) { - int length; - - pathInfo = pathInfo.replaceFirst("/", ""); - length = pathInfo.length(); - if (pathInfo.charAt(length - 1) == '/') { - new StringBuilder(pathInfo).replace(length - 2, length - 1, ""); - } - returnValue = pathInfo.split("/"); - } - else { - returnValue = new String[] { "/" }; - } - return returnValue; - } + protected final static int PATH_ARRAY_NR = 0; + protected final static int QUERRY_ARRAY_NR = 1; + + protected static String buildString(BufferedReader br) { + StringBuilder text = new StringBuilder(); + String line; + try { + while ((line = br.readLine()) != null) { + text.append(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + return text.toString(); + } + + /** + * Only the first String will be sended over HTTP response. + * + * @param response + * @param errorCode + * @param logger + * @param msg + */ + protected static void sendHTTPErrorAndLogWarn(HttpServletResponse response, int errorCode, Logger logger, String... msg) { + + try { + response.sendError(errorCode, msg[0]); + } catch (IOException e) { + logger.error("Could not send HTTP Error message."); + e.printStackTrace(); + } + StringBuilder warnMessage = new StringBuilder(); + for (String m : msg) { + warnMessage.append(m); + } + logger.warn(warnMessage.toString()); + } + + /** + * Only the first String will be sended over HTTP response. + * + * @param response + * @param errorCode + * @param logger + * @param msg + */ + protected static void sendHTTPErrorAndLogDebug(HttpServletResponse response, int errorCode, Logger logger, String... msg) { + + try { + response.sendError(errorCode, msg[0]); + } catch (IOException e) { + logger.error("Could not send HTTP Error message."); + e.printStackTrace(); + } + StringBuilder warnMessage = new StringBuilder(); + for (String m : msg) { + warnMessage.append(m); + } + logger.debug(warnMessage.toString()); + } + + /** + * Logger and HTTP response are the same message. + * + * @param response + * @param errorCode + * @param logger + * @param msg + */ + protected static void sendHTTPErrorAndLogErr(HttpServletResponse response, int errorCode, Logger logger, String... msg) { + + try { + StringBuilder sbErrMessage = new StringBuilder(); + for (String m : msg) { + sbErrMessage.append(m); + } + String errMessage = sbErrMessage.toString(); + response.sendError(errorCode, errMessage); + logger.error(errMessage); + } catch (IOException e) { + logger.error("Could not send HTTP Error message."); + e.printStackTrace(); + } + + } + + protected static String getJsonText(HttpServletRequest request) throws IOException { + + String jsonText = ""; + jsonText = ServletLib.buildString(request.getReader()); + return jsonText; + } + + protected static String[] getPathInfoArray(String pathInfo) { + + String returnValue[]; + + if (pathInfo.length() > 1) { + int length; + + pathInfo = pathInfo.replaceFirst("/", ""); + length = pathInfo.length(); + if (pathInfo.charAt(length - 1) == '/') { + new StringBuilder(pathInfo).replace(length - 2, length - 1, ""); + } + returnValue = pathInfo.split("/"); + } else { + returnValue = new String[]{"/"}; + } + return returnValue; + } } diff --git a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/UserServlet.java b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/UserServlet.java index f329b733..a2d86487 100644 --- a/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/UserServlet.java +++ b/projects/server/restws/src/main/java/org/openmuc/framework/server/restws/servlets/UserServlet.java @@ -20,15 +20,6 @@ */ package org.openmuc.framework.server.restws.servlets; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.openmuc.framework.authentication.AuthenticationService; import org.openmuc.framework.lib.json.Const; import org.openmuc.framework.lib.json.FromJson; @@ -37,190 +28,183 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + public class UserServlet extends GenericServlet { - private static final long serialVersionUID = -5635380730045771853L; - private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); - - private AuthenticationService authenticationService; - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - setServices(); - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - ToJson json = new ToJson(); - - if (pathInfo.equals("/")) { - Set userSet = authenticationService.getAllUsers(); - List userList = new ArrayList(); - userList.addAll(userSet); - json.addStringList(Const.USERS, userList); - } - else { - String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); - - if (pathInfoArray.length == 1) { - - String userID = pathInfoArray[0].replace("/", ""); - - if (userID.equalsIgnoreCase(Const.GROUPS)) { - - List groupList = new ArrayList(); - groupList.add(""); // TODO: add real groups, if groups exists in OpenMUC - json.addStringList(Const.GROUPS, groupList); - } - else if (authenticationService.contains(userID)) { - RestUserConfig restUserConfig = new RestUserConfig(); - restUserConfig.setId(userID); - restUserConfig.setPassword("*****"); - restUserConfig.setGroups(new String[] { "" }); - restUserConfig.setDescription(""); - json.addRestUserConfig(restUserConfig); - } - - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "User does not exist.", " User = ", userID); - } - - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); - } - - } - sendJson(json, response); - } - } - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - setServices(); - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfo.equals("/")) { - RestUserConfig userConfig = json.getRestUserConfig(); - - if (authenticationService.contains(userConfig.getId())) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "User already exists.", " User = ", userConfig.getId()); - } - else if (userConfig.getPassword() == null || userConfig.getPassword().equals("")) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, - "Password is mandatory."); - } - else { - authenticationService.register(userConfig.getId(), userConfig.getPassword()); - } - - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } - - @Override - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - setServices(); - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfo.equals("/")) { - RestUserConfig userConfig = json.getRestUserConfig(); - - if (userConfig.getPassword() == null || userConfig.getPassword().equals("")) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, - "Password is mandatory."); - } - else if (userConfig.getOldPassword() == null || userConfig.getOldPassword().equals("")) { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, - "Old password is mandatory."); - } - else if (authenticationService.contains(userConfig.getId())) { - String id = userConfig.getId(); - if (authenticationService.login(id, userConfig.getOldPassword())) { - authenticationService.register(id, userConfig.getPassword()); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_UNAUTHORIZED, logger, - "Old password is wrong."); - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "User does not exist.", " User = ", userConfig.getId()); - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - } - - @Override - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - response.setContentType("application/json"); - String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); - - if (pathAndQueryString != null) { - - setServices(); - String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; - - FromJson json = new FromJson(ServletLib.getJsonText(request)); - - if (pathInfo.equals("/")) { - - RestUserConfig userConfig = json.getRestUserConfig(); - String userID = userConfig.getId(); - - if (authenticationService.contains(userID)) { - authenticationService.delete(userID); - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested user does not exist.", " User = ", userID); - } - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - - } - else { - ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, - "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); - } - } - - private void setServices() { - - this.authenticationService = handleAuthenticationService(null); - } + private static final long serialVersionUID = -5635380730045771853L; + private final static Logger logger = LoggerFactory.getLogger(DriverResourceServlet.class); + + private AuthenticationService authenticationService; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + setServices(); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + ToJson json = new ToJson(); + + if (pathInfo.equals("/")) { + Set userSet = authenticationService.getAllUsers(); + List userList = new ArrayList(); + userList.addAll(userSet); + json.addStringList(Const.USERS, userList); + } else { + String[] pathInfoArray = ServletLib.getPathInfoArray(pathInfo); + + if (pathInfoArray.length == 1) { + + String userID = pathInfoArray[0].replace("/", ""); + + if (userID.equalsIgnoreCase(Const.GROUPS)) { + + List groupList = new ArrayList(); + groupList.add(""); // TODO: add real groups, if groups exists in OpenMUC + json.addStringList(Const.GROUPS, groupList); + } else if (authenticationService.contains(userID)) { + RestUserConfig restUserConfig = new RestUserConfig(); + restUserConfig.setId(userID); + restUserConfig.setPassword("*****"); + restUserConfig.setGroups(new String[]{""}); + restUserConfig.setDescription(""); + json.addRestUserConfig(restUserConfig); + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "User does not exist.", + " User = ", userID); + } + + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Path Info = ", request.getPathInfo()); + } + + } + sendJson(json, response); + } + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + setServices(); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfo.equals("/")) { + RestUserConfig userConfig = json.getRestUserConfig(); + + if (authenticationService.contains(userConfig.getId())) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "User already exists.", + " User = ", userConfig.getId()); + } else if (userConfig.getPassword() == null || userConfig.getPassword().equals("")) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, + "Password is mandatory."); + } else { + authenticationService.register(userConfig.getId(), userConfig.getPassword()); + } + + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } + + @Override + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + setServices(); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfo.equals("/")) { + RestUserConfig userConfig = json.getRestUserConfig(); + + if (userConfig.getPassword() == null || userConfig.getPassword().equals("")) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, + "Password is mandatory."); + } else if (userConfig.getOldPassword() == null || userConfig.getOldPassword().equals("")) { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_PRECONDITION_FAILED, logger, + "Old password is mandatory."); + } else if (authenticationService.contains(userConfig.getId())) { + String id = userConfig.getId(); + if (authenticationService.login(id, userConfig.getOldPassword())) { + authenticationService.register(id, userConfig.getPassword()); + } else { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_UNAUTHORIZED, logger, "Old password is wrong."); + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "User does not exist.", + " User = ", userConfig.getId()); + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + } + } + + @Override + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.setContentType("application/json"); + String[] pathAndQueryString = checkIfItIsACorrectRest(request, response, logger); + + if (pathAndQueryString != null) { + + setServices(); + String pathInfo = pathAndQueryString[ServletLib.PATH_ARRAY_NR]; + + FromJson json = new FromJson(ServletLib.getJsonText(request)); + + if (pathInfo.equals("/")) { + + RestUserConfig userConfig = json.getRestUserConfig(); + String userID = userConfig.getId(); + + if (authenticationService.contains(userID)) { + authenticationService.delete(userID); + } else { + ServletLib + .sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested user does not exist.", + " User = ", userID); + } + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, + "Requested rest path is not available.", " Rest Path = ", request.getPathInfo()); + } + + } else { + ServletLib.sendHTTPErrorAndLogDebug(response, HttpServletResponse.SC_NOT_FOUND, logger, "Requested rest path is not available.", + " Rest Path = ", request.getPathInfo()); + } + } + + private void setServices() { + + this.authenticationService = handleAuthenticationService(null); + } } diff --git a/projects/server/restws/src/main/resources/OSGI-INF/components.xml b/projects/server/restws/src/main/resources/OSGI-INF/components.xml index 44785900..d62c0b19 100644 --- a/projects/server/restws/src/main/resources/OSGI-INF/components.xml +++ b/projects/server/restws/src/main/resources/OSGI-INF/components.xml @@ -1,20 +1,20 @@ - - - - - + + + + + diff --git a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/Constants.java b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/Constants.java index f5c9a53e..9e48850c 100644 --- a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/Constants.java +++ b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/Constants.java @@ -24,17 +24,17 @@ public final class Constants { - public final static double DOUBLE_VALUE = 3.2415; - public final static float FLOAT_VALUE = 3.2415f; - public final static int INTEGER_VALUE = 10513; - public final static int LONG_VALUE = 12345678; - public final static short SHORT_VALUE = 1234; - public final static byte BYTE_VALUE = 123; - public final static boolean BOOLEAN_VALUE = true; - public final static byte[] BYTE_ARRAY_VALUE = { 0, 1, 9, 10, 15, 16, 17, 127, -127, -81, -16, -1 }; - public final static String STRING_VALUE = "TestString"; - public final static Flag TEST_FLAG = Flag.VALID; - public final static long TIMESTAMP = 1417783028138l; - public final static String JSON_OBJECT_BEGIN = "{"; - public final static String JSON_OBJECT_END = "}"; + public final static double DOUBLE_VALUE = 3.2415; + public final static float FLOAT_VALUE = 3.2415f; + public final static int INTEGER_VALUE = 10513; + public final static int LONG_VALUE = 12345678; + public final static short SHORT_VALUE = 1234; + public final static byte BYTE_VALUE = 123; + public final static boolean BOOLEAN_VALUE = true; + public final static byte[] BYTE_ARRAY_VALUE = {0, 1, 9, 10, 15, 16, 17, 127, -127, -81, -16, -1}; + public final static String STRING_VALUE = "TestString"; + public final static Flag TEST_FLAG = Flag.VALID; + public final static long TIMESTAMP = 1417783028138l; + public final static String JSON_OBJECT_BEGIN = "{"; + public final static String JSON_OBJECT_END = "}"; } diff --git a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_fromJson.java b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_fromJson.java index 94f87a35..7c04cbed 100644 --- a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_fromJson.java +++ b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_fromJson.java @@ -20,13 +20,6 @@ */ package org.openmuc.framework.server.restws.test; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; - import org.junit.BeforeClass; import org.junit.Test; import org.openmuc.framework.data.Record; @@ -34,79 +27,84 @@ import org.openmuc.framework.lib.json.Const; import org.openmuc.framework.lib.json.FromJson; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.Set; + +import static org.junit.Assert.assertTrue; + public class TestJsonHelper_fromJson { - private static String stringValueWithTicks = "\"" + Constants.STRING_VALUE + "\""; - - private static String[] sTestJsonValueArray; - private static String sTestRecord; - - @BeforeClass - public static void setup() { - - String testJsonDoubleValue = "\"value\":" + Constants.DOUBLE_VALUE; - String testJsonFloatValue = "\"value\":" + Constants.FLOAT_VALUE; - String testJsonLongValue = "\"value\":" + Constants.LONG_VALUE; - String testJsonIntegerValue = "\"value\":" + Constants.INTEGER_VALUE; - String testJsonShortValue = "\"value\":" + Constants.SHORT_VALUE; - String testJsonByteValue = "\"value\":" + Constants.BYTE_VALUE; - String testJsonBooleanValue = "\"value\":" + Constants.BOOLEAN_VALUE; - String testJsonByteArrayValue = "\"value\":" + Arrays.toString(Constants.BYTE_ARRAY_VALUE); - String testJsonStringValue = "\"value\":" + stringValueWithTicks; - - // ValueType enum: DOUBLE, FLOAT, LONG, INTEGER, SHORT, BYTE, BOOLEAN, BYTE_ARRAY, STRING - String[] testJsonValueArray = { testJsonDoubleValue, testJsonFloatValue, testJsonLongValue, - testJsonIntegerValue, testJsonShortValue, testJsonByteValue, testJsonBooleanValue, - testJsonByteArrayValue, testJsonStringValue }; - - String testRecord = "\"" + Const.RECORD + "\":{\"timestamp\":" + Constants.TIMESTAMP + ",\"flag\":\"" - + Constants.TEST_FLAG.toString() + "\","; - sTestRecord = testRecord; - sTestJsonValueArray = testJsonValueArray; - } - - @Test - public void test_jsonToRecord() { - - boolean result = true; - String testMethodName = "Test_jsonToRecord"; - - Set elements = EnumSet.allOf(ValueType.class); - Iterator it = elements.iterator(); - Record record; - ValueType valueType; - int i = 0; - - while (it.hasNext()) { - - // build json record - valueType = it.next(); - String jsonString = "{" + sTestRecord + sTestJsonValueArray[i] + Constants.JSON_OBJECT_END + '}'; - System.out.println(testMethodName + "; ValueType: " + valueType.toString() + "; JsonString: " + jsonString); - FromJson json = new FromJson(jsonString); - record = json.getRecord(valueType); - - // test JsonHelper response - if (record.getTimestamp() != Constants.TIMESTAMP) { - result = false; - System.out - .println(testMethodName + ": result is \"" + result + "\"; error: Record timestamp is wrong."); - break; - } - if (record.getFlag().compareTo(Constants.TEST_FLAG) != 0) { - result = false; - System.out.println(testMethodName + ": result is \"" + result - + "\"; error: Record flag is wrong. Should be " + Constants.TEST_FLAG + " but is " - + record.getFlag()); - break; - } - result = TestTools.testValue(testMethodName, valueType, record.getValue()); - ++i; - } - if (result) { - System.out.println(testMethodName + ": result is " + result); - } - assertTrue(result); - } + private static String stringValueWithTicks = "\"" + Constants.STRING_VALUE + "\""; + + private static String[] sTestJsonValueArray; + private static String sTestRecord; + + @BeforeClass + public static void setup() { + + String testJsonDoubleValue = "\"value\":" + Constants.DOUBLE_VALUE; + String testJsonFloatValue = "\"value\":" + Constants.FLOAT_VALUE; + String testJsonLongValue = "\"value\":" + Constants.LONG_VALUE; + String testJsonIntegerValue = "\"value\":" + Constants.INTEGER_VALUE; + String testJsonShortValue = "\"value\":" + Constants.SHORT_VALUE; + String testJsonByteValue = "\"value\":" + Constants.BYTE_VALUE; + String testJsonBooleanValue = "\"value\":" + Constants.BOOLEAN_VALUE; + String testJsonByteArrayValue = "\"value\":" + Arrays.toString(Constants.BYTE_ARRAY_VALUE); + String testJsonStringValue = "\"value\":" + stringValueWithTicks; + + // ValueType enum: DOUBLE, FLOAT, LONG, INTEGER, SHORT, BYTE, BOOLEAN, BYTE_ARRAY, STRING + String[] testJsonValueArray = {testJsonDoubleValue, testJsonFloatValue, testJsonLongValue, testJsonIntegerValue, + testJsonShortValue, testJsonByteValue, testJsonBooleanValue, testJsonByteArrayValue, testJsonStringValue}; + + String testRecord = "\"" + Const.RECORD + "\":{\"timestamp\":" + Constants.TIMESTAMP + ",\"flag\":\"" + Constants.TEST_FLAG + .toString() + "\","; + sTestRecord = testRecord; + sTestJsonValueArray = testJsonValueArray; + } + + @Test + public void test_jsonToRecord() { + + boolean result = true; + String testMethodName = "Test_jsonToRecord"; + + Set elements = EnumSet.allOf(ValueType.class); + Iterator it = elements.iterator(); + Record record; + ValueType valueType; + int i = 0; + + while (it.hasNext()) { + + // build json record + valueType = it.next(); + String jsonString = "{" + sTestRecord + sTestJsonValueArray[i] + Constants.JSON_OBJECT_END + '}'; + System.out.println(testMethodName + "; ValueType: " + valueType.toString() + "; JsonString: " + jsonString); + FromJson json = new FromJson(jsonString); + record = json.getRecord(valueType); + + // test JsonHelper response + if (record.getTimestamp() != Constants.TIMESTAMP) { + result = false; + System.out.println(testMethodName + ": result is \"" + result + "\"; error: Record timestamp is wrong."); + break; + } + if (record.getFlag().compareTo(Constants.TEST_FLAG) != 0) { + result = false; + System.out.println( + testMethodName + ": result is \"" + result + "\"; error: Record flag is wrong. Should be " + Constants.TEST_FLAG + " but is " + record + .getFlag()); + break; + } + result = TestTools.testValue(testMethodName, valueType, record.getValue()); + ++i; + } + if (result) { + System.out.println(testMethodName + ": result is " + result); + } + assertTrue(result); + } } diff --git a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_toJson.java b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_toJson.java index 5e54bf6a..fc86e711 100644 --- a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_toJson.java +++ b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestJsonHelper_toJson.java @@ -24,8 +24,8 @@ public class TestJsonHelper_toJson { - @Test - public void test_RecordToJson() { + @Test + public void test_RecordToJson() { - } + } } diff --git a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestSuit.java b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestSuit.java index f20a8765..22601767 100644 --- a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestSuit.java +++ b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestSuit.java @@ -27,16 +27,16 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ TestJsonHelper_fromJson.class /* , TestJsonHelper_toJson.class, /* */}) +@SuiteClasses({TestJsonHelper_fromJson.class /* , TestJsonHelper_toJson.class, /* */}) public class TestSuit { - @BeforeClass - public static void setUp() { - System.out.println("setting up"); - } + @BeforeClass + public static void setUp() { + System.out.println("setting up"); + } - @AfterClass - public static void tearDown() { - System.out.println("tearing down"); - } + @AfterClass + public static void tearDown() { + System.out.println("tearing down"); + } } diff --git a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestTools.java b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestTools.java index 036b9afb..9afb0b21 100644 --- a/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestTools.java +++ b/projects/server/restws/src/test/java/org/openmuc/framework/server/restws/test/TestTools.java @@ -20,114 +20,107 @@ */ package org.openmuc.framework.server.restws.test; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - import org.junit.Assert; import org.openmuc.framework.data.TypeConversionException; import org.openmuc.framework.data.Value; import org.openmuc.framework.data.ValueType; +import java.util.Arrays; + +import static org.junit.Assert.assertTrue; + public class TestTools { - public static boolean testValue(String Test_method, ValueType valueType, Value value) { - boolean result = true; + public static boolean testValue(String Test_method, ValueType valueType, Value value) { + boolean result = true; - if (value == null) { - result = false; - System.out.println(Test_method + ": result is \"" + result + "\"; error: Value is null."); - } - try { - checkValueConversion(valueType, value); - } catch (TypeConversionException e) { - result = false; - System.out.println(Test_method + " result is \"" + result + "\"; error: ValueType is wrong;\n errormsg: " - + e); - } - checkValueValue(Test_method, valueType, value); + if (value == null) { + result = false; + System.out.println(Test_method + ": result is \"" + result + "\"; error: Value is null."); + } + try { + checkValueConversion(valueType, value); + } catch (TypeConversionException e) { + result = false; + System.out.println(Test_method + " result is \"" + result + "\"; error: ValueType is wrong;\n errormsg: " + e); + } + checkValueValue(Test_method, valueType, value); - return result; - } + return result; + } - public static void checkValueConversion(ValueType valueType, Value value) throws TypeConversionException { + public static void checkValueConversion(ValueType valueType, Value value) throws TypeConversionException { - switch (valueType) { - case BOOLEAN: - value.asBoolean(); - break; - case BYTE: - value.asByte(); - break; - case BYTE_ARRAY: - value.asByteArray(); - break; - case DOUBLE: - value.asDouble(); - break; - case FLOAT: - value.asFloat(); - break; - case INTEGER: - value.asInt(); - break; - case LONG: - value.asLong(); - break; - case SHORT: - value.asShort(); - break; - case STRING: - value.asString(); - break; - default: - // should never happen - throw new TypeConversionException("Unknown ValueType"); - } - } + switch (valueType) { + case BOOLEAN: + value.asBoolean(); + break; + case BYTE: + value.asByte(); + break; + case BYTE_ARRAY: + value.asByteArray(); + break; + case DOUBLE: + value.asDouble(); + break; + case FLOAT: + value.asFloat(); + break; + case INTEGER: + value.asInt(); + break; + case LONG: + value.asLong(); + break; + case SHORT: + value.asShort(); + break; + case STRING: + value.asString(); + break; + default: + // should never happen + throw new TypeConversionException("Unknown ValueType"); + } + } - public static void checkValueValue(String Test_method, ValueType valueType, Value value) { + public static void checkValueValue(String Test_method, ValueType valueType, Value value) { - switch (valueType) { - case BOOLEAN: - Assert.assertEquals(Test_method + ": Expected boolean is not equal the actual", Constants.BOOLEAN_VALUE, - value.asBoolean()); - break; - case BYTE: - Assert.assertEquals(Test_method + ": Expected byte is not equal the actual", Constants.BYTE_VALUE, - value.asByte()); - break; - case BYTE_ARRAY: - if (!Arrays.equals(Constants.BYTE_ARRAY_VALUE, value.asByteArray())) { - assertTrue(Test_method + ": Expected byte[] is not equal the actual", false); - } - break; - case DOUBLE: - Assert.assertEquals(Test_method + ": Expected double is not equal the actual", Constants.DOUBLE_VALUE, - value.asDouble(), 0.00001); - break; - case FLOAT: - Assert.assertEquals(Test_method + ": Expected double is not equal the actual", Constants.FLOAT_VALUE, - value.asFloat(), 0.00001); - break; - case INTEGER: - Assert.assertEquals(Test_method + ": Expected int is not equal the actual", Constants.INTEGER_VALUE, - value.asInt()); - break; - case LONG: - Assert.assertEquals(Test_method + ": Expected long is not equal the actual", Constants.LONG_VALUE, - value.asLong()); - break; - case SHORT: - Assert.assertEquals(Test_method + ": Expected short is not equal the actual", Constants.SHORT_VALUE, - value.asShort()); - break; - case STRING: - Assert.assertEquals(Test_method + ": Expected String is not equal the actual", Constants.STRING_VALUE, - value.asString()); - break; - default: - // should never happen - } - } + switch (valueType) { + case BOOLEAN: + Assert.assertEquals(Test_method + ": Expected boolean is not equal the actual", Constants.BOOLEAN_VALUE, value.asBoolean()); + break; + case BYTE: + Assert.assertEquals(Test_method + ": Expected byte is not equal the actual", Constants.BYTE_VALUE, value.asByte()); + break; + case BYTE_ARRAY: + if (!Arrays.equals(Constants.BYTE_ARRAY_VALUE, value.asByteArray())) { + assertTrue(Test_method + ": Expected byte[] is not equal the actual", false); + } + break; + case DOUBLE: + Assert.assertEquals(Test_method + ": Expected double is not equal the actual", Constants.DOUBLE_VALUE, value.asDouble(), + 0.00001); + break; + case FLOAT: + Assert.assertEquals(Test_method + ": Expected double is not equal the actual", Constants.FLOAT_VALUE, value.asFloat(), + 0.00001); + break; + case INTEGER: + Assert.assertEquals(Test_method + ": Expected int is not equal the actual", Constants.INTEGER_VALUE, value.asInt()); + break; + case LONG: + Assert.assertEquals(Test_method + ": Expected long is not equal the actual", Constants.LONG_VALUE, value.asLong()); + break; + case SHORT: + Assert.assertEquals(Test_method + ": Expected short is not equal the actual", Constants.SHORT_VALUE, value.asShort()); + break; + case STRING: + Assert.assertEquals(Test_method + ": Expected String is not equal the actual", Constants.STRING_VALUE, value.asString()); + break; + default: + // should never happen + } + } } diff --git a/projects/webui/base/build.gradle b/projects/webui/base/build.gradle index 2b07b58e..08324452 100644 --- a/projects/webui/base/build.gradle +++ b/projects/webui/base/build.gradle @@ -1,24 +1,24 @@ configurations.create('embed') dependencies { - compile project(':openmuc-core-api') - compile project(':openmuc-webui-spi') - compile group: 'com.google.code.gson', name: 'gson', version: 2.3 - embed group: 'com.google.code.gson', name: 'gson', version: 2.3 + compile project(':openmuc-core-api') + compile project(':openmuc-webui-spi') + compile group: 'com.google.code.gson', name: 'gson', version: 2.3 + embed group: 'com.google.code.gson', name: 'gson', version: 2.3 } jar { - manifest { - name = "OpenMUC WebUI - Base" - instruction 'Bundle-ClassPath', '.,lib/gson-2.3.jar' - instruction 'Import-Package', '!com.google.gson.*,*' - instruction 'Export-Package', '' - instruction 'Service-Component', 'OSGI-INF/components.xml' - } + manifest { + name = "OpenMUC WebUI - Base" + instruction 'Bundle-ClassPath', '.,lib/gson-2.3.jar' + instruction 'Import-Package', '!com.google.gson.*,*' + instruction 'Export-Package', '' + instruction 'Service-Component', 'OSGI-INF/components.xml' + } } jar { - into('lib') { - from configurations.embed - } + into('lib') { + from configurations.embed + } } diff --git a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/Application.java b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/Application.java index 3cd4aaf9..e6459aea 100644 --- a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/Application.java +++ b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/Application.java @@ -22,23 +22,23 @@ public class Application { - private String alias = ""; - private String name = ""; + private String alias = ""; + private String name = ""; - public void setAlias(String alias) { - this.alias = alias; - } + public void setAlias(String alias) { + this.alias = alias; + } - public String getAlias() { - return alias; - } + public String getAlias() { + return alias; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/BundleHttpContext.java b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/BundleHttpContext.java index c1a7df70..2c6d9f31 100644 --- a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/BundleHttpContext.java +++ b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/BundleHttpContext.java @@ -20,79 +20,77 @@ */ package org.openmuc.framework.webui.base; -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.openmuc.framework.authentication.AuthenticationService; import org.osgi.framework.Bundle; import org.osgi.service.http.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + public class BundleHttpContext implements HttpContext { - Bundle contextBundle; - AuthenticationService authService; + Bundle contextBundle; + AuthenticationService authService; - private final static Logger logger = LoggerFactory.getLogger(BundleHttpContext.class); + private final static Logger logger = LoggerFactory.getLogger(BundleHttpContext.class); - public BundleHttpContext(Bundle contextBundle, AuthenticationService authService) { - this.contextBundle = contextBundle; - this.authService = authService; - } + public BundleHttpContext(Bundle contextBundle, AuthenticationService authService) { + this.contextBundle = contextBundle; + this.authService = authService; + } - @Override - public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { - // if (!request.getScheme().equals("https")) { - // response.sendError(HttpServletResponse.SC_FORBIDDEN); - // return false; - // } + @Override + public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { + // if (!request.getScheme().equals("https")) { + // response.sendError(HttpServletResponse.SC_FORBIDDEN); + // return false; + // } - // if (!authenticated(request)) { - // response.setHeader("WWW-Authenticate", "BASIC realm=\"private area\""); - // response.sendError(HttpServletResponse.SC_UNAUTHORIZED); - // return false; - // } + // if (!authenticated(request)) { + // response.setHeader("WWW-Authenticate", "BASIC realm=\"private area\""); + // response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + // return false; + // } - return true; - } + return true; + } - @Override - public URL getResource(String name) { - if (name.startsWith("/media/")) { - File file = new File(System.getProperty("user.dir") + name); - if (!file.canRead()) { - return null; - } - try { - return file.toURI().toURL(); - } catch (MalformedURLException e) { - return null; - } - } - else if (name.startsWith("/conf/webui/")) { - File file = new File(System.getProperty("user.dir") + name + ".conf"); - if (!file.canRead()) { - return null; - } - try { - return file.toURI().toURL(); - } catch (MalformedURLException e) { - return null; - } - } - return contextBundle.getResource(name); + @Override + public URL getResource(String name) { + if (name.startsWith("/media/")) { + File file = new File(System.getProperty("user.dir") + name); + if (!file.canRead()) { + return null; + } + try { + return file.toURI().toURL(); + } catch (MalformedURLException e) { + return null; + } + } else if (name.startsWith("/conf/webui/")) { + File file = new File(System.getProperty("user.dir") + name + ".conf"); + if (!file.canRead()) { + return null; + } + try { + return file.toURI().toURL(); + } catch (MalformedURLException e) { + return null; + } + } + return contextBundle.getResource(name); - } + } - @Override - public String getMimeType(String name) { - return null; - } + @Override + public String getMimeType(String name) { + return null; + } } diff --git a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBase.java b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBase.java index af3c6e11..c14cbfd2 100644 --- a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBase.java +++ b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBase.java @@ -20,10 +20,6 @@ */ package org.openmuc.framework.webui.base; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - import org.openmuc.framework.authentication.AuthenticationService; import org.openmuc.framework.webui.spi.WebUiPluginService; import org.osgi.service.component.ComponentContext; @@ -32,115 +28,119 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + public final class WebUiBase { - private final static Logger logger = LoggerFactory.getLogger(WebUiBase.class); - - final Map pluginsByAlias = new ConcurrentHashMap(); - private volatile HttpService httpService; - private AuthenticationService authService; - - private volatile WebUiBaseServlet servlet; - - protected void activate(ComponentContext context) throws Exception { - logger.info("Activating WebUI Base"); - - servlet = new WebUiBaseServlet(this); - - BundleHttpContext bundleHttpContext = new BundleHttpContext(context.getBundleContext().getBundle(), authService); - - try { - httpService.registerResources("/app", "/app", bundleHttpContext); - httpService.registerResources("/assets", "/assets", bundleHttpContext); - httpService.registerResources("/openmuc/css", "/css", bundleHttpContext); - httpService.registerResources("/openmuc/images", "/images", bundleHttpContext); - httpService.registerResources("/openmuc/html", "/html", bundleHttpContext); - httpService.registerResources("/openmuc/js", "/js", bundleHttpContext); - httpService.registerResources("/media", "/media", bundleHttpContext); - httpService.registerResources("/conf/webui", "/conf/webui", bundleHttpContext); - httpService.registerServlet("/", servlet, null, bundleHttpContext); - } catch (Exception e) { - } - - synchronized (pluginsByAlias) { - for (WebUiPluginService plugin : pluginsByAlias.values()) { - registerResources(plugin); - } - } - - } - - protected void deactivate(ComponentContext context) { - logger.info("Deactivating WebUI Base"); - httpService.unregister("/openmuc"); - httpService.unregister("/openmuc/css"); - httpService.unregister("/openmuc/images"); - httpService.unregister("/openmuc/js"); - httpService.unregister("/js"); - } - - protected void setHttpService(HttpService httpService) { - this.httpService = httpService; - } - - protected void unsetHttpService(HttpService httpService) { - this.httpService = null; - } - - protected void setWebUiPluginService(WebUiPluginService uiPlugin) { - - synchronized (pluginsByAlias) { - if (!pluginsByAlias.containsValue(uiPlugin)) { - pluginsByAlias.put(uiPlugin.getAlias(), uiPlugin); - registerResources(uiPlugin); - } - } - logger.info("WebUI plugin registered: " + uiPlugin.getName()); - } - - protected void unsetWebUiPluginService(WebUiPluginService uiPlugin) { - unregisterResources(uiPlugin); - pluginsByAlias.remove(uiPlugin.getAlias()); - logger.info("WebUI plugin deregistered: " + uiPlugin.getName()); - } - - protected void setAuthenticationService(AuthenticationService authService) { - this.authService = authService; - } - - protected void unsetAuthenticationService(AuthenticationService authService) { - this.authService = null; - } - - private void registerResources(WebUiPluginService plugin) { - if (servlet != null && httpService != null) { - - BundleHttpContext bundleHttpContext = new BundleHttpContext(plugin.getContextBundle(), authService); - - Set aliases = plugin.getResources().keySet(); - for (String alias : aliases) { - try { - - httpService.registerResources("/" + plugin.getAlias() + "/" + alias, - plugin.getResources().get(alias), bundleHttpContext); - - } catch (NamespaceException e) { - logger.error("Servlet with alias \"/" + plugin.getAlias() + "/" + alias + "\" already registered"); - } - } - } - } - - private void unregisterResources(WebUiPluginService plugin) { - Set aliases = plugin.getResources().keySet(); - - for (String alias : aliases) { - httpService.unregister("/" + plugin.getAlias() + "/" + alias); - } - } - - public AuthenticationService getAuthenticationService() { - return authService; - } + private final static Logger logger = LoggerFactory.getLogger(WebUiBase.class); + + final Map pluginsByAlias = new ConcurrentHashMap(); + private volatile HttpService httpService; + private AuthenticationService authService; + + private volatile WebUiBaseServlet servlet; + + protected void activate(ComponentContext context) throws Exception { + logger.info("Activating WebUI Base"); + + servlet = new WebUiBaseServlet(this); + + BundleHttpContext bundleHttpContext = new BundleHttpContext(context.getBundleContext().getBundle(), authService); + + try { + httpService.registerResources("/app", "/app", bundleHttpContext); + httpService.registerResources("/assets", "/assets", bundleHttpContext); + httpService.registerResources("/openmuc/css", "/css", bundleHttpContext); + httpService.registerResources("/openmuc/images", "/images", bundleHttpContext); + httpService.registerResources("/openmuc/html", "/html", bundleHttpContext); + httpService.registerResources("/openmuc/js", "/js", bundleHttpContext); + httpService.registerResources("/media", "/media", bundleHttpContext); + httpService.registerResources("/conf/webui", "/conf/webui", bundleHttpContext); + httpService.registerServlet("/", servlet, null, bundleHttpContext); + } catch (Exception e) { + } + + synchronized (pluginsByAlias) { + for (WebUiPluginService plugin : pluginsByAlias.values()) { + registerResources(plugin); + } + } + + } + + protected void deactivate(ComponentContext context) { + logger.info("Deactivating WebUI Base"); + httpService.unregister("/openmuc"); + httpService.unregister("/openmuc/css"); + httpService.unregister("/openmuc/images"); + httpService.unregister("/openmuc/js"); + httpService.unregister("/js"); + } + + protected void setHttpService(HttpService httpService) { + this.httpService = httpService; + } + + protected void unsetHttpService(HttpService httpService) { + this.httpService = null; + } + + protected void setWebUiPluginService(WebUiPluginService uiPlugin) { + + synchronized (pluginsByAlias) { + if (!pluginsByAlias.containsValue(uiPlugin)) { + pluginsByAlias.put(uiPlugin.getAlias(), uiPlugin); + registerResources(uiPlugin); + } + } + logger.info("WebUI plugin registered: " + uiPlugin.getName()); + } + + protected void unsetWebUiPluginService(WebUiPluginService uiPlugin) { + unregisterResources(uiPlugin); + pluginsByAlias.remove(uiPlugin.getAlias()); + logger.info("WebUI plugin deregistered: " + uiPlugin.getName()); + } + + protected void setAuthenticationService(AuthenticationService authService) { + this.authService = authService; + } + + protected void unsetAuthenticationService(AuthenticationService authService) { + this.authService = null; + } + + private void registerResources(WebUiPluginService plugin) { + if (servlet != null && httpService != null) { + + BundleHttpContext bundleHttpContext = new BundleHttpContext(plugin.getContextBundle(), authService); + + Set aliases = plugin.getResources().keySet(); + for (String alias : aliases) { + try { + + httpService + .registerResources("/" + plugin.getAlias() + "/" + alias, plugin.getResources().get(alias), bundleHttpContext); + + } catch (NamespaceException e) { + logger.error("Servlet with alias \"/" + plugin.getAlias() + "/" + alias + "\" already registered"); + } + } + } + } + + private void unregisterResources(WebUiPluginService plugin) { + Set aliases = plugin.getResources().keySet(); + + for (String alias : aliases) { + httpService.unregister("/" + plugin.getAlias() + "/" + alias); + } + } + + public AuthenticationService getAuthenticationService() { + return authService; + } } diff --git a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBaseServlet.java b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBaseServlet.java index 22afaa0f..cdf0fc2a 100644 --- a/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBaseServlet.java +++ b/projects/webui/base/src/main/java/org/openmuc/framework/webui/base/WebUiBaseServlet.java @@ -20,149 +20,145 @@ */ package org.openmuc.framework.webui.base; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.openmuc.framework.authentication.AuthenticationService; +import org.openmuc.framework.webui.spi.WebUiPluginService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; - -import org.openmuc.framework.authentication.AuthenticationService; -import org.openmuc.framework.webui.spi.WebUiPluginService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; @SuppressWarnings("serial") public final class WebUiBaseServlet extends HttpServlet { - private final static Logger logger = LoggerFactory.getLogger(WebUiBaseServlet.class); - - private static final int SESSION_TIMEOUT = 300; - - private final WebUiBase webUiBase; - - private final static Gson gson = new Gson(); - - public WebUiBaseServlet(WebUiBase webUiBase) { - this.webUiBase = webUiBase; - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - if (req.getPathInfo().equals("/applications")) { - - if (req.getSession().isNew()) { - req.getSession().invalidate(); - resp.sendError(401); - return; - } - - List applications = new ArrayList(); - for (WebUiPluginService webUiApplication : webUiBase.pluginsByAlias.values()) { - Application application = new Application(); - application.setAlias(webUiApplication.getAlias()); - application.setName(webUiApplication.getName()); - applications.add(application); - } - Type typeOfSrc = new TypeToken>() { - }.getType(); - logger.info(gson.toJsonTree(applications, typeOfSrc).toString()); - resp.getWriter().println(gson.toJsonTree(applications, typeOfSrc)); - return; - } - - InputStream inputStream = getServletContext().getResourceAsStream("page.html"); - OutputStream outputStream = resp.getOutputStream(); - - copyStream(inputStream, outputStream); - - outputStream.close(); - inputStream.close(); - - } - - public static void copyStream(InputStream input, OutputStream output) throws IOException { - byte[] buffer = new byte[1024]; // Adjust if you want - int bytesRead; - while ((bytesRead = input.read(buffer)) != -1) { - output.write(buffer, 0, bytesRead); - } - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (req.getPathInfo().equals("/login")) { - String user = req.getParameter("user"); - String pwd = req.getParameter("pwd"); - - AuthenticationService auth = webUiBase.getAuthenticationService(); - if (auth.login(user, pwd)) { - - HttpSession session = req.getSession(true); // create a new session - session.setMaxInactiveInterval(SESSION_TIMEOUT); // and set timeout - session.putValue("user", user); - } - else { - logger.info("login failed!"); - req.getSession().invalidate(); // invalidate the session - resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); - } - - // String redirect = req.getParameter("redirect"); - // if (redirect.contains("logout")) { - // redirect = "/openmuc"; - // } - // resp.sendRedirect(redirect); - } - // else if (req.getPathInfo().equals("/account")) { - // AuthenticationService auth = webUiBase.getAuthenticationService(); - // String user = (String) req.getSession().getValue("user"); - // String pwd = req.getParameter("pwd"); - // logger.info(user + " is trying to change his account..."); - // if (auth.login(user, pwd)) { - // if (req.getParameter("change").equals("pwd")) { - // String newPwd = req.getParameter("newPwd"); - // String rePwd = req.getParameter("rePwd"); - // if (newPwd.equals(rePwd)) { - // auth.delete(user); - // auth.register(user, newPwd); - // logger.info("succeeded! (Password changed)"); - // } - // else { - // logger.info("failed! (Password mismatch)"); - // } - // } - // else if (req.getParameter("change").equals("user")) { - // String newUser = req.getParameter("newUser"); - // if (!newUser.equals("") && !auth.contains(newUser) && !newUser.contains(":")) { - // auth.delete(user); - // auth.register(newUser, pwd); - // req.getSession().putValue("user", newUser); - // logger.info("suceeded! (Username changed to " + newUser + ")\n"); - // } - // else { - // logger.info("failed! (Username could not be changed)\n"); - // } - // } - // } - // else { - // logger.info("failed! (Login failed)\n"); - // } - // resp.sendRedirect(req.getRequestURI()); - // } - else { - doGet(req, resp); - } - - } + private final static Logger logger = LoggerFactory.getLogger(WebUiBaseServlet.class); + + private static final int SESSION_TIMEOUT = 300; + + private final WebUiBase webUiBase; + + private final static Gson gson = new Gson(); + + public WebUiBaseServlet(WebUiBase webUiBase) { + this.webUiBase = webUiBase; + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + if (req.getPathInfo().equals("/applications")) { + + if (req.getSession().isNew()) { + req.getSession().invalidate(); + resp.sendError(401); + return; + } + + List applications = new ArrayList(); + for (WebUiPluginService webUiApplication : webUiBase.pluginsByAlias.values()) { + Application application = new Application(); + application.setAlias(webUiApplication.getAlias()); + application.setName(webUiApplication.getName()); + applications.add(application); + } + Type typeOfSrc = new TypeToken>() {}.getType(); + logger.info(gson.toJsonTree(applications, typeOfSrc).toString()); + resp.getWriter().println(gson.toJsonTree(applications, typeOfSrc)); + return; + } + + InputStream inputStream = getServletContext().getResourceAsStream("page.html"); + OutputStream outputStream = resp.getOutputStream(); + + copyStream(inputStream, outputStream); + + outputStream.close(); + inputStream.close(); + + } + + public static void copyStream(InputStream input, OutputStream output) throws IOException { + byte[] buffer = new byte[1024]; // Adjust if you want + int bytesRead; + while ((bytesRead = input.read(buffer)) != -1) { + output.write(buffer, 0, bytesRead); + } + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getPathInfo().equals("/login")) { + String user = req.getParameter("user"); + String pwd = req.getParameter("pwd"); + + AuthenticationService auth = webUiBase.getAuthenticationService(); + if (auth.login(user, pwd)) { + + HttpSession session = req.getSession(true); // create a new session + session.setMaxInactiveInterval(SESSION_TIMEOUT); // and set timeout + session.putValue("user", user); + } else { + logger.info("login failed!"); + req.getSession().invalidate(); // invalidate the session + resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } + + // String redirect = req.getParameter("redirect"); + // if (redirect.contains("logout")) { + // redirect = "/openmuc"; + // } + // resp.sendRedirect(redirect); + } + // else if (req.getPathInfo().equals("/account")) { + // AuthenticationService auth = webUiBase.getAuthenticationService(); + // String user = (String) req.getSession().getValue("user"); + // String pwd = req.getParameter("pwd"); + // logger.info(user + " is trying to change his account..."); + // if (auth.login(user, pwd)) { + // if (req.getParameter("change").equals("pwd")) { + // String newPwd = req.getParameter("newPwd"); + // String rePwd = req.getParameter("rePwd"); + // if (newPwd.equals(rePwd)) { + // auth.delete(user); + // auth.register(user, newPwd); + // logger.info("succeeded! (Password changed)"); + // } + // else { + // logger.info("failed! (Password mismatch)"); + // } + // } + // else if (req.getParameter("change").equals("user")) { + // String newUser = req.getParameter("newUser"); + // if (!newUser.equals("") && !auth.contains(newUser) && !newUser.contains(":")) { + // auth.delete(user); + // auth.register(newUser, pwd); + // req.getSession().putValue("user", newUser); + // logger.info("suceeded! (Username changed to " + newUser + ")\n"); + // } + // else { + // logger.info("failed! (Username could not be changed)\n"); + // } + // } + // } + // else { + // logger.info("failed! (Login failed)\n"); + // } + // resp.sendRedirect(req.getRequestURI()); + // } + else { + doGet(req, resp); + } + + } } diff --git a/projects/webui/base/src/main/resources/OSGI-INF/components.xml b/projects/webui/base/src/main/resources/OSGI-INF/components.xml index 51cf685e..af0d8b5b 100644 --- a/projects/webui/base/src/main/resources/OSGI-INF/components.xml +++ b/projects/webui/base/src/main/resources/OSGI-INF/components.xml @@ -1,21 +1,21 @@ - - - - + + + + diff --git a/projects/webui/base/src/main/resources/css/dashboard/dashboard.css b/projects/webui/base/src/main/resources/css/dashboard/dashboard.css index 041b2506..73812333 100644 --- a/projects/webui/base/src/main/resources/css/dashboard/dashboard.css +++ b/projects/webui/base/src/main/resources/css/dashboard/dashboard.css @@ -1,20 +1,20 @@ #dashboard-grid { - margin-bottom: 30px; + margin-bottom: 30px; } #dashboard-grid .item { - margin-bottom: 20px; + margin-bottom: 20px; } #dashboard-grid .item .item-label { - display: block; - padding: 10px 15px 20px 15px; - font-weight: bold; + display: block; + padding: 10px 15px 20px 15px; + font-weight: bold; } #dashboard-grid .item .item-icon { - display: block; - font-size: 36px; - padding-bottom: 15px; - color: #00947a; + display: block; + font-size: 36px; + padding-bottom: 15px; + color: #00947a; } \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/helpers/helper.css b/projects/webui/base/src/main/resources/css/helpers/helper.css index 0106cb37..08c40d56 100644 --- a/projects/webui/base/src/main/resources/css/helpers/helper.css +++ b/projects/webui/base/src/main/resources/css/helpers/helper.css @@ -1,103 +1,110 @@ /* OVERWRITE MAIN LINK COLOR */ -a {color:#009474} -a:hover,a:focus{color:#006956} +a { + color: #009474 +} + +a:hover, a:focus { + color: #006956 +} /* PAGE HEADER */ @media (min-width: 768px) { - .page-header { - margin: 40px 0px 25px; - padding-bottom: 0px; - } + .page-header { + margin: 40px 0px 25px; + padding-bottom: 0px; + } } /* TABS */ @media (max-width: 768px) { - .nav-tabs > li { - float:none; - } - - .nav-tabs>li.active>a, .nav-tabs>li.active>a:hover, .nav-tabs>li.active>a:focus { - border-left: 1px solid #ddd; - border-top: none; - border-right: none; - border-radius: 0px; - } + .nav-tabs > li { + float: none; + } + + .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus { + border-left: 1px solid #ddd; + border-top: none; + border-right: none; + border-radius: 0px; + } } .nav.nav-tabs { - margin-bottom: 20px; + margin-bottom: 20px; } /* NOTIFICATION ALERTS */ .alert.ng-scope.top-right { - -webkit-box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.3); - -moz-box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.3); - box-shadow: 2px 2px 2px 0px rgba(0,0,0,0.3); + -webkit-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, 0.3); + box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, 0.3); } .alert.ng-scope.top-right .close { - margin-left: 10px; + margin-left: 10px; } /* LISTS */ .indent-item { - margin-left: 20px; + margin-left: 20px; } /* FORMS */ -@media (min-width:768px){ - .form-horizontal .control-label { - text-align:left; - } +@media (min-width: 768px) { + .form-horizontal .control-label { + text-align: left; + } } .form-group .glyphicon-info-sign { - margin-right: 2px; - color: #07947A; + margin-right: 2px; + color: #07947A; } .help-block { - font-size: 13px; + font-size: 13px; } /* ALERTS */ .alert-primary { - color: #00947a; - background-color: #E3F0EE; - border-color: #D0DFDC; + color: #00947a; + background-color: #E3F0EE; + border-color: #D0DFDC; } .alert.alert-sm { - padding: 10px 15px; + padding: 10px 15px; } /* PANELS */ .panel-link-heading { - display: block; - cursor: pointer; - margin-bottom: 10px; + display: block; + cursor: pointer; + margin-bottom: 10px; } /* BUTTONS */ .btn-primary { - background-color: #009474; - border-color: #009474; + background-color: #009474; + border-color: #009474; } + .btn-primary[disabled], .btn-primary[disabled]:hover, .btn-primary[disabled]:focus { - background-color: #009474; - border-color: #009474; + background-color: #009474; + border-color: #009474; } + .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, @@ -105,45 +112,46 @@ a:hover,a:focus{color:#006956} .btn-primary.active, .btn-primary.open, .open > .dropdown-toggle.btn-primary { - background-color: #00816A; - border-color: #00816A; + background-color: #00816A; + border-color: #00816A; } .btn-grid { - background-color: #F3F3F3; - border-color: #E5E5E5; - padding: 20px; - font-weight: bold; - color: #333; + background-color: #F3F3F3; + border-color: #E5E5E5; + padding: 20px; + font-weight: bold; + color: #333; } + .btn-grid:hover, .btn-grid:focus, .btn-grid.focus, .btn-grid:active, .btn-grid.active, .open > .dropdown-toggle.btn-grid { - background-color: #FAFAFA; - border-color: #83b8af; + background-color: #FAFAFA; + border-color: #83b8af; } /* ASIDE */ .aside .aside-dialog .aside-header { - background: #009474; + background: #009474; } /* PAGE HEADER */ @media (max-width: 768px) { - .page-header { - margin-top: 20px; - } + .page-header { + margin-top: 20px; + } } .dropdown-toggle { - cursor: pointer; + cursor: pointer; } -.display-block{ - display: block; +.display-block { + display: block; } \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/libs/angularjs/angular-motion.css b/projects/webui/base/src/main/resources/css/libs/angularjs/angular-motion.css index aec50504..d9005bf6 100644 --- a/projects/webui/base/src/main/resources/css/libs/angularjs/angular-motion.css +++ b/projects/webui/base/src/main/resources/css/libs/angularjs/angular-motion.css @@ -6,1021 +6,1162 @@ * @license MIT License, http://www.opensource.org/licenses/MIT */ .am-collapse { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease; - animation-timing-function: ease; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; - opacity: 1; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease; + animation-timing-function: ease; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; + opacity: 1; } + .am-collapse.am-collapse-add, .am-collapse.ng-hide-remove, .am-collapse.ng-move { - -webkit-animation-name: expand; - animation-name: expand; + -webkit-animation-name: expand; + animation-name: expand; } + .am-collapse.am-collapse-remove, .am-collapse.ng-hide { - -webkit-animation-name: collapse; - animation-name: collapse; + -webkit-animation-name: collapse; + animation-name: collapse; } + .am-collapse.ng-enter { - visibility: hidden; - -webkit-animation-name: expand; - animation-name: expand; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: expand; + animation-name: expand; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-collapse.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-collapse.ng-leave { - -webkit-animation-name: collapse; - animation-name: collapse; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: collapse; + animation-name: collapse; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-collapse.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes expand { - from { - max-height: 0px; - } - to { - max-height: 500px; - } + from { + max-height: 0px; + } + to { + max-height: 500px; + } } + @keyframes expand { - from { - max-height: 0px; - } - to { - max-height: 500px; - } + from { + max-height: 0px; + } + to { + max-height: 500px; + } } + @-webkit-keyframes collapse { - from { - max-height: 500px; - } - to { - max-height: 0px; - } + from { + max-height: 500px; + } + to { + max-height: 0px; + } } + @keyframes collapse { - from { - max-height: 500px; - } - to { - max-height: 0px; - } + from { + max-height: 500px; + } + to { + max-height: 0px; + } } + .panel-collapse.am-collapse.in-remove { - -webkit-animation-name: collapse; - animation-name: collapse; - display: block; + -webkit-animation-name: collapse; + animation-name: collapse; + display: block; } + .panel-collapse.am-collapse.in-add { - -webkit-animation-name: expand; - animation-name: expand; + -webkit-animation-name: expand; + animation-name: expand; } .am-fade-and-scale { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-fade-and-scale.ng-enter, .am-fade-and-scale.am-fade-and-scale-add, .am-fade-and-scale.ng-hide-remove, .am-fade-and-scale.ng-move { - -webkit-animation-name: fadeAndScaleIn; - animation-name: fadeAndScaleIn; + -webkit-animation-name: fadeAndScaleIn; + animation-name: fadeAndScaleIn; } + .am-fade-and-scale.ng-leave, .am-fade-and-scale.am-fade-and-scale-remove, .am-fade-and-scale.ng-hide { - -webkit-animation-name: fadeAndScaleOut; - animation-name: fadeAndScaleOut; + -webkit-animation-name: fadeAndScaleOut; + animation-name: fadeAndScaleOut; } + .am-fade-and-scale.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeAndScaleIn; - animation-name: fadeAndScaleIn; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeAndScaleIn; + animation-name: fadeAndScaleIn; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-scale.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-scale.ng-leave { - -webkit-animation-name: fadeAndScaleOut; - animation-name: fadeAndScaleOut; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeAndScaleOut; + animation-name: fadeAndScaleOut; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-scale.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes fadeAndScaleIn { - from { - opacity: 0; - -webkit-transform: scale(0.7); - transform: scale(0.7); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: scale(0.7); + transform: scale(0.7); + } + to { + opacity: 1; + } } + @keyframes fadeAndScaleIn { - from { - opacity: 0; - -webkit-transform: scale(0.7); - transform: scale(0.7); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: scale(0.7); + transform: scale(0.7); + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeAndScaleOut { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: scale(0.7); - transform: scale(0.7); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: scale(0.7); + transform: scale(0.7); + } } + @keyframes fadeAndScaleOut { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: scale(0.7); - transform: scale(0.7); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: scale(0.7); + transform: scale(0.7); + } } .am-fade-and-slide-top { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-fade-and-slide-top.am-fade-and-slide-top-add, .am-fade-and-slide-top.ng-hide-remove, .am-fade-and-slide-top.ng-move { - -webkit-animation-name: fadeAndSlideFromTop; - animation-name: fadeAndSlideFromTop; + -webkit-animation-name: fadeAndSlideFromTop; + animation-name: fadeAndSlideFromTop; } + .am-fade-and-slide-top.am-fade-and-slide-top-remove, .am-fade-and-slide-top.ng-hide { - -webkit-animation-name: fadeAndSlideToTop; - animation-name: fadeAndSlideToTop; + -webkit-animation-name: fadeAndSlideToTop; + animation-name: fadeAndSlideToTop; } + .am-fade-and-slide-top.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeAndSlideFromTop; - animation-name: fadeAndSlideFromTop; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeAndSlideFromTop; + animation-name: fadeAndSlideFromTop; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-top.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-top.ng-leave { - -webkit-animation-name: fadeAndSlideToTop; - animation-name: fadeAndSlideToTop; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeAndSlideToTop; + animation-name: fadeAndSlideToTop; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-top.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-right { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-fade-and-slide-right.am-fade-and-slide-right-add, .am-fade-and-slide-right.ng-hide-remove, .am-fade-and-slide-right.ng-move { - -webkit-animation-name: fadeAndSlideFromRight; - animation-name: fadeAndSlideFromRight; + -webkit-animation-name: fadeAndSlideFromRight; + animation-name: fadeAndSlideFromRight; } + .am-fade-and-slide-right.am-fade-and-slide-right-remove, .am-fade-and-slide-right.ng-hide { - -webkit-animation-name: fadeAndSlideToRight; - animation-name: fadeAndSlideToRight; + -webkit-animation-name: fadeAndSlideToRight; + animation-name: fadeAndSlideToRight; } + .am-fade-and-slide-right.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeAndSlideFromRight; - animation-name: fadeAndSlideFromRight; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeAndSlideFromRight; + animation-name: fadeAndSlideFromRight; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-right.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-right.ng-leave { - -webkit-animation-name: fadeAndSlideToRight; - animation-name: fadeAndSlideToRight; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeAndSlideToRight; + animation-name: fadeAndSlideToRight; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-right.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-bottom { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-fade-and-slide-bottom.am-fade-and-slide-bottom-add, .am-fade-and-slide-bottom.ng-hide-remove, .am-fade-and-slide-bottom.ng-move { - -webkit-animation-name: fadeAndSlideFromBottom; - animation-name: fadeAndSlideFromBottom; + -webkit-animation-name: fadeAndSlideFromBottom; + animation-name: fadeAndSlideFromBottom; } + .am-fade-and-slide-bottom.am-fade-and-slide-bottom-remove, .am-fade-and-slide-bottom.ng-hide { - -webkit-animation-name: fadeAndSlideToBottom; - animation-name: fadeAndSlideToBottom; + -webkit-animation-name: fadeAndSlideToBottom; + animation-name: fadeAndSlideToBottom; } + .am-fade-and-slide-bottom.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeAndSlideFromBottom; - animation-name: fadeAndSlideFromBottom; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeAndSlideFromBottom; + animation-name: fadeAndSlideFromBottom; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-bottom.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-bottom.ng-leave { - -webkit-animation-name: fadeAndSlideToBottom; - animation-name: fadeAndSlideToBottom; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeAndSlideToBottom; + animation-name: fadeAndSlideToBottom; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-bottom.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-left { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-fade-and-slide-left.am-fade-and-slide-left-add, .am-fade-and-slide-left.ng-hide-remove, .am-fade-and-slide-left.ng-move { - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; - -webkit-animation-name: fadeAndSlideFromLeft; - animation-name: fadeAndSlideFromLeft; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; + -webkit-animation-name: fadeAndSlideFromLeft; + animation-name: fadeAndSlideFromLeft; } + .am-fade-and-slide-left.am-fade-and-slide-left-remove, .am-fade-and-slide-left.ng-hide { - -webkit-animation-name: fadeAndSlideToLeft; - animation-name: fadeAndSlideToLeft; + -webkit-animation-name: fadeAndSlideToLeft; + animation-name: fadeAndSlideToLeft; } + .am-fade-and-slide-left.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeAndSlideFromLeft; - animation-name: fadeAndSlideFromLeft; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeAndSlideFromLeft; + animation-name: fadeAndSlideFromLeft; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-left.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade-and-slide-left.ng-leave { - -webkit-animation-name: fadeAndSlideToLeft; - animation-name: fadeAndSlideToLeft; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeAndSlideToLeft; + animation-name: fadeAndSlideToLeft; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade-and-slide-left.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes fadeAndSlideFromTop { - from { - opacity: 0; - -webkit-transform: translateY(-20%); - transform: translateY(-20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateY(-20%); + transform: translateY(-20%); + } + to { + opacity: 1; + } } + @keyframes fadeAndSlideFromTop { - from { - opacity: 0; - -webkit-transform: translateY(-20%); - transform: translateY(-20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateY(-20%); + transform: translateY(-20%); + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeAndSlideToTop { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateY(-20%); - transform: translateY(-20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateY(-20%); + transform: translateY(-20%); + } } + @keyframes fadeAndSlideToTop { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateY(-20%); - transform: translateY(-20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateY(-20%); + transform: translateY(-20%); + } } + @-webkit-keyframes fadeAndSlideFromRight { - from { - opacity: 0; - -webkit-transform: translateX(20%); - transform: translateX(20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateX(20%); + transform: translateX(20%); + } + to { + opacity: 1; + } } + @keyframes fadeAndSlideFromRight { - from { - opacity: 0; - -webkit-transform: translateX(20%); - transform: translateX(20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateX(20%); + transform: translateX(20%); + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeAndSlideToRight { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateX(20%); - transform: translateX(20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateX(20%); + transform: translateX(20%); + } } + @keyframes fadeAndSlideToRight { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateX(20%); - transform: translateX(20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateX(20%); + transform: translateX(20%); + } } + @-webkit-keyframes fadeAndSlideFromBottom { - from { - opacity: 0; - -webkit-transform: translateY(20%); - transform: translateY(20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateY(20%); + transform: translateY(20%); + } + to { + opacity: 1; + } } + @keyframes fadeAndSlideFromBottom { - from { - opacity: 0; - -webkit-transform: translateY(20%); - transform: translateY(20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateY(20%); + transform: translateY(20%); + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeAndSlideToBottom { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateY(20%); - transform: translateY(20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateY(20%); + transform: translateY(20%); + } } + @keyframes fadeAndSlideToBottom { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateY(20%); - transform: translateY(20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateY(20%); + transform: translateY(20%); + } } + @-webkit-keyframes fadeAndSlideFromLeft { - from { - opacity: 0; - -webkit-transform: translateX(-20%); - transform: translateX(-20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateX(-20%); + transform: translateX(-20%); + } + to { + opacity: 1; + } } + @keyframes fadeAndSlideFromLeft { - from { - opacity: 0; - -webkit-transform: translateX(-20%); - transform: translateX(-20%); - } - to { - opacity: 1; - } + from { + opacity: 0; + -webkit-transform: translateX(-20%); + transform: translateX(-20%); + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeAndSlideToLeft { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateX(-20%); - transform: translateX(-20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateX(-20%); + transform: translateX(-20%); + } } + @keyframes fadeAndSlideToLeft { - from { - opacity: 1; - } - to { - opacity: 0; - -webkit-transform: translateX(-20%); - transform: translateX(-20%); - } + from { + opacity: 1; + } + to { + opacity: 0; + -webkit-transform: translateX(-20%); + transform: translateX(-20%); + } } .am-fade { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: linear; - animation-timing-function: linear; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; - opacity: 1; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: linear; + animation-timing-function: linear; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; + opacity: 1; } + .am-fade.am-fade-add, .am-fade.ng-hide-remove, .am-fade.ng-move { - -webkit-animation-name: fadeIn; - animation-name: fadeIn; + -webkit-animation-name: fadeIn; + animation-name: fadeIn; } + .am-fade.am-fade-remove, .am-fade.ng-hide { - -webkit-animation-name: fadeOut; - animation-name: fadeOut; + -webkit-animation-name: fadeOut; + animation-name: fadeOut; } + .am-fade.ng-enter { - visibility: hidden; - -webkit-animation-name: fadeIn; - animation-name: fadeIn; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: fadeIn; + animation-name: fadeIn; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-fade.ng-leave { - -webkit-animation-name: fadeOut; - animation-name: fadeOut; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: fadeOut; + animation-name: fadeOut; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-fade.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes fadeIn { - from { - opacity: 0; - } - to { - opacity: 1; - } + from { + opacity: 0; + } + to { + opacity: 1; + } } + @keyframes fadeIn { - from { - opacity: 0; - } - to { - opacity: 1; - } + from { + opacity: 0; + } + to { + opacity: 1; + } } + @-webkit-keyframes fadeOut { - from { - opacity: 1; - } - to { - opacity: 0; - } + from { + opacity: 1; + } + to { + opacity: 0; + } } + @keyframes fadeOut { - from { - opacity: 1; - } - to { - opacity: 0; - } + from { + opacity: 1; + } + to { + opacity: 0; + } } + .tab-pane.am-fade.active-remove { - display: none !important; + display: none !important; } + .tab-pane.am-fade.active-add { - -webkit-animation-name: fadeIn; - animation-name: fadeIn; + -webkit-animation-name: fadeIn; + animation-name: fadeIn; } + .modal-backdrop.am-fade, .aside-backdrop.am-fade { - background: rgba(0, 0, 0, 0.5); - -webkit-animation-duration: 0.15s; - animation-duration: 0.15s; + background: rgba(0, 0, 0, 0.5); + -webkit-animation-duration: 0.15s; + animation-duration: 0.15s; } + .modal-backdrop.am-fade.ng-leave, .aside-backdrop.am-fade.ng-leave { - -webkit-animation-delay: 0.3s; - animation-delay: 0.3s; + -webkit-animation-delay: 0.3s; + animation-delay: 0.3s; } .am-flip-x { - -webkit-animation-duration: 0.4s; - animation-duration: 0.4s; - -webkit-animation-timing-function: ease; - animation-timing-function: ease; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.4s; + animation-duration: 0.4s; + -webkit-animation-timing-function: ease; + animation-timing-function: ease; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-flip-x.am-flip-x-add, .am-flip-x.ng-hide-remove, .am-flip-x.ng-move { - -webkit-animation-name: flipInXBounce; - animation-name: flipInXBounce; + -webkit-animation-name: flipInXBounce; + animation-name: flipInXBounce; } + .am-flip-x.am-flip-x-remove, .am-flip-x.ng-hide { - -webkit-animation-name: flipOutX; - animation-name: flipOutX; + -webkit-animation-name: flipOutX; + animation-name: flipOutX; } + .am-flip-x.ng-enter { - visibility: hidden; - -webkit-animation-name: flipInXBounce; - animation-name: flipInXBounce; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: flipInXBounce; + animation-name: flipInXBounce; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-flip-x.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-flip-x.ng-leave { - -webkit-animation-name: flipOutX; - animation-name: flipOutX; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: flipOutX; + animation-name: flipOutX; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-flip-x.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-flip-x-linear { - -webkit-animation-duration: 0.4s; - animation-duration: 0.4s; - -webkit-animation-timing-function: ease; - animation-timing-function: ease; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.4s; + animation-duration: 0.4s; + -webkit-animation-timing-function: ease; + animation-timing-function: ease; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-flip-x-linear.am-flip-x-add, .am-flip-x-linear.ng-hide-remove, .am-flip-x-linear.ng-move { - -webkit-animation-name: flipInX; - animation-name: flipInX; + -webkit-animation-name: flipInX; + animation-name: flipInX; } + .am-flip-x-linear.am-flip-x-remove, .am-flip-x-linear.ng-hide { - -webkit-animation-name: flipOutX; - animation-name: flipOutX; + -webkit-animation-name: flipOutX; + animation-name: flipOutX; } + .am-flip-x-linear.ng-enter { - visibility: hidden; - -webkit-animation-name: flipInX; - animation-name: flipInX; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: flipInX; + animation-name: flipInX; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-flip-x-linear.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-flip-x-linear.ng-leave { - -webkit-animation-name: flipOutX; - animation-name: flipOutX; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: flipOutX; + animation-name: flipOutX; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-flip-x-linear.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes flipInX { - from { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } - to { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } + from { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } + to { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } } + @keyframes flipInX { - from { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } - to { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } + from { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } + to { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } } + @-webkit-keyframes flipInXBounce { - from { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } - 40% { - -webkit-transform: perspective(400px) rotateX(-10deg); - transform: perspective(400px) rotateX(-10deg); - } - 70% { - -webkit-transform: perspective(400px) rotateX(10deg); - transform: perspective(400px) rotateX(10deg); - } - to { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } + from { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } + 40% { + -webkit-transform: perspective(400px) rotateX(-10deg); + transform: perspective(400px) rotateX(-10deg); + } + 70% { + -webkit-transform: perspective(400px) rotateX(10deg); + transform: perspective(400px) rotateX(10deg); + } + to { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } } + @keyframes flipInXBounce { - from { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } - 40% { - -webkit-transform: perspective(400px) rotateX(-10deg); - transform: perspective(400px) rotateX(-10deg); - } - 70% { - -webkit-transform: perspective(400px) rotateX(10deg); - transform: perspective(400px) rotateX(10deg); - } - to { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } + from { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } + 40% { + -webkit-transform: perspective(400px) rotateX(-10deg); + transform: perspective(400px) rotateX(-10deg); + } + 70% { + -webkit-transform: perspective(400px) rotateX(10deg); + transform: perspective(400px) rotateX(10deg); + } + to { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } } + @-webkit-keyframes flipOutX { - from { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } - to { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } + from { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } + to { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } } + @keyframes flipOutX { - from { - opacity: 1; - -webkit-transform: perspective(400px) rotateX(0deg); - transform: perspective(400px) rotateX(0deg); - } - to { - opacity: 0; - -webkit-transform: perspective(400px) rotateX(90deg); - transform: perspective(400px) rotateX(90deg); - } + from { + opacity: 1; + -webkit-transform: perspective(400px) rotateX(0deg); + transform: perspective(400px) rotateX(0deg); + } + to { + opacity: 0; + -webkit-transform: perspective(400px) rotateX(90deg); + transform: perspective(400px) rotateX(90deg); + } } .am-slide-top { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-slide-top.am-slide-top-add, .am-slide-top.ng-hide-remove, .am-slide-top.ng-move { - -webkit-animation-name: slideFromTop; - animation-name: slideFromTop; + -webkit-animation-name: slideFromTop; + animation-name: slideFromTop; } + .am-slide-top.am-slide-top-remove, .am-slide-top.ng-hide { - -webkit-animation-name: slideToTop; - animation-name: slideToTop; + -webkit-animation-name: slideToTop; + animation-name: slideToTop; } + .am-slide-top.ng-enter { - visibility: hidden; - -webkit-animation-name: slideFromTop; - animation-name: slideFromTop; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: slideFromTop; + animation-name: slideFromTop; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-top.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-top.ng-leave { - -webkit-animation-name: slideToTop; - animation-name: slideToTop; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: slideToTop; + animation-name: slideToTop; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-top.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-right { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-slide-right.am-slide-right-add, .am-slide-right.ng-hide-remove, .am-slide-right.ng-move { - -webkit-animation-name: slideFromRight; - animation-name: slideFromRight; + -webkit-animation-name: slideFromRight; + animation-name: slideFromRight; } + .am-slide-right.am-slide-right-remove, .am-slide-right.ng-hide { - -webkit-animation-name: slideToRight; - animation-name: slideToRight; + -webkit-animation-name: slideToRight; + animation-name: slideToRight; } + .am-slide-right.ng-enter { - visibility: hidden; - -webkit-animation-name: slideFromRight; - animation-name: slideFromRight; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: slideFromRight; + animation-name: slideFromRight; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-right.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-right.ng-leave { - -webkit-animation-name: slideToRight; - animation-name: slideToRight; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: slideToRight; + animation-name: slideToRight; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-right.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-bottom { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-slide-bottom.am-slide-bottom-add, .am-slide-bottom.ng-hide-remove, .am-slide-bottom.ng-move { - -webkit-animation-name: slideFromBottom; - animation-name: slideFromBottom; + -webkit-animation-name: slideFromBottom; + animation-name: slideFromBottom; } + .am-slide-bottom.am-slide-bottom-remove, .am-slide-bottom.ng-hide { - -webkit-animation-name: slideToBottom; - animation-name: slideToBottom; + -webkit-animation-name: slideToBottom; + animation-name: slideToBottom; } + .am-slide-bottom.ng-enter { - visibility: hidden; - -webkit-animation-name: slideFromBottom; - animation-name: slideFromBottom; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: slideFromBottom; + animation-name: slideFromBottom; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-bottom.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-bottom.ng-leave { - -webkit-animation-name: slideToBottom; - animation-name: slideToBottom; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: slideToBottom; + animation-name: slideToBottom; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-bottom.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-left { - -webkit-animation-duration: 0.3s; - animation-duration: 0.3s; - -webkit-animation-timing-function: ease-in-out; - animation-timing-function: ease-in-out; - -webkit-animation-fill-mode: backwards; - animation-fill-mode: backwards; + -webkit-animation-duration: 0.3s; + animation-duration: 0.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-fill-mode: backwards; + animation-fill-mode: backwards; } + .am-slide-left.am-slide-left-add, .am-slide-left.ng-hide-remove, .am-slide-left.ng-move { - -webkit-animation-name: slideFromLeft; - animation-name: slideFromLeft; + -webkit-animation-name: slideFromLeft; + animation-name: slideFromLeft; } + .am-slide-left.am-slide-left-remove, .am-slide-left.ng-hide { - -webkit-animation-name: slideToLeft; - animation-name: slideToLeft; + -webkit-animation-name: slideToLeft; + animation-name: slideToLeft; } + .am-slide-left.ng-enter { - visibility: hidden; - -webkit-animation-name: slideFromLeft; - animation-name: slideFromLeft; - -webkit-animation-play-state: paused; - animation-play-state: paused; + visibility: hidden; + -webkit-animation-name: slideFromLeft; + animation-name: slideFromLeft; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-left.ng-enter.ng-enter-active { - visibility: visible; - -webkit-animation-play-state: running; - animation-play-state: running; + visibility: visible; + -webkit-animation-play-state: running; + animation-play-state: running; } + .am-slide-left.ng-leave { - -webkit-animation-name: slideToLeft; - animation-name: slideToLeft; - -webkit-animation-play-state: paused; - animation-play-state: paused; + -webkit-animation-name: slideToLeft; + animation-name: slideToLeft; + -webkit-animation-play-state: paused; + animation-play-state: paused; } + .am-slide-left.ng-leave.ng-leave-active { - -webkit-animation-play-state: running; - animation-play-state: running; + -webkit-animation-play-state: running; + animation-play-state: running; } + @-webkit-keyframes slideFromTop { - from { - -webkit-transform: translateY(-100%); - transform: translateY(-100%); - } + from { + -webkit-transform: translateY(-100%); + transform: translateY(-100%); + } } + @keyframes slideFromTop { - from { - -webkit-transform: translateY(-100%); - transform: translateY(-100%); - } + from { + -webkit-transform: translateY(-100%); + transform: translateY(-100%); + } } + @-webkit-keyframes slideToTop { - to { - -webkit-transform: translateY(-100%); - transform: translateY(-100%); - } + to { + -webkit-transform: translateY(-100%); + transform: translateY(-100%); + } } + @keyframes slideToTop { - to { - -webkit-transform: translateY(-100%); - transform: translateY(-100%); - } + to { + -webkit-transform: translateY(-100%); + transform: translateY(-100%); + } } + @-webkit-keyframes slideFromRight { - from { - -webkit-transform: translateX(100%); - transform: translateX(100%); - } + from { + -webkit-transform: translateX(100%); + transform: translateX(100%); + } } + @keyframes slideFromRight { - from { - -webkit-transform: translateX(100%); - transform: translateX(100%); - } + from { + -webkit-transform: translateX(100%); + transform: translateX(100%); + } } + @-webkit-keyframes slideToRight { - to { - -webkit-transform: translateX(100%); - transform: translateX(100%); - } + to { + -webkit-transform: translateX(100%); + transform: translateX(100%); + } } + @keyframes slideToRight { - to { - -webkit-transform: translateX(100%); - transform: translateX(100%); - } + to { + -webkit-transform: translateX(100%); + transform: translateX(100%); + } } + @-webkit-keyframes slideFromBottom { - from { - -webkit-transform: translateY(100%); - transform: translateY(100%); - } + from { + -webkit-transform: translateY(100%); + transform: translateY(100%); + } } + @keyframes slideFromBottom { - from { - -webkit-transform: translateY(100%); - transform: translateY(100%); - } + from { + -webkit-transform: translateY(100%); + transform: translateY(100%); + } } + @-webkit-keyframes slideToBottom { - to { - -webkit-transform: translateY(100%); - transform: translateY(100%); - } + to { + -webkit-transform: translateY(100%); + transform: translateY(100%); + } } + @keyframes slideToBottom { - to { - -webkit-transform: translateY(100%); - transform: translateY(100%); - } + to { + -webkit-transform: translateY(100%); + transform: translateY(100%); + } } + @-webkit-keyframes slideFromLeft { - from { - -webkit-transform: translateX(-100%); - transform: translateX(-100%); - } + from { + -webkit-transform: translateX(-100%); + transform: translateX(-100%); + } } + @keyframes slideFromLeft { - from { - -webkit-transform: translateX(-100%); - transform: translateX(-100%); - } + from { + -webkit-transform: translateX(-100%); + transform: translateX(-100%); + } } + @-webkit-keyframes slideToLeft { - to { - -webkit-transform: translateX(-100%); - transform: translateX(-100%); - } + to { + -webkit-transform: translateX(-100%); + transform: translateX(-100%); + } } + @keyframes slideToLeft { - to { - -webkit-transform: translateX(-100%); - transform: translateX(-100%); - } + to { + -webkit-transform: translateX(-100%); + transform: translateX(-100%); + } } \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap-additions.css b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap-additions.css index 19f4dbe9..25bceff9 100644 --- a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap-additions.css +++ b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap-additions.css @@ -9,28 +9,32 @@ .thumbnail a > img, .carousel-inner > .item > img, .carousel-inner > .item > a > img { - display: block; - max-width: 100%; - height: auto; + display: block; + max-width: 100%; + height: auto; } + .btn-group-lg > .btn { - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.33; + border-radius: 6px; } + .btn-group-sm > .btn { - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + .btn-group-xs > .btn { - padding: 1px 5px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + padding: 1px 5px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + .container:before, .container:after, .container-fluid:before, @@ -59,9 +63,10 @@ .modal-footer:after, .aside .aside-dialog .aside-footer:before, .aside .aside-dialog .aside-footer:after { - content: " "; - display: table; + content: " "; + display: table; } + .container:after, .container-fluid:after, .row:after, @@ -76,8 +81,9 @@ .panel-body:after, .modal-footer:after, .aside .aside-dialog .aside-footer:after { - clear: both; + clear: both; } + /* * Alerts placement */ @@ -87,132 +93,160 @@ .alert.bottom, .alert.bottom-left, .alert.bottom-right { - position: fixed; - z-index: 1050; - margin: 20px; + position: fixed; + z-index: 1050; + margin: 20px; } + .alert.top, .alert.top-left, .alert.top-right { - top: 50px; + top: 50px; } + .alert.top { - right: 0px; - left: 0px; + right: 0px; + left: 0px; } + .alert.top-right { - right: 0px; + right: 0px; } + .alert.top-right .close { - padding-left: 10px; + padding-left: 10px; } + .alert.top-left { - left: 0px; + left: 0px; } + .alert.top-left .close { - padding-right: 10px; + padding-right: 10px; } + .alert.bottom, .alert.bottom-right, .alert.bottom-left { - bottom: 0px; + bottom: 0px; } + .alert.bottom { - right: 0px; - left: 0px; + right: 0px; + left: 0px; } + .alert.bottom-right { - right: 0px; + right: 0px; } + .alert.bottom-right .close { - padding-left: 10px; + padding-left: 10px; } + .alert.bottom-left { - left: 0px; + left: 0px; } + .alert.bottom-left .close { - padding-right: 10px; + padding-right: 10px; } + /* * Aside element */ .aside { - position: fixed; - top: 0; - bottom: 0; - z-index: 1049; - overflow: auto; - min-width: 320px; - background: white; -} + position: fixed; + top: 0; + bottom: 0; + z-index: 1049; + overflow: auto; + min-width: 320px; + background: white; +} + .aside:focus { - outline: none; + outline: none; } + @media (max-width: 991px) { - .aside { - min-width: 240px; - } + .aside { + min-width: 240px; + } } + .aside.left { - right: auto; - left: 0; + right: auto; + left: 0; } + .aside.right { - right: 0; - left: auto; + right: 0; + left: auto; } + .aside .aside-dialog .aside-header { - padding: 15px; - border-bottom: 1px solid #e5e5e5; - min-height: 16.42857143px; - padding: 6px 15px; - background: #428bca; - color: white; -} + padding: 15px; + border-bottom: 1px solid #e5e5e5; + min-height: 16.42857143px; + padding: 6px 15px; + background: #428bca; + color: white; +} + .aside .aside-dialog .aside-header .close { - margin-right: -8px; - padding: 4px 8px; - color: white; - font-size: 25px; - opacity: .8; + margin-right: -8px; + padding: 4px 8px; + color: white; + font-size: 25px; + opacity: .8; } + .aside .aside-dialog .aside-body { - position: relative; - padding: 20px; + position: relative; + padding: 20px; } + .aside .aside-dialog .aside-footer { - margin-top: 15px; - padding: 19px 20px 20px; - text-align: right; - border-top: 1px solid #e5e5e5; + margin-top: 15px; + padding: 19px 20px 20px; + text-align: right; + border-top: 1px solid #e5e5e5; } + .aside .aside-dialog .aside-footer .btn + .btn { - margin-left: 5px; - margin-bottom: 0; + margin-left: 5px; + margin-bottom: 0; } + .aside .aside-dialog .aside-footer .btn-group .btn + .btn { - margin-left: -1px; + margin-left: -1px; } + .aside .aside-dialog .aside-footer .btn-block + .btn-block { - margin-left: 0; + margin-left: 0; } + .aside-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - background-color: #000000; -} + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000000; +} + .aside-backdrop.fade { - opacity: 0; - filter: alpha(opacity=0); + opacity: 0; + filter: alpha(opacity=0); } + .aside-backdrop.in { - opacity: 0.5; - filter: alpha(opacity=50); + opacity: 0.5; + filter: alpha(opacity=50); } + /* * Callouts * @@ -220,164 +254,194 @@ * Requires a base and modifier class. */ .callout { - margin: 20px 0; - padding: 20px; - border-left: 3px solid #eee; + margin: 20px 0; + padding: 20px; + border-left: 3px solid #eee; } + .callout h4 { - margin-top: 0; - margin-bottom: 5px; + margin-top: 0; + margin-bottom: 5px; } + .callout p:last-child { - margin-bottom: 0; + margin-bottom: 0; } + /* Variations */ .callout-danger { - border-color: #eed3d7; - background-color: #fdf7f7; + border-color: #eed3d7; + background-color: #fdf7f7; } + .callout-danger h4 { - color: #b94a48; + color: #b94a48; } + .callout-warning { - border-color: #faebcc; - background-color: #faf8f0; + border-color: #faebcc; + background-color: #faf8f0; } + .callout-warning h4 { - color: #8a6d3b; + color: #8a6d3b; } + .callout-info { - border-color: #bce8f1; - background-color: #f4f8fa; + border-color: #bce8f1; + background-color: #f4f8fa; } + .callout-info h4 { - color: #34789a; + color: #34789a; } + /* * Datepicker element */ .datepicker.dropdown-menu { - width: 250px; - height: 270px; + width: 250px; + height: 270px; } + .datepicker.dropdown-menu button { - outline: none; - border: 0px; + outline: none; + border: 0px; } + .datepicker.dropdown-menu tbody { - height: 180px; + height: 180px; } + .datepicker.dropdown-menu tbody button { - padding: 6px; + padding: 6px; } + .datepicker.dropdown-menu.datepicker-mode-1 tbody button, .datepicker.dropdown-menu.datepicker-mode-2 tbody button { - height: 65px; + height: 65px; } + .modal.center .modal-dialog { - position: fixed; - top: 40%; - left: 50%; - min-width: 320px; - max-width: 630px; - width: 50%; - -webkit-transform: translateX(-50%) translateY(-50%); - transform: translateX(-50%) translateY(-50%); -} + position: fixed; + top: 40%; + left: 50%; + min-width: 320px; + max-width: 630px; + width: 50%; + -webkit-transform: translateX(-50%) translateY(-50%); + transform: translateX(-50%) translateY(-50%); +} + /* * Popovers corner placement * * Inherit exotic positionning from basic ones & fix arrow placement */ .popover.top-left { - margin-top: -10px; + margin-top: -10px; } + .popover.top-left .arrow { - left: 50%; - margin-left: -11px; - border-bottom-width: 0; - border-top-color: #999999; - border-top-color: rgba(0, 0, 0, 0.25); - bottom: -11px; - left: 10%; -} + left: 50%; + margin-left: -11px; + border-bottom-width: 0; + border-top-color: #999999; + border-top-color: rgba(0, 0, 0, 0.25); + bottom: -11px; + left: 10%; +} + .popover.top-left .arrow:after { - content: " "; - bottom: 1px; - margin-left: -10px; - border-bottom-width: 0; - border-top-color: #ffffff; + content: " "; + bottom: 1px; + margin-left: -10px; + border-bottom-width: 0; + border-top-color: #ffffff; } + .popover.top-right { - margin-top: -10px; + margin-top: -10px; } + .popover.top-right .arrow { - left: 50%; - margin-left: -11px; - border-bottom-width: 0; - border-top-color: #999999; - border-top-color: rgba(0, 0, 0, 0.25); - bottom: -11px; - left: 90%; -} + left: 50%; + margin-left: -11px; + border-bottom-width: 0; + border-top-color: #999999; + border-top-color: rgba(0, 0, 0, 0.25); + bottom: -11px; + left: 90%; +} + .popover.top-right .arrow:after { - content: " "; - bottom: 1px; - margin-left: -10px; - border-bottom-width: 0; - border-top-color: #ffffff; + content: " "; + bottom: 1px; + margin-left: -10px; + border-bottom-width: 0; + border-top-color: #ffffff; } + .popover.bottom-left { - margin-top: 10px; + margin-top: 10px; } + .popover.bottom-left .arrow { - left: 50%; - margin-left: -11px; - border-top-width: 0; - border-bottom-color: #999999; - border-bottom-color: rgba(0, 0, 0, 0.25); - top: -11px; - left: 10%; -} + left: 50%; + margin-left: -11px; + border-top-width: 0; + border-bottom-color: #999999; + border-bottom-color: rgba(0, 0, 0, 0.25); + top: -11px; + left: 10%; +} + .popover.bottom-left .arrow:after { - content: " "; - top: 1px; - margin-left: -10px; - border-top-width: 0; - border-bottom-color: #ffffff; + content: " "; + top: 1px; + margin-left: -10px; + border-top-width: 0; + border-bottom-color: #ffffff; } + .popover.bottom-right { - margin-top: 10px; + margin-top: 10px; } + .popover.bottom-right .arrow { - left: 50%; - margin-left: -11px; - border-top-width: 0; - border-bottom-color: #999999; - border-bottom-color: rgba(0, 0, 0, 0.25); - top: -11px; - left: 90%; -} + left: 50%; + margin-left: -11px; + border-top-width: 0; + border-bottom-color: #999999; + border-bottom-color: rgba(0, 0, 0, 0.25); + top: -11px; + left: 90%; +} + .popover.bottom-right .arrow:after { - content: " "; - top: 1px; - margin-left: -10px; - border-top-width: 0; - border-bottom-color: #ffffff; + content: " "; + top: 1px; + margin-left: -10px; + border-top-width: 0; + border-bottom-color: #ffffff; } + /* * Timepicker element */ .timepicker.dropdown-menu { - padding: 0 4px; + padding: 0 4px; } + .timepicker.dropdown-menu button { - outline: none; - border: 0px; + outline: none; + border: 0px; } + .timepicker.dropdown-menu tbody button { - padding: 6px; + padding: 6px; } + /* * Fancy tooltips * @@ -385,134 +449,162 @@ .tooltip.tooltip-info.top .tooltip-arrow, .tooltip.tooltip-info.top-left .tooltip-arrow, .tooltip.tooltip-info.top-right .tooltip-arrow { - border-top-color: #d9edf7; + border-top-color: #d9edf7; } + .tooltip.tooltip-info.right .tooltip-arrow { - border-right-color: #d9edf7; + border-right-color: #d9edf7; } + .tooltip.tooltip-info.bottom .tooltip-arrow, .tooltip.tooltip-info.bottom-left .tooltip-arrow, .tooltip.tooltip-info.bottom-right .tooltip-arrow { - border-bottom-color: #d9edf7; + border-bottom-color: #d9edf7; } + .tooltip.tooltip-info.left .tooltip-arrow { - border-left-color: #d9edf7; + border-left-color: #d9edf7; } + .tooltip.tooltip-info .tooltip-inner { - background-color: #d9edf7; - border-color: #bce8f1; - color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; + color: #31708f; } + .tooltip.tooltip-info .tooltip-inner hr { - border-top-color: #a6e1ec; + border-top-color: #a6e1ec; } + .tooltip.tooltip-info .tooltip-inner .alert-link { - color: #245269; + color: #245269; } + .tooltip.tooltip-success.top .tooltip-arrow, .tooltip.tooltip-success.top-left .tooltip-arrow, .tooltip.tooltip-success.top-right .tooltip-arrow { - border-top-color: #dff0d8; + border-top-color: #dff0d8; } + .tooltip.tooltip-success.right .tooltip-arrow { - border-right-color: #dff0d8; + border-right-color: #dff0d8; } + .tooltip.tooltip-success.bottom .tooltip-arrow, .tooltip.tooltip-success.bottom-left .tooltip-arrow, .tooltip.tooltip-success.bottom-right .tooltip-arrow { - border-bottom-color: #dff0d8; + border-bottom-color: #dff0d8; } + .tooltip.tooltip-success.left .tooltip-arrow { - border-left-color: #dff0d8; + border-left-color: #dff0d8; } + .tooltip.tooltip-success .tooltip-inner { - background-color: #dff0d8; - border-color: #d6e9c6; - color: #3c763d; + background-color: #dff0d8; + border-color: #d6e9c6; + color: #3c763d; } + .tooltip.tooltip-success .tooltip-inner hr { - border-top-color: #c9e2b3; + border-top-color: #c9e2b3; } + .tooltip.tooltip-success .tooltip-inner .alert-link { - color: #2b542c; + color: #2b542c; } + .tooltip.tooltip-danger.top .tooltip-arrow, .tooltip.tooltip-danger.top-left .tooltip-arrow, .tooltip.tooltip-danger.top-right .tooltip-arrow { - border-top-color: #f2dede; + border-top-color: #f2dede; } + .tooltip.tooltip-danger.right .tooltip-arrow { - border-right-color: #f2dede; + border-right-color: #f2dede; } + .tooltip.tooltip-danger.bottom .tooltip-arrow, .tooltip.tooltip-danger.bottom-left .tooltip-arrow, .tooltip.tooltip-danger.bottom-right .tooltip-arrow { - border-bottom-color: #f2dede; + border-bottom-color: #f2dede; } + .tooltip.tooltip-danger.left .tooltip-arrow { - border-left-color: #f2dede; + border-left-color: #f2dede; } + .tooltip.tooltip-danger .tooltip-inner { - background-color: #f2dede; - border-color: #ebccd1; - color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; + color: #a94442; } + .tooltip.tooltip-danger .tooltip-inner hr { - border-top-color: #e4b9c0; + border-top-color: #e4b9c0; } + .tooltip.tooltip-danger .tooltip-inner .alert-link { - color: #843534; + color: #843534; } + /* * Tooltip corner placement * * Inherit exotic positionning from basic ones & fix arrow placement */ .tooltip.top-left { - margin-top: -3px; - padding: 5px 0; + margin-top: -3px; + padding: 5px 0; } + .tooltip.top-left .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-width: 5px 5px 0; - border-top-color: #000000; - left: 10%; -} + bottom: 0; + left: 50%; + margin-left: -5px; + border-width: 5px 5px 0; + border-top-color: #000000; + left: 10%; +} + .tooltip.top-right { - margin-top: -3px; - padding: 5px 0; + margin-top: -3px; + padding: 5px 0; } + .tooltip.top-right .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-width: 5px 5px 0; - border-top-color: #000000; - left: 90%; -} + bottom: 0; + left: 50%; + margin-left: -5px; + border-width: 5px 5px 0; + border-top-color: #000000; + left: 90%; +} + .tooltip.bottom-left { - margin-top: 3px; - padding: 5px 0; + margin-top: 3px; + padding: 5px 0; } + .tooltip.bottom-left .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000000; - left: 10%; -} + top: 0; + left: 50%; + margin-left: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000000; + left: 10%; +} + .tooltip.bottom-right { - margin-top: 3px; - padding: 5px 0; + margin-top: 3px; + padding: 5px 0; } + .tooltip.bottom-right .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000000; - left: 90%; + top: 0; + left: 50%; + margin-left: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000000; + left: 90%; } \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css index 6564b7c9..95ed9ab0 100644 --- a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css +++ b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css @@ -6,13 +6,15 @@ /*! normalize.css v3.0.2 | MIT License | git.io/normalize */ html { - font-family: sans-serif; - -webkit-text-size-adjust: 100%; - -ms-text-size-adjust: 100%; + font-family: sans-serif; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; } + body { - margin: 0; + margin: 0; } + article, aside, details, @@ -26,967 +28,1242 @@ menu, nav, section, summary { - display: block; + display: block; } + audio, canvas, progress, video { - display: inline-block; - vertical-align: baseline; + display: inline-block; + vertical-align: baseline; } + audio:not([controls]) { - display: none; - height: 0; + display: none; + height: 0; } + [hidden], template { - display: none; + display: none; } + a { - background-color: transparent; + background-color: transparent; } + a:active, a:hover { - outline: 0; + outline: 0; } + abbr[title] { - border-bottom: 1px dotted; + border-bottom: 1px dotted; } + b, strong { - font-weight: bold; + font-weight: bold; } + dfn { - font-style: italic; + font-style: italic; } + h1 { - margin: .67em 0; - font-size: 2em; + margin: .67em 0; + font-size: 2em; } + mark { - color: #000; - background: #ff0; + color: #000; + background: #ff0; } + small { - font-size: 80%; + font-size: 80%; } + sub, sup { - position: relative; - font-size: 75%; - line-height: 0; - vertical-align: baseline; + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; } + sup { - top: -.5em; + top: -.5em; } + sub { - bottom: -.25em; + bottom: -.25em; } + img { - border: 0; + border: 0; } + svg:not(:root) { - overflow: hidden; + overflow: hidden; } + figure { - margin: 1em 40px; + margin: 1em 40px; } + hr { - height: 0; - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; + height: 0; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; } + pre { - overflow: auto; + overflow: auto; } + code, kbd, pre, samp { - font-family: monospace, monospace; - font-size: 1em; + font-family: monospace, monospace; + font-size: 1em; } + button, input, optgroup, select, textarea { - margin: 0; - font: inherit; - color: inherit; + margin: 0; + font: inherit; + color: inherit; } + button { - overflow: visible; + overflow: visible; } + button, select { - text-transform: none; + text-transform: none; } + button, html input[type="button"], input[type="reset"], input[type="submit"] { - -webkit-appearance: button; - cursor: pointer; + -webkit-appearance: button; + cursor: pointer; } + button[disabled], html input[disabled] { - cursor: default; + cursor: default; } + button::-moz-focus-inner, input::-moz-focus-inner { - padding: 0; - border: 0; + padding: 0; + border: 0; } + input { - line-height: normal; + line-height: normal; } + input[type="checkbox"], input[type="radio"] { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - padding: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 0; } + input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { - height: auto; + height: auto; } + input[type="search"] { - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; - -webkit-appearance: textfield; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + -webkit-appearance: textfield; } + input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { - -webkit-appearance: none; + -webkit-appearance: none; } + fieldset { - padding: .35em .625em .75em; - margin: 0 2px; - border: 1px solid #c0c0c0; + padding: .35em .625em .75em; + margin: 0 2px; + border: 1px solid #c0c0c0; } + legend { - padding: 0; - border: 0; + padding: 0; + border: 0; } + textarea { - overflow: auto; + overflow: auto; } + optgroup { - font-weight: bold; + font-weight: bold; } + table { - border-spacing: 0; - border-collapse: collapse; + border-spacing: 0; + border-collapse: collapse; } + td, th { - padding: 0; + padding: 0; } + /*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */ @media print { - *, - *:before, - *:after { - color: #000 !important; - text-shadow: none !important; - background: transparent !important; - -webkit-box-shadow: none !important; - box-shadow: none !important; - } - a, - a:visited { - text-decoration: underline; - } - a[href]:after { - content: " (" attr(href) ")"; - } - abbr[title]:after { - content: " (" attr(title) ")"; - } - a[href^="#"]:after, - a[href^="javascript:"]:after { - content: ""; - } - pre, - blockquote { - border: 1px solid #999; + *, + *:before, + *:after { + color: #000 !important; + text-shadow: none !important; + background: transparent !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; + } - page-break-inside: avoid; - } - thead { - display: table-header-group; - } - tr, - img { - page-break-inside: avoid; - } - img { - max-width: 100% !important; - } - p, - h2, - h3 { - orphans: 3; - widows: 3; - } - h2, - h3 { - page-break-after: avoid; - } - select { - background: #fff !important; - } - .navbar { - display: none; - } - .btn > .caret, - .dropup > .btn > .caret { - border-top-color: #000 !important; - } - .label { - border: 1px solid #000; - } - .table { - border-collapse: collapse !important; - } - .table td, - .table th { - background-color: #fff !important; - } - .table-bordered th, - .table-bordered td { - border: 1px solid #ddd !important; - } + a, + a:visited { + text-decoration: underline; + } + + a[href]:after { + content: " (" attr(href) ")"; + } + + abbr[title]:after { + content: " (" attr(title) ")"; + } + + a[href^="#"]:after, + a[href^="javascript:"]:after { + content: ""; + } + + pre, + blockquote { + border: 1px solid #999; + + page-break-inside: avoid; + } + + thead { + display: table-header-group; + } + + tr, + img { + page-break-inside: avoid; + } + + img { + max-width: 100% !important; + } + + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + + h2, + h3 { + page-break-after: avoid; + } + + select { + background: #fff !important; + } + + .navbar { + display: none; + } + + .btn > .caret, + .dropup > .btn > .caret { + border-top-color: #000 !important; + } + + .label { + border: 1px solid #000; + } + + .table { + border-collapse: collapse !important; + } + + .table td, + .table th { + background-color: #fff !important; + } + + .table-bordered th, + .table-bordered td { + border: 1px solid #ddd !important; + } } + @font-face { - font-family: 'Glyphicons Halflings'; + font-family: 'Glyphicons Halflings'; - src: url('../fonts/glyphicons-halflings-regular.eot'); - src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); + src: url('../fonts/glyphicons-halflings-regular.eot'); + src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); } + .glyphicon { - position: relative; - top: 1px; - display: inline-block; - font-family: 'Glyphicons Halflings'; - font-style: normal; - font-weight: normal; - line-height: 1; + position: relative; + top: 1px; + display: inline-block; + font-family: 'Glyphicons Halflings'; + font-style: normal; + font-weight: normal; + line-height: 1; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } + .glyphicon-asterisk:before { - content: "\2a"; + content: "\2a"; } + .glyphicon-plus:before { - content: "\2b"; + content: "\2b"; } + .glyphicon-euro:before, .glyphicon-eur:before { - content: "\20ac"; + content: "\20ac"; } + .glyphicon-minus:before { - content: "\2212"; + content: "\2212"; } + .glyphicon-cloud:before { - content: "\2601"; + content: "\2601"; } + .glyphicon-envelope:before { - content: "\2709"; + content: "\2709"; } + .glyphicon-pencil:before { - content: "\270f"; + content: "\270f"; } + .glyphicon-glass:before { - content: "\e001"; + content: "\e001"; } + .glyphicon-music:before { - content: "\e002"; + content: "\e002"; } + .glyphicon-search:before { - content: "\e003"; + content: "\e003"; } + .glyphicon-heart:before { - content: "\e005"; + content: "\e005"; } + .glyphicon-star:before { - content: "\e006"; + content: "\e006"; } + .glyphicon-star-empty:before { - content: "\e007"; + content: "\e007"; } + .glyphicon-user:before { - content: "\e008"; + content: "\e008"; } + .glyphicon-film:before { - content: "\e009"; + content: "\e009"; } + .glyphicon-th-large:before { - content: "\e010"; + content: "\e010"; } + .glyphicon-th:before { - content: "\e011"; + content: "\e011"; } + .glyphicon-th-list:before { - content: "\e012"; + content: "\e012"; } + .glyphicon-ok:before { - content: "\e013"; + content: "\e013"; } + .glyphicon-remove:before { - content: "\e014"; + content: "\e014"; } + .glyphicon-zoom-in:before { - content: "\e015"; + content: "\e015"; } + .glyphicon-zoom-out:before { - content: "\e016"; + content: "\e016"; } + .glyphicon-off:before { - content: "\e017"; + content: "\e017"; } + .glyphicon-signal:before { - content: "\e018"; + content: "\e018"; } + .glyphicon-cog:before { - content: "\e019"; + content: "\e019"; } + .glyphicon-trash:before { - content: "\e020"; + content: "\e020"; } + .glyphicon-home:before { - content: "\e021"; + content: "\e021"; } + .glyphicon-file:before { - content: "\e022"; + content: "\e022"; } + .glyphicon-time:before { - content: "\e023"; + content: "\e023"; } + .glyphicon-road:before { - content: "\e024"; + content: "\e024"; } + .glyphicon-download-alt:before { - content: "\e025"; + content: "\e025"; } + .glyphicon-download:before { - content: "\e026"; + content: "\e026"; } + .glyphicon-upload:before { - content: "\e027"; + content: "\e027"; } + .glyphicon-inbox:before { - content: "\e028"; + content: "\e028"; } + .glyphicon-play-circle:before { - content: "\e029"; + content: "\e029"; } + .glyphicon-repeat:before { - content: "\e030"; + content: "\e030"; } + .glyphicon-refresh:before { - content: "\e031"; + content: "\e031"; } + .glyphicon-list-alt:before { - content: "\e032"; + content: "\e032"; } + .glyphicon-lock:before { - content: "\e033"; + content: "\e033"; } + .glyphicon-flag:before { - content: "\e034"; + content: "\e034"; } + .glyphicon-headphones:before { - content: "\e035"; + content: "\e035"; } + .glyphicon-volume-off:before { - content: "\e036"; + content: "\e036"; } + .glyphicon-volume-down:before { - content: "\e037"; + content: "\e037"; } + .glyphicon-volume-up:before { - content: "\e038"; + content: "\e038"; } + .glyphicon-qrcode:before { - content: "\e039"; + content: "\e039"; } + .glyphicon-barcode:before { - content: "\e040"; + content: "\e040"; } + .glyphicon-tag:before { - content: "\e041"; + content: "\e041"; } + .glyphicon-tags:before { - content: "\e042"; + content: "\e042"; } + .glyphicon-book:before { - content: "\e043"; + content: "\e043"; } + .glyphicon-bookmark:before { - content: "\e044"; + content: "\e044"; } + .glyphicon-print:before { - content: "\e045"; + content: "\e045"; } + .glyphicon-camera:before { - content: "\e046"; + content: "\e046"; } + .glyphicon-font:before { - content: "\e047"; + content: "\e047"; } + .glyphicon-bold:before { - content: "\e048"; + content: "\e048"; } + .glyphicon-italic:before { - content: "\e049"; + content: "\e049"; } + .glyphicon-text-height:before { - content: "\e050"; + content: "\e050"; } + .glyphicon-text-width:before { - content: "\e051"; + content: "\e051"; } + .glyphicon-align-left:before { - content: "\e052"; + content: "\e052"; } + .glyphicon-align-center:before { - content: "\e053"; + content: "\e053"; } + .glyphicon-align-right:before { - content: "\e054"; + content: "\e054"; } + .glyphicon-align-justify:before { - content: "\e055"; + content: "\e055"; } + .glyphicon-list:before { - content: "\e056"; + content: "\e056"; } + .glyphicon-indent-left:before { - content: "\e057"; + content: "\e057"; } + .glyphicon-indent-right:before { - content: "\e058"; + content: "\e058"; } + .glyphicon-facetime-video:before { - content: "\e059"; + content: "\e059"; } + .glyphicon-picture:before { - content: "\e060"; + content: "\e060"; } + .glyphicon-map-marker:before { - content: "\e062"; + content: "\e062"; } + .glyphicon-adjust:before { - content: "\e063"; + content: "\e063"; } + .glyphicon-tint:before { - content: "\e064"; + content: "\e064"; } + .glyphicon-edit:before { - content: "\e065"; + content: "\e065"; } + .glyphicon-share:before { - content: "\e066"; + content: "\e066"; } + .glyphicon-check:before { - content: "\e067"; + content: "\e067"; } + .glyphicon-move:before { - content: "\e068"; + content: "\e068"; } + .glyphicon-step-backward:before { - content: "\e069"; + content: "\e069"; } + .glyphicon-fast-backward:before { - content: "\e070"; + content: "\e070"; } + .glyphicon-backward:before { - content: "\e071"; + content: "\e071"; } + .glyphicon-play:before { - content: "\e072"; + content: "\e072"; } + .glyphicon-pause:before { - content: "\e073"; + content: "\e073"; } + .glyphicon-stop:before { - content: "\e074"; + content: "\e074"; } + .glyphicon-forward:before { - content: "\e075"; + content: "\e075"; } + .glyphicon-fast-forward:before { - content: "\e076"; + content: "\e076"; } + .glyphicon-step-forward:before { - content: "\e077"; + content: "\e077"; } + .glyphicon-eject:before { - content: "\e078"; + content: "\e078"; } + .glyphicon-chevron-left:before { - content: "\e079"; + content: "\e079"; } + .glyphicon-chevron-right:before { - content: "\e080"; + content: "\e080"; } + .glyphicon-plus-sign:before { - content: "\e081"; + content: "\e081"; } + .glyphicon-minus-sign:before { - content: "\e082"; + content: "\e082"; } + .glyphicon-remove-sign:before { - content: "\e083"; + content: "\e083"; } + .glyphicon-ok-sign:before { - content: "\e084"; + content: "\e084"; } + .glyphicon-question-sign:before { - content: "\e085"; + content: "\e085"; } + .glyphicon-info-sign:before { - content: "\e086"; + content: "\e086"; } + .glyphicon-screenshot:before { - content: "\e087"; + content: "\e087"; } + .glyphicon-remove-circle:before { - content: "\e088"; + content: "\e088"; } + .glyphicon-ok-circle:before { - content: "\e089"; + content: "\e089"; } + .glyphicon-ban-circle:before { - content: "\e090"; + content: "\e090"; } + .glyphicon-arrow-left:before { - content: "\e091"; + content: "\e091"; } + .glyphicon-arrow-right:before { - content: "\e092"; + content: "\e092"; } + .glyphicon-arrow-up:before { - content: "\e093"; + content: "\e093"; } + .glyphicon-arrow-down:before { - content: "\e094"; + content: "\e094"; } + .glyphicon-share-alt:before { - content: "\e095"; + content: "\e095"; } + .glyphicon-resize-full:before { - content: "\e096"; + content: "\e096"; } + .glyphicon-resize-small:before { - content: "\e097"; + content: "\e097"; } + .glyphicon-exclamation-sign:before { - content: "\e101"; + content: "\e101"; } + .glyphicon-gift:before { - content: "\e102"; + content: "\e102"; } + .glyphicon-leaf:before { - content: "\e103"; + content: "\e103"; } + .glyphicon-fire:before { - content: "\e104"; + content: "\e104"; } + .glyphicon-eye-open:before { - content: "\e105"; + content: "\e105"; } + .glyphicon-eye-close:before { - content: "\e106"; + content: "\e106"; } + .glyphicon-warning-sign:before { - content: "\e107"; + content: "\e107"; } + .glyphicon-plane:before { - content: "\e108"; + content: "\e108"; } + .glyphicon-calendar:before { - content: "\e109"; + content: "\e109"; } + .glyphicon-random:before { - content: "\e110"; + content: "\e110"; } + .glyphicon-comment:before { - content: "\e111"; + content: "\e111"; } + .glyphicon-magnet:before { - content: "\e112"; + content: "\e112"; } + .glyphicon-chevron-up:before { - content: "\e113"; + content: "\e113"; } + .glyphicon-chevron-down:before { - content: "\e114"; + content: "\e114"; } + .glyphicon-retweet:before { - content: "\e115"; + content: "\e115"; } + .glyphicon-shopping-cart:before { - content: "\e116"; + content: "\e116"; } + .glyphicon-folder-close:before { - content: "\e117"; + content: "\e117"; } + .glyphicon-folder-open:before { - content: "\e118"; + content: "\e118"; } + .glyphicon-resize-vertical:before { - content: "\e119"; + content: "\e119"; } + .glyphicon-resize-horizontal:before { - content: "\e120"; + content: "\e120"; } + .glyphicon-hdd:before { - content: "\e121"; + content: "\e121"; } + .glyphicon-bullhorn:before { - content: "\e122"; + content: "\e122"; } + .glyphicon-bell:before { - content: "\e123"; + content: "\e123"; } + .glyphicon-certificate:before { - content: "\e124"; + content: "\e124"; } + .glyphicon-thumbs-up:before { - content: "\e125"; + content: "\e125"; } + .glyphicon-thumbs-down:before { - content: "\e126"; + content: "\e126"; } + .glyphicon-hand-right:before { - content: "\e127"; + content: "\e127"; } + .glyphicon-hand-left:before { - content: "\e128"; + content: "\e128"; } + .glyphicon-hand-up:before { - content: "\e129"; + content: "\e129"; } + .glyphicon-hand-down:before { - content: "\e130"; + content: "\e130"; } + .glyphicon-circle-arrow-right:before { - content: "\e131"; + content: "\e131"; } + .glyphicon-circle-arrow-left:before { - content: "\e132"; + content: "\e132"; } + .glyphicon-circle-arrow-up:before { - content: "\e133"; + content: "\e133"; } + .glyphicon-circle-arrow-down:before { - content: "\e134"; + content: "\e134"; } + .glyphicon-globe:before { - content: "\e135"; + content: "\e135"; } + .glyphicon-wrench:before { - content: "\e136"; + content: "\e136"; } + .glyphicon-tasks:before { - content: "\e137"; + content: "\e137"; } + .glyphicon-filter:before { - content: "\e138"; + content: "\e138"; } + .glyphicon-briefcase:before { - content: "\e139"; + content: "\e139"; } + .glyphicon-fullscreen:before { - content: "\e140"; + content: "\e140"; } + .glyphicon-dashboard:before { - content: "\e141"; + content: "\e141"; } + .glyphicon-paperclip:before { - content: "\e142"; + content: "\e142"; } + .glyphicon-heart-empty:before { - content: "\e143"; + content: "\e143"; } + .glyphicon-link:before { - content: "\e144"; + content: "\e144"; } + .glyphicon-phone:before { - content: "\e145"; + content: "\e145"; } + .glyphicon-pushpin:before { - content: "\e146"; + content: "\e146"; } + .glyphicon-usd:before { - content: "\e148"; + content: "\e148"; } + .glyphicon-gbp:before { - content: "\e149"; + content: "\e149"; } + .glyphicon-sort:before { - content: "\e150"; + content: "\e150"; } + .glyphicon-sort-by-alphabet:before { - content: "\e151"; + content: "\e151"; } + .glyphicon-sort-by-alphabet-alt:before { - content: "\e152"; + content: "\e152"; } + .glyphicon-sort-by-order:before { - content: "\e153"; + content: "\e153"; } + .glyphicon-sort-by-order-alt:before { - content: "\e154"; + content: "\e154"; } + .glyphicon-sort-by-attributes:before { - content: "\e155"; + content: "\e155"; } + .glyphicon-sort-by-attributes-alt:before { - content: "\e156"; + content: "\e156"; } + .glyphicon-unchecked:before { - content: "\e157"; + content: "\e157"; } + .glyphicon-expand:before { - content: "\e158"; + content: "\e158"; } + .glyphicon-collapse-down:before { - content: "\e159"; + content: "\e159"; } + .glyphicon-collapse-up:before { - content: "\e160"; + content: "\e160"; } + .glyphicon-log-in:before { - content: "\e161"; + content: "\e161"; } + .glyphicon-flash:before { - content: "\e162"; + content: "\e162"; } + .glyphicon-log-out:before { - content: "\e163"; + content: "\e163"; } + .glyphicon-new-window:before { - content: "\e164"; + content: "\e164"; } + .glyphicon-record:before { - content: "\e165"; + content: "\e165"; } + .glyphicon-save:before { - content: "\e166"; + content: "\e166"; } + .glyphicon-open:before { - content: "\e167"; + content: "\e167"; } + .glyphicon-saved:before { - content: "\e168"; + content: "\e168"; } + .glyphicon-import:before { - content: "\e169"; + content: "\e169"; } + .glyphicon-export:before { - content: "\e170"; + content: "\e170"; } + .glyphicon-send:before { - content: "\e171"; + content: "\e171"; } + .glyphicon-floppy-disk:before { - content: "\e172"; + content: "\e172"; } + .glyphicon-floppy-saved:before { - content: "\e173"; + content: "\e173"; } + .glyphicon-floppy-remove:before { - content: "\e174"; + content: "\e174"; } + .glyphicon-floppy-save:before { - content: "\e175"; + content: "\e175"; } + .glyphicon-floppy-open:before { - content: "\e176"; + content: "\e176"; } + .glyphicon-credit-card:before { - content: "\e177"; + content: "\e177"; } + .glyphicon-transfer:before { - content: "\e178"; + content: "\e178"; } + .glyphicon-cutlery:before { - content: "\e179"; + content: "\e179"; } + .glyphicon-header:before { - content: "\e180"; + content: "\e180"; } + .glyphicon-compressed:before { - content: "\e181"; + content: "\e181"; } + .glyphicon-earphone:before { - content: "\e182"; + content: "\e182"; } + .glyphicon-phone-alt:before { - content: "\e183"; + content: "\e183"; } + .glyphicon-tower:before { - content: "\e184"; + content: "\e184"; } + .glyphicon-stats:before { - content: "\e185"; + content: "\e185"; } + .glyphicon-sd-video:before { - content: "\e186"; + content: "\e186"; } + .glyphicon-hd-video:before { - content: "\e187"; + content: "\e187"; } + .glyphicon-subtitles:before { - content: "\e188"; + content: "\e188"; } + .glyphicon-sound-stereo:before { - content: "\e189"; + content: "\e189"; } + .glyphicon-sound-dolby:before { - content: "\e190"; + content: "\e190"; } + .glyphicon-sound-5-1:before { - content: "\e191"; + content: "\e191"; } + .glyphicon-sound-6-1:before { - content: "\e192"; + content: "\e192"; } + .glyphicon-sound-7-1:before { - content: "\e193"; + content: "\e193"; } + .glyphicon-copyright-mark:before { - content: "\e194"; + content: "\e194"; } + .glyphicon-registration-mark:before { - content: "\e195"; + content: "\e195"; } + .glyphicon-cloud-download:before { - content: "\e197"; + content: "\e197"; } + .glyphicon-cloud-upload:before { - content: "\e198"; + content: "\e198"; } + .glyphicon-tree-conifer:before { - content: "\e199"; + content: "\e199"; } + .glyphicon-tree-deciduous:before { - content: "\e200"; + content: "\e200"; } + * { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } + *:before, *:after { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } + html { - font-size: 10px; + font-size: 10px; - -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } + body { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - line-height: 1.42857143; - color: #333; - background-color: #fff; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.42857143; + color: #333; + background-color: #fff; } + input, button, select, textarea { - font-family: inherit; - font-size: inherit; - line-height: inherit; + font-family: inherit; + font-size: inherit; + line-height: inherit; } + a { - color: #337ab7; - text-decoration: none; + color: #337ab7; + text-decoration: none; } + a:hover, a:focus { - color: #23527c; - text-decoration: underline; + color: #23527c; + text-decoration: underline; } + a:focus { - outline: thin dotted; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } + figure { - margin: 0; + margin: 0; } + img { - vertical-align: middle; + vertical-align: middle; } + .img-responsive, .thumbnail > img, .thumbnail a > img, .carousel-inner > .item > img, .carousel-inner > .item > a > img { - display: block; - max-width: 100%; - height: auto; + display: block; + max-width: 100%; + height: auto; } + .img-rounded { - border-radius: 6px; + border-radius: 6px; } + .img-thumbnail { - display: inline-block; - max-width: 100%; - height: auto; - padding: 4px; - line-height: 1.42857143; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 4px; - -webkit-transition: all .2s ease-in-out; - -o-transition: all .2s ease-in-out; - transition: all .2s ease-in-out; + display: inline-block; + max-width: 100%; + height: auto; + padding: 4px; + line-height: 1.42857143; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + -webkit-transition: all .2s ease-in-out; + -o-transition: all .2s ease-in-out; + transition: all .2s ease-in-out; } + .img-circle { - border-radius: 50%; + border-radius: 50%; } + hr { - margin-top: 20px; - margin-bottom: 20px; - border: 0; - border-top: 1px solid #eee; + margin-top: 20px; + margin-bottom: 20px; + border: 0; + border-top: 1px solid #eee; } + .sr-only { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - border: 0; + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; } + .sr-only-focusable:active, .sr-only-focusable:focus { - position: static; - width: auto; - height: auto; - margin: 0; - overflow: visible; - clip: auto; + position: static; + width: auto; + height: auto; + margin: 0; + overflow: visible; + clip: auto; } + h1, h2, h3, @@ -999,11 +1276,12 @@ h6, .h4, .h5, .h6 { - font-family: inherit; - font-weight: 500; - line-height: 1.1; - color: inherit; + font-family: inherit; + font-weight: 500; + line-height: 1.1; + color: inherit; } + h1 small, h2 small, h3 small, @@ -1028,19 +1306,21 @@ h6 .small, .h4 .small, .h5 .small, .h6 .small { - font-weight: normal; - line-height: 1; - color: #777; + font-weight: normal; + line-height: 1; + color: #777; } + h1, .h1, h2, .h2, h3, .h3 { - margin-top: 20px; - margin-bottom: 10px; + margin-top: 20px; + margin-bottom: 10px; } + h1 small, .h1 small, h2 small, @@ -1053,17 +1333,19 @@ h2 .small, .h2 .small, h3 .small, .h3 .small { - font-size: 65%; + font-size: 65%; } + h4, .h4, h5, .h5, h6, .h6 { - margin-top: 10px; - margin-bottom: 10px; + margin-top: 10px; + margin-bottom: 10px; } + h4 small, .h4 small, h5 small, @@ -1076,1070 +1358,1372 @@ h5 .small, .h5 .small, h6 .small, .h6 .small { - font-size: 75%; + font-size: 75%; } + h1, .h1 { - font-size: 36px; + font-size: 36px; } + h2, .h2 { - font-size: 30px; + font-size: 30px; } + h3, .h3 { - font-size: 24px; + font-size: 24px; } + h4, .h4 { - font-size: 18px; + font-size: 18px; } + h5, .h5 { - font-size: 14px; + font-size: 14px; } + h6, .h6 { - font-size: 12px; + font-size: 12px; } + p { - margin: 0 0 10px; + margin: 0 0 10px; } + .lead { - margin-bottom: 20px; - font-size: 16px; - font-weight: 300; - line-height: 1.4; + margin-bottom: 20px; + font-size: 16px; + font-weight: 300; + line-height: 1.4; } + @media (min-width: 768px) { - .lead { - font-size: 21px; - } + .lead { + font-size: 21px; + } } + small, .small { - font-size: 85%; + font-size: 85%; } + mark, .mark { - padding: .2em; - background-color: #fcf8e3; + padding: .2em; + background-color: #fcf8e3; } + .text-left { - text-align: left; + text-align: left; } + .text-right { - text-align: right; + text-align: right; } + .text-center { - text-align: center; + text-align: center; } + .text-justify { - text-align: justify; + text-align: justify; } + .text-nowrap { - white-space: nowrap; + white-space: nowrap; } + .text-lowercase { - text-transform: lowercase; + text-transform: lowercase; } + .text-uppercase { - text-transform: uppercase; + text-transform: uppercase; } + .text-capitalize { - text-transform: capitalize; + text-transform: capitalize; } + .text-muted { - color: #777; + color: #777; } + .text-primary { - color: #337ab7; + color: #337ab7; } + a.text-primary:hover { - color: #286090; + color: #286090; } + .text-success { - color: #3c763d; + color: #3c763d; } + a.text-success:hover { - color: #2b542c; + color: #2b542c; } + .text-info { - color: #31708f; + color: #31708f; } + a.text-info:hover { - color: #245269; + color: #245269; } + .text-warning { - color: #8a6d3b; + color: #8a6d3b; } + a.text-warning:hover { - color: #66512c; + color: #66512c; } + .text-danger { - color: #a94442; + color: #a94442; } + a.text-danger:hover { - color: #843534; + color: #843534; } + .bg-primary { - color: #fff; - background-color: #337ab7; + color: #fff; + background-color: #337ab7; } + a.bg-primary:hover { - background-color: #286090; + background-color: #286090; } + .bg-success { - background-color: #dff0d8; + background-color: #dff0d8; } + a.bg-success:hover { - background-color: #c1e2b3; + background-color: #c1e2b3; } + .bg-info { - background-color: #d9edf7; + background-color: #d9edf7; } + a.bg-info:hover { - background-color: #afd9ee; + background-color: #afd9ee; } + .bg-warning { - background-color: #fcf8e3; + background-color: #fcf8e3; } + a.bg-warning:hover { - background-color: #f7ecb5; + background-color: #f7ecb5; } + .bg-danger { - background-color: #f2dede; + background-color: #f2dede; } + a.bg-danger:hover { - background-color: #e4b9b9; + background-color: #e4b9b9; } + .page-header { - padding-bottom: 9px; - margin: 40px 0 20px; - border-bottom: 1px solid #eee; + padding-bottom: 9px; + margin: 40px 0 20px; + border-bottom: 1px solid #eee; } + ul, ol { - margin-top: 0; - margin-bottom: 10px; + margin-top: 0; + margin-bottom: 10px; } + ul ul, ol ul, ul ol, ol ol { - margin-bottom: 0; + margin-bottom: 0; } + .list-unstyled { - padding-left: 0; - list-style: none; + padding-left: 0; + list-style: none; } + .list-inline { - padding-left: 0; - margin-left: -5px; - list-style: none; + padding-left: 0; + margin-left: -5px; + list-style: none; } + .list-inline > li { - display: inline-block; - padding-right: 5px; - padding-left: 5px; + display: inline-block; + padding-right: 5px; + padding-left: 5px; } + dl { - margin-top: 0; - margin-bottom: 20px; + margin-top: 0; + margin-bottom: 20px; } + dt, dd { - line-height: 1.42857143; + line-height: 1.42857143; } + dt { - font-weight: bold; + font-weight: bold; } + dd { - margin-left: 0; + margin-left: 0; } + @media (min-width: 768px) { - .dl-horizontal dt { - float: left; - width: 160px; - overflow: hidden; - clear: left; - text-align: right; - text-overflow: ellipsis; - white-space: nowrap; - } - .dl-horizontal dd { - margin-left: 180px; - } + .dl-horizontal dt { + float: left; + width: 160px; + overflow: hidden; + clear: left; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; + } + + .dl-horizontal dd { + margin-left: 180px; + } } + abbr[title], abbr[data-original-title] { - cursor: help; - border-bottom: 1px dotted #777; + cursor: help; + border-bottom: 1px dotted #777; } + .initialism { - font-size: 90%; - text-transform: uppercase; + font-size: 90%; + text-transform: uppercase; } + blockquote { - padding: 10px 20px; - margin: 0 0 20px; - font-size: 17.5px; - border-left: 5px solid #eee; + padding: 10px 20px; + margin: 0 0 20px; + font-size: 17.5px; + border-left: 5px solid #eee; } + blockquote p:last-child, blockquote ul:last-child, blockquote ol:last-child { - margin-bottom: 0; + margin-bottom: 0; } + blockquote footer, blockquote small, blockquote .small { - display: block; - font-size: 80%; - line-height: 1.42857143; - color: #777; + display: block; + font-size: 80%; + line-height: 1.42857143; + color: #777; } + blockquote footer:before, blockquote small:before, blockquote .small:before { - content: '\2014 \00A0'; + content: '\2014 \00A0'; } + .blockquote-reverse, blockquote.pull-right { - padding-right: 15px; - padding-left: 0; - text-align: right; - border-right: 5px solid #eee; - border-left: 0; + padding-right: 15px; + padding-left: 0; + text-align: right; + border-right: 5px solid #eee; + border-left: 0; } + .blockquote-reverse footer:before, blockquote.pull-right footer:before, .blockquote-reverse small:before, blockquote.pull-right small:before, .blockquote-reverse .small:before, blockquote.pull-right .small:before { - content: ''; + content: ''; } + .blockquote-reverse footer:after, blockquote.pull-right footer:after, .blockquote-reverse small:after, blockquote.pull-right small:after, .blockquote-reverse .small:after, blockquote.pull-right .small:after { - content: '\00A0 \2014'; + content: '\00A0 \2014'; } + address { - margin-bottom: 20px; - font-style: normal; - line-height: 1.42857143; + margin-bottom: 20px; + font-style: normal; + line-height: 1.42857143; } + code, kbd, pre, samp { - font-family: Menlo, Monaco, Consolas, "Courier New", monospace; + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; } + code { - padding: 2px 4px; - font-size: 90%; - color: #c7254e; - background-color: #f9f2f4; - border-radius: 4px; + padding: 2px 4px; + font-size: 90%; + color: #c7254e; + background-color: #f9f2f4; + border-radius: 4px; } + kbd { - padding: 2px 4px; - font-size: 90%; - color: #fff; - background-color: #333; - border-radius: 3px; - -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); - box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); + padding: 2px 4px; + font-size: 90%; + color: #fff; + background-color: #333; + border-radius: 3px; + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); } + kbd kbd { - padding: 0; - font-size: 100%; - font-weight: bold; - -webkit-box-shadow: none; - box-shadow: none; + padding: 0; + font-size: 100%; + font-weight: bold; + -webkit-box-shadow: none; + box-shadow: none; } + pre { - display: block; - padding: 9.5px; - margin: 0 0 10px; - font-size: 13px; - line-height: 1.42857143; - color: #333; - word-break: break-all; - word-wrap: break-word; - background-color: #f5f5f5; - border: 1px solid #ccc; - border-radius: 4px; + display: block; + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + line-height: 1.42857143; + color: #333; + word-break: break-all; + word-wrap: break-word; + background-color: #f5f5f5; + border: 1px solid #ccc; + border-radius: 4px; } + pre code { - padding: 0; - font-size: inherit; - color: inherit; - white-space: pre-wrap; - background-color: transparent; - border-radius: 0; + padding: 0; + font-size: inherit; + color: inherit; + white-space: pre-wrap; + background-color: transparent; + border-radius: 0; } + .pre-scrollable { - max-height: 340px; - overflow-y: scroll; + max-height: 340px; + overflow-y: scroll; } + .container { - padding-right: 15px; - padding-left: 15px; - margin-right: auto; - margin-left: auto; + padding-right: 15px; + padding-left: 15px; + margin-right: auto; + margin-left: auto; } + @media (min-width: 768px) { - .container { - width: 750px; - } + .container { + width: 750px; + } } + @media (min-width: 992px) { - .container { - width: 970px; - } + .container { + width: 970px; + } } + @media (min-width: 1200px) { - .container { - width: 1170px; - } + .container { + width: 1170px; + } } + .container-fluid { - padding-right: 15px; - padding-left: 15px; - margin-right: auto; - margin-left: auto; + padding-right: 15px; + padding-left: 15px; + margin-right: auto; + margin-left: auto; } + .row { - margin-right: -15px; - margin-left: -15px; + margin-right: -15px; + margin-left: -15px; } + .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 { - position: relative; - min-height: 1px; - padding-right: 15px; - padding-left: 15px; + position: relative; + min-height: 1px; + padding-right: 15px; + padding-left: 15px; } + .col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 { - float: left; + float: left; } + .col-xs-12 { - width: 100%; + width: 100%; } + .col-xs-11 { - width: 91.66666667%; + width: 91.66666667%; } + .col-xs-10 { - width: 83.33333333%; + width: 83.33333333%; } + .col-xs-9 { - width: 75%; + width: 75%; } + .col-xs-8 { - width: 66.66666667%; + width: 66.66666667%; } + .col-xs-7 { - width: 58.33333333%; + width: 58.33333333%; } + .col-xs-6 { - width: 50%; + width: 50%; } + .col-xs-5 { - width: 41.66666667%; + width: 41.66666667%; } + .col-xs-4 { - width: 33.33333333%; + width: 33.33333333%; } + .col-xs-3 { - width: 25%; + width: 25%; } + .col-xs-2 { - width: 16.66666667%; + width: 16.66666667%; } + .col-xs-1 { - width: 8.33333333%; + width: 8.33333333%; } + .col-xs-pull-12 { - right: 100%; + right: 100%; } + .col-xs-pull-11 { - right: 91.66666667%; + right: 91.66666667%; } + .col-xs-pull-10 { - right: 83.33333333%; + right: 83.33333333%; } + .col-xs-pull-9 { - right: 75%; + right: 75%; } + .col-xs-pull-8 { - right: 66.66666667%; + right: 66.66666667%; } + .col-xs-pull-7 { - right: 58.33333333%; + right: 58.33333333%; } + .col-xs-pull-6 { - right: 50%; + right: 50%; } + .col-xs-pull-5 { - right: 41.66666667%; + right: 41.66666667%; } + .col-xs-pull-4 { - right: 33.33333333%; + right: 33.33333333%; } + .col-xs-pull-3 { - right: 25%; + right: 25%; } + .col-xs-pull-2 { - right: 16.66666667%; + right: 16.66666667%; } + .col-xs-pull-1 { - right: 8.33333333%; + right: 8.33333333%; } + .col-xs-pull-0 { - right: auto; + right: auto; } + .col-xs-push-12 { - left: 100%; + left: 100%; } + .col-xs-push-11 { - left: 91.66666667%; + left: 91.66666667%; } + .col-xs-push-10 { - left: 83.33333333%; + left: 83.33333333%; } + .col-xs-push-9 { - left: 75%; + left: 75%; } + .col-xs-push-8 { - left: 66.66666667%; + left: 66.66666667%; } + .col-xs-push-7 { - left: 58.33333333%; + left: 58.33333333%; } + .col-xs-push-6 { - left: 50%; + left: 50%; } + .col-xs-push-5 { - left: 41.66666667%; + left: 41.66666667%; } + .col-xs-push-4 { - left: 33.33333333%; + left: 33.33333333%; } + .col-xs-push-3 { - left: 25%; + left: 25%; } + .col-xs-push-2 { - left: 16.66666667%; + left: 16.66666667%; } + .col-xs-push-1 { - left: 8.33333333%; + left: 8.33333333%; } + .col-xs-push-0 { - left: auto; + left: auto; } + .col-xs-offset-12 { - margin-left: 100%; + margin-left: 100%; } + .col-xs-offset-11 { - margin-left: 91.66666667%; + margin-left: 91.66666667%; } + .col-xs-offset-10 { - margin-left: 83.33333333%; + margin-left: 83.33333333%; } + .col-xs-offset-9 { - margin-left: 75%; + margin-left: 75%; } + .col-xs-offset-8 { - margin-left: 66.66666667%; + margin-left: 66.66666667%; } + .col-xs-offset-7 { - margin-left: 58.33333333%; + margin-left: 58.33333333%; } + .col-xs-offset-6 { - margin-left: 50%; + margin-left: 50%; } + .col-xs-offset-5 { - margin-left: 41.66666667%; + margin-left: 41.66666667%; } + .col-xs-offset-4 { - margin-left: 33.33333333%; + margin-left: 33.33333333%; } + .col-xs-offset-3 { - margin-left: 25%; + margin-left: 25%; } + .col-xs-offset-2 { - margin-left: 16.66666667%; + margin-left: 16.66666667%; } + .col-xs-offset-1 { - margin-left: 8.33333333%; + margin-left: 8.33333333%; } + .col-xs-offset-0 { - margin-left: 0; + margin-left: 0; } + @media (min-width: 768px) { - .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 { - float: left; - } - .col-sm-12 { - width: 100%; - } - .col-sm-11 { - width: 91.66666667%; - } - .col-sm-10 { - width: 83.33333333%; - } - .col-sm-9 { - width: 75%; - } - .col-sm-8 { - width: 66.66666667%; - } - .col-sm-7 { - width: 58.33333333%; - } - .col-sm-6 { - width: 50%; - } - .col-sm-5 { - width: 41.66666667%; - } - .col-sm-4 { - width: 33.33333333%; - } - .col-sm-3 { - width: 25%; - } - .col-sm-2 { - width: 16.66666667%; - } - .col-sm-1 { - width: 8.33333333%; - } - .col-sm-pull-12 { - right: 100%; - } - .col-sm-pull-11 { - right: 91.66666667%; - } - .col-sm-pull-10 { - right: 83.33333333%; - } - .col-sm-pull-9 { - right: 75%; - } - .col-sm-pull-8 { - right: 66.66666667%; - } - .col-sm-pull-7 { - right: 58.33333333%; - } - .col-sm-pull-6 { - right: 50%; - } - .col-sm-pull-5 { - right: 41.66666667%; - } - .col-sm-pull-4 { - right: 33.33333333%; - } - .col-sm-pull-3 { - right: 25%; - } - .col-sm-pull-2 { - right: 16.66666667%; - } - .col-sm-pull-1 { - right: 8.33333333%; - } - .col-sm-pull-0 { - right: auto; - } - .col-sm-push-12 { - left: 100%; - } - .col-sm-push-11 { - left: 91.66666667%; - } - .col-sm-push-10 { - left: 83.33333333%; - } - .col-sm-push-9 { - left: 75%; - } - .col-sm-push-8 { - left: 66.66666667%; - } - .col-sm-push-7 { - left: 58.33333333%; - } - .col-sm-push-6 { - left: 50%; - } - .col-sm-push-5 { - left: 41.66666667%; - } - .col-sm-push-4 { - left: 33.33333333%; - } - .col-sm-push-3 { - left: 25%; - } - .col-sm-push-2 { - left: 16.66666667%; - } - .col-sm-push-1 { - left: 8.33333333%; - } - .col-sm-push-0 { - left: auto; - } - .col-sm-offset-12 { - margin-left: 100%; - } - .col-sm-offset-11 { - margin-left: 91.66666667%; - } - .col-sm-offset-10 { - margin-left: 83.33333333%; - } - .col-sm-offset-9 { - margin-left: 75%; - } - .col-sm-offset-8 { - margin-left: 66.66666667%; - } - .col-sm-offset-7 { - margin-left: 58.33333333%; - } - .col-sm-offset-6 { - margin-left: 50%; - } - .col-sm-offset-5 { - margin-left: 41.66666667%; - } - .col-sm-offset-4 { - margin-left: 33.33333333%; - } - .col-sm-offset-3 { - margin-left: 25%; - } - .col-sm-offset-2 { - margin-left: 16.66666667%; - } - .col-sm-offset-1 { - margin-left: 8.33333333%; - } - .col-sm-offset-0 { - margin-left: 0; - } + .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 { + float: left; + } + + .col-sm-12 { + width: 100%; + } + + .col-sm-11 { + width: 91.66666667%; + } + + .col-sm-10 { + width: 83.33333333%; + } + + .col-sm-9 { + width: 75%; + } + + .col-sm-8 { + width: 66.66666667%; + } + + .col-sm-7 { + width: 58.33333333%; + } + + .col-sm-6 { + width: 50%; + } + + .col-sm-5 { + width: 41.66666667%; + } + + .col-sm-4 { + width: 33.33333333%; + } + + .col-sm-3 { + width: 25%; + } + + .col-sm-2 { + width: 16.66666667%; + } + + .col-sm-1 { + width: 8.33333333%; + } + + .col-sm-pull-12 { + right: 100%; + } + + .col-sm-pull-11 { + right: 91.66666667%; + } + + .col-sm-pull-10 { + right: 83.33333333%; + } + + .col-sm-pull-9 { + right: 75%; + } + + .col-sm-pull-8 { + right: 66.66666667%; + } + + .col-sm-pull-7 { + right: 58.33333333%; + } + + .col-sm-pull-6 { + right: 50%; + } + + .col-sm-pull-5 { + right: 41.66666667%; + } + + .col-sm-pull-4 { + right: 33.33333333%; + } + + .col-sm-pull-3 { + right: 25%; + } + + .col-sm-pull-2 { + right: 16.66666667%; + } + + .col-sm-pull-1 { + right: 8.33333333%; + } + + .col-sm-pull-0 { + right: auto; + } + + .col-sm-push-12 { + left: 100%; + } + + .col-sm-push-11 { + left: 91.66666667%; + } + + .col-sm-push-10 { + left: 83.33333333%; + } + + .col-sm-push-9 { + left: 75%; + } + + .col-sm-push-8 { + left: 66.66666667%; + } + + .col-sm-push-7 { + left: 58.33333333%; + } + + .col-sm-push-6 { + left: 50%; + } + + .col-sm-push-5 { + left: 41.66666667%; + } + + .col-sm-push-4 { + left: 33.33333333%; + } + + .col-sm-push-3 { + left: 25%; + } + + .col-sm-push-2 { + left: 16.66666667%; + } + + .col-sm-push-1 { + left: 8.33333333%; + } + + .col-sm-push-0 { + left: auto; + } + + .col-sm-offset-12 { + margin-left: 100%; + } + + .col-sm-offset-11 { + margin-left: 91.66666667%; + } + + .col-sm-offset-10 { + margin-left: 83.33333333%; + } + + .col-sm-offset-9 { + margin-left: 75%; + } + + .col-sm-offset-8 { + margin-left: 66.66666667%; + } + + .col-sm-offset-7 { + margin-left: 58.33333333%; + } + + .col-sm-offset-6 { + margin-left: 50%; + } + + .col-sm-offset-5 { + margin-left: 41.66666667%; + } + + .col-sm-offset-4 { + margin-left: 33.33333333%; + } + + .col-sm-offset-3 { + margin-left: 25%; + } + + .col-sm-offset-2 { + margin-left: 16.66666667%; + } + + .col-sm-offset-1 { + margin-left: 8.33333333%; + } + + .col-sm-offset-0 { + margin-left: 0; + } } + @media (min-width: 992px) { - .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 { - float: left; - } - .col-md-12 { - width: 100%; - } - .col-md-11 { - width: 91.66666667%; - } - .col-md-10 { - width: 83.33333333%; - } - .col-md-9 { - width: 75%; - } - .col-md-8 { - width: 66.66666667%; - } - .col-md-7 { - width: 58.33333333%; - } - .col-md-6 { - width: 50%; - } - .col-md-5 { - width: 41.66666667%; - } - .col-md-4 { - width: 33.33333333%; - } - .col-md-3 { - width: 25%; - } - .col-md-2 { - width: 16.66666667%; - } - .col-md-1 { - width: 8.33333333%; - } - .col-md-pull-12 { - right: 100%; - } - .col-md-pull-11 { - right: 91.66666667%; - } - .col-md-pull-10 { - right: 83.33333333%; - } - .col-md-pull-9 { - right: 75%; - } - .col-md-pull-8 { - right: 66.66666667%; - } - .col-md-pull-7 { - right: 58.33333333%; - } - .col-md-pull-6 { - right: 50%; - } - .col-md-pull-5 { - right: 41.66666667%; - } - .col-md-pull-4 { - right: 33.33333333%; - } - .col-md-pull-3 { - right: 25%; - } - .col-md-pull-2 { - right: 16.66666667%; - } - .col-md-pull-1 { - right: 8.33333333%; - } - .col-md-pull-0 { - right: auto; - } - .col-md-push-12 { - left: 100%; - } - .col-md-push-11 { - left: 91.66666667%; - } - .col-md-push-10 { - left: 83.33333333%; - } - .col-md-push-9 { - left: 75%; - } - .col-md-push-8 { - left: 66.66666667%; - } - .col-md-push-7 { - left: 58.33333333%; - } - .col-md-push-6 { - left: 50%; - } - .col-md-push-5 { - left: 41.66666667%; - } - .col-md-push-4 { - left: 33.33333333%; - } - .col-md-push-3 { - left: 25%; - } - .col-md-push-2 { - left: 16.66666667%; - } - .col-md-push-1 { - left: 8.33333333%; - } - .col-md-push-0 { - left: auto; - } - .col-md-offset-12 { - margin-left: 100%; - } - .col-md-offset-11 { - margin-left: 91.66666667%; - } - .col-md-offset-10 { - margin-left: 83.33333333%; - } - .col-md-offset-9 { - margin-left: 75%; - } - .col-md-offset-8 { - margin-left: 66.66666667%; - } - .col-md-offset-7 { - margin-left: 58.33333333%; - } - .col-md-offset-6 { - margin-left: 50%; - } - .col-md-offset-5 { - margin-left: 41.66666667%; - } - .col-md-offset-4 { - margin-left: 33.33333333%; - } - .col-md-offset-3 { - margin-left: 25%; - } - .col-md-offset-2 { - margin-left: 16.66666667%; - } - .col-md-offset-1 { - margin-left: 8.33333333%; - } - .col-md-offset-0 { - margin-left: 0; - } + .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 { + float: left; + } + + .col-md-12 { + width: 100%; + } + + .col-md-11 { + width: 91.66666667%; + } + + .col-md-10 { + width: 83.33333333%; + } + + .col-md-9 { + width: 75%; + } + + .col-md-8 { + width: 66.66666667%; + } + + .col-md-7 { + width: 58.33333333%; + } + + .col-md-6 { + width: 50%; + } + + .col-md-5 { + width: 41.66666667%; + } + + .col-md-4 { + width: 33.33333333%; + } + + .col-md-3 { + width: 25%; + } + + .col-md-2 { + width: 16.66666667%; + } + + .col-md-1 { + width: 8.33333333%; + } + + .col-md-pull-12 { + right: 100%; + } + + .col-md-pull-11 { + right: 91.66666667%; + } + + .col-md-pull-10 { + right: 83.33333333%; + } + + .col-md-pull-9 { + right: 75%; + } + + .col-md-pull-8 { + right: 66.66666667%; + } + + .col-md-pull-7 { + right: 58.33333333%; + } + + .col-md-pull-6 { + right: 50%; + } + + .col-md-pull-5 { + right: 41.66666667%; + } + + .col-md-pull-4 { + right: 33.33333333%; + } + + .col-md-pull-3 { + right: 25%; + } + + .col-md-pull-2 { + right: 16.66666667%; + } + + .col-md-pull-1 { + right: 8.33333333%; + } + + .col-md-pull-0 { + right: auto; + } + + .col-md-push-12 { + left: 100%; + } + + .col-md-push-11 { + left: 91.66666667%; + } + + .col-md-push-10 { + left: 83.33333333%; + } + + .col-md-push-9 { + left: 75%; + } + + .col-md-push-8 { + left: 66.66666667%; + } + + .col-md-push-7 { + left: 58.33333333%; + } + + .col-md-push-6 { + left: 50%; + } + + .col-md-push-5 { + left: 41.66666667%; + } + + .col-md-push-4 { + left: 33.33333333%; + } + + .col-md-push-3 { + left: 25%; + } + + .col-md-push-2 { + left: 16.66666667%; + } + + .col-md-push-1 { + left: 8.33333333%; + } + + .col-md-push-0 { + left: auto; + } + + .col-md-offset-12 { + margin-left: 100%; + } + + .col-md-offset-11 { + margin-left: 91.66666667%; + } + + .col-md-offset-10 { + margin-left: 83.33333333%; + } + + .col-md-offset-9 { + margin-left: 75%; + } + + .col-md-offset-8 { + margin-left: 66.66666667%; + } + + .col-md-offset-7 { + margin-left: 58.33333333%; + } + + .col-md-offset-6 { + margin-left: 50%; + } + + .col-md-offset-5 { + margin-left: 41.66666667%; + } + + .col-md-offset-4 { + margin-left: 33.33333333%; + } + + .col-md-offset-3 { + margin-left: 25%; + } + + .col-md-offset-2 { + margin-left: 16.66666667%; + } + + .col-md-offset-1 { + margin-left: 8.33333333%; + } + + .col-md-offset-0 { + margin-left: 0; + } } + @media (min-width: 1200px) { - .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 { - float: left; - } - .col-lg-12 { - width: 100%; - } - .col-lg-11 { - width: 91.66666667%; - } - .col-lg-10 { - width: 83.33333333%; - } - .col-lg-9 { - width: 75%; - } - .col-lg-8 { - width: 66.66666667%; - } - .col-lg-7 { - width: 58.33333333%; - } - .col-lg-6 { - width: 50%; - } - .col-lg-5 { - width: 41.66666667%; - } - .col-lg-4 { - width: 33.33333333%; - } - .col-lg-3 { - width: 25%; - } - .col-lg-2 { - width: 16.66666667%; - } - .col-lg-1 { - width: 8.33333333%; - } - .col-lg-pull-12 { - right: 100%; - } - .col-lg-pull-11 { - right: 91.66666667%; - } - .col-lg-pull-10 { - right: 83.33333333%; - } - .col-lg-pull-9 { - right: 75%; - } - .col-lg-pull-8 { - right: 66.66666667%; - } - .col-lg-pull-7 { - right: 58.33333333%; - } - .col-lg-pull-6 { - right: 50%; - } - .col-lg-pull-5 { - right: 41.66666667%; - } - .col-lg-pull-4 { - right: 33.33333333%; - } - .col-lg-pull-3 { - right: 25%; - } - .col-lg-pull-2 { - right: 16.66666667%; - } - .col-lg-pull-1 { - right: 8.33333333%; - } - .col-lg-pull-0 { - right: auto; - } - .col-lg-push-12 { - left: 100%; - } - .col-lg-push-11 { - left: 91.66666667%; - } - .col-lg-push-10 { - left: 83.33333333%; - } - .col-lg-push-9 { - left: 75%; - } - .col-lg-push-8 { - left: 66.66666667%; - } - .col-lg-push-7 { - left: 58.33333333%; - } - .col-lg-push-6 { - left: 50%; - } - .col-lg-push-5 { - left: 41.66666667%; - } - .col-lg-push-4 { - left: 33.33333333%; - } - .col-lg-push-3 { - left: 25%; - } - .col-lg-push-2 { - left: 16.66666667%; - } - .col-lg-push-1 { - left: 8.33333333%; - } - .col-lg-push-0 { - left: auto; - } - .col-lg-offset-12 { - margin-left: 100%; - } - .col-lg-offset-11 { - margin-left: 91.66666667%; - } - .col-lg-offset-10 { - margin-left: 83.33333333%; - } - .col-lg-offset-9 { - margin-left: 75%; - } - .col-lg-offset-8 { - margin-left: 66.66666667%; - } - .col-lg-offset-7 { - margin-left: 58.33333333%; - } - .col-lg-offset-6 { - margin-left: 50%; - } - .col-lg-offset-5 { - margin-left: 41.66666667%; - } - .col-lg-offset-4 { - margin-left: 33.33333333%; - } - .col-lg-offset-3 { - margin-left: 25%; - } - .col-lg-offset-2 { - margin-left: 16.66666667%; - } - .col-lg-offset-1 { - margin-left: 8.33333333%; - } - .col-lg-offset-0 { - margin-left: 0; - } + .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 { + float: left; + } + + .col-lg-12 { + width: 100%; + } + + .col-lg-11 { + width: 91.66666667%; + } + + .col-lg-10 { + width: 83.33333333%; + } + + .col-lg-9 { + width: 75%; + } + + .col-lg-8 { + width: 66.66666667%; + } + + .col-lg-7 { + width: 58.33333333%; + } + + .col-lg-6 { + width: 50%; + } + + .col-lg-5 { + width: 41.66666667%; + } + + .col-lg-4 { + width: 33.33333333%; + } + + .col-lg-3 { + width: 25%; + } + + .col-lg-2 { + width: 16.66666667%; + } + + .col-lg-1 { + width: 8.33333333%; + } + + .col-lg-pull-12 { + right: 100%; + } + + .col-lg-pull-11 { + right: 91.66666667%; + } + + .col-lg-pull-10 { + right: 83.33333333%; + } + + .col-lg-pull-9 { + right: 75%; + } + + .col-lg-pull-8 { + right: 66.66666667%; + } + + .col-lg-pull-7 { + right: 58.33333333%; + } + + .col-lg-pull-6 { + right: 50%; + } + + .col-lg-pull-5 { + right: 41.66666667%; + } + + .col-lg-pull-4 { + right: 33.33333333%; + } + + .col-lg-pull-3 { + right: 25%; + } + + .col-lg-pull-2 { + right: 16.66666667%; + } + + .col-lg-pull-1 { + right: 8.33333333%; + } + + .col-lg-pull-0 { + right: auto; + } + + .col-lg-push-12 { + left: 100%; + } + + .col-lg-push-11 { + left: 91.66666667%; + } + + .col-lg-push-10 { + left: 83.33333333%; + } + + .col-lg-push-9 { + left: 75%; + } + + .col-lg-push-8 { + left: 66.66666667%; + } + + .col-lg-push-7 { + left: 58.33333333%; + } + + .col-lg-push-6 { + left: 50%; + } + + .col-lg-push-5 { + left: 41.66666667%; + } + + .col-lg-push-4 { + left: 33.33333333%; + } + + .col-lg-push-3 { + left: 25%; + } + + .col-lg-push-2 { + left: 16.66666667%; + } + + .col-lg-push-1 { + left: 8.33333333%; + } + + .col-lg-push-0 { + left: auto; + } + + .col-lg-offset-12 { + margin-left: 100%; + } + + .col-lg-offset-11 { + margin-left: 91.66666667%; + } + + .col-lg-offset-10 { + margin-left: 83.33333333%; + } + + .col-lg-offset-9 { + margin-left: 75%; + } + + .col-lg-offset-8 { + margin-left: 66.66666667%; + } + + .col-lg-offset-7 { + margin-left: 58.33333333%; + } + + .col-lg-offset-6 { + margin-left: 50%; + } + + .col-lg-offset-5 { + margin-left: 41.66666667%; + } + + .col-lg-offset-4 { + margin-left: 33.33333333%; + } + + .col-lg-offset-3 { + margin-left: 25%; + } + + .col-lg-offset-2 { + margin-left: 16.66666667%; + } + + .col-lg-offset-1 { + margin-left: 8.33333333%; + } + + .col-lg-offset-0 { + margin-left: 0; + } } + table { - background-color: transparent; + background-color: transparent; } + caption { - padding-top: 8px; - padding-bottom: 8px; - color: #777; - text-align: left; + padding-top: 8px; + padding-bottom: 8px; + color: #777; + text-align: left; } + th { - text-align: left; + text-align: left; } + .table { - width: 100%; - max-width: 100%; - margin-bottom: 20px; + width: 100%; + max-width: 100%; + margin-bottom: 20px; } + .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td { - padding: 8px; - line-height: 1.42857143; - vertical-align: top; - border-top: 1px solid #ddd; + padding: 8px; + line-height: 1.42857143; + vertical-align: top; + border-top: 1px solid #ddd; } + .table > thead > tr > th { - vertical-align: bottom; - border-bottom: 2px solid #ddd; + vertical-align: bottom; + border-bottom: 2px solid #ddd; } + .table > caption + thead > tr:first-child > th, .table > colgroup + thead > tr:first-child > th, .table > thead:first-child > tr:first-child > th, .table > caption + thead > tr:first-child > td, .table > colgroup + thead > tr:first-child > td, .table > thead:first-child > tr:first-child > td { - border-top: 0; + border-top: 0; } + .table > tbody + tbody { - border-top: 2px solid #ddd; + border-top: 2px solid #ddd; } + .table .table { - background-color: #fff; + background-color: #fff; } + .table-condensed > thead > tr > th, .table-condensed > tbody > tr > th, .table-condensed > tfoot > tr > th, .table-condensed > thead > tr > td, .table-condensed > tbody > tr > td, .table-condensed > tfoot > tr > td { - padding: 5px; + padding: 5px; } + .table-bordered { - border: 1px solid #ddd; + border: 1px solid #ddd; } + .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td { - border: 1px solid #ddd; + border: 1px solid #ddd; } + .table-bordered > thead > tr > th, .table-bordered > thead > tr > td { - border-bottom-width: 2px; + border-bottom-width: 2px; } + .table-striped > tbody > tr:nth-child(odd) { - background-color: #f9f9f9; + background-color: #f9f9f9; } + .table-hover > tbody > tr:hover { - background-color: #f5f5f5; + background-color: #f5f5f5; } + table col[class*="col-"] { - position: static; - display: table-column; - float: none; + position: static; + display: table-column; + float: none; } + table td[class*="col-"], table th[class*="col-"] { - position: static; - display: table-cell; - float: none; + position: static; + display: table-cell; + float: none; } + .table > thead > tr > td.active, .table > tbody > tr > td.active, .table > tfoot > tr > td.active, @@ -2152,15 +2736,17 @@ table th[class*="col-"] { .table > thead > tr.active > th, .table > tbody > tr.active > th, .table > tfoot > tr.active > th { - background-color: #f5f5f5; + background-color: #f5f5f5; } + .table-hover > tbody > tr > td.active:hover, .table-hover > tbody > tr > th.active:hover, .table-hover > tbody > tr.active:hover > td, .table-hover > tbody > tr:hover > .active, .table-hover > tbody > tr.active:hover > th { - background-color: #e8e8e8; + background-color: #e8e8e8; } + .table > thead > tr > td.success, .table > tbody > tr > td.success, .table > tfoot > tr > td.success, @@ -2173,15 +2759,17 @@ table th[class*="col-"] { .table > thead > tr.success > th, .table > tbody > tr.success > th, .table > tfoot > tr.success > th { - background-color: #dff0d8; + background-color: #dff0d8; } + .table-hover > tbody > tr > td.success:hover, .table-hover > tbody > tr > th.success:hover, .table-hover > tbody > tr.success:hover > td, .table-hover > tbody > tr:hover > .success, .table-hover > tbody > tr.success:hover > th { - background-color: #d0e9c6; + background-color: #d0e9c6; } + .table > thead > tr > td.info, .table > tbody > tr > td.info, .table > tfoot > tr > td.info, @@ -2194,15 +2782,17 @@ table th[class*="col-"] { .table > thead > tr.info > th, .table > tbody > tr.info > th, .table > tfoot > tr.info > th { - background-color: #d9edf7; + background-color: #d9edf7; } + .table-hover > tbody > tr > td.info:hover, .table-hover > tbody > tr > th.info:hover, .table-hover > tbody > tr.info:hover > td, .table-hover > tbody > tr:hover > .info, .table-hover > tbody > tr.info:hover > th { - background-color: #c4e3f3; + background-color: #c4e3f3; } + .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot > tr > td.warning, @@ -2215,15 +2805,17 @@ table th[class*="col-"] { .table > thead > tr.warning > th, .table > tbody > tr.warning > th, .table > tfoot > tr.warning > th { - background-color: #fcf8e3; + background-color: #fcf8e3; } + .table-hover > tbody > tr > td.warning:hover, .table-hover > tbody > tr > th.warning:hover, .table-hover > tbody > tr.warning:hover > td, .table-hover > tbody > tr:hover > .warning, .table-hover > tbody > tr.warning:hover > th { - background-color: #faf2cc; + background-color: #faf2cc; } + .table > thead > tr > td.danger, .table > tbody > tr > td.danger, .table > tfoot > tr > td.danger, @@ -2236,330 +2828,384 @@ table th[class*="col-"] { .table > thead > tr.danger > th, .table > tbody > tr.danger > th, .table > tfoot > tr.danger > th { - background-color: #f2dede; + background-color: #f2dede; } + .table-hover > tbody > tr > td.danger:hover, .table-hover > tbody > tr > th.danger:hover, .table-hover > tbody > tr.danger:hover > td, .table-hover > tbody > tr:hover > .danger, .table-hover > tbody > tr.danger:hover > th { - background-color: #ebcccc; + background-color: #ebcccc; } + .table-responsive { - min-height: .01%; - overflow-x: auto; + min-height: .01%; + overflow-x: auto; } + @media screen and (max-width: 767px) { - .table-responsive { - width: 100%; - margin-bottom: 15px; - overflow-y: hidden; - -ms-overflow-style: -ms-autohiding-scrollbar; - border: 1px solid #ddd; - } - .table-responsive > .table { - margin-bottom: 0; - } - .table-responsive > .table > thead > tr > th, - .table-responsive > .table > tbody > tr > th, - .table-responsive > .table > tfoot > tr > th, - .table-responsive > .table > thead > tr > td, - .table-responsive > .table > tbody > tr > td, - .table-responsive > .table > tfoot > tr > td { - white-space: nowrap; - } - .table-responsive > .table-bordered { - border: 0; - } - .table-responsive > .table-bordered > thead > tr > th:first-child, - .table-responsive > .table-bordered > tbody > tr > th:first-child, - .table-responsive > .table-bordered > tfoot > tr > th:first-child, - .table-responsive > .table-bordered > thead > tr > td:first-child, - .table-responsive > .table-bordered > tbody > tr > td:first-child, - .table-responsive > .table-bordered > tfoot > tr > td:first-child { - border-left: 0; - } - .table-responsive > .table-bordered > thead > tr > th:last-child, - .table-responsive > .table-bordered > tbody > tr > th:last-child, - .table-responsive > .table-bordered > tfoot > tr > th:last-child, - .table-responsive > .table-bordered > thead > tr > td:last-child, - .table-responsive > .table-bordered > tbody > tr > td:last-child, - .table-responsive > .table-bordered > tfoot > tr > td:last-child { - border-right: 0; - } - .table-responsive > .table-bordered > tbody > tr:last-child > th, - .table-responsive > .table-bordered > tfoot > tr:last-child > th, - .table-responsive > .table-bordered > tbody > tr:last-child > td, - .table-responsive > .table-bordered > tfoot > tr:last-child > td { - border-bottom: 0; - } + .table-responsive { + width: 100%; + margin-bottom: 15px; + overflow-y: hidden; + -ms-overflow-style: -ms-autohiding-scrollbar; + border: 1px solid #ddd; + } + + .table-responsive > .table { + margin-bottom: 0; + } + + .table-responsive > .table > thead > tr > th, + .table-responsive > .table > tbody > tr > th, + .table-responsive > .table > tfoot > tr > th, + .table-responsive > .table > thead > tr > td, + .table-responsive > .table > tbody > tr > td, + .table-responsive > .table > tfoot > tr > td { + white-space: nowrap; + } + + .table-responsive > .table-bordered { + border: 0; + } + + .table-responsive > .table-bordered > thead > tr > th:first-child, + .table-responsive > .table-bordered > tbody > tr > th:first-child, + .table-responsive > .table-bordered > tfoot > tr > th:first-child, + .table-responsive > .table-bordered > thead > tr > td:first-child, + .table-responsive > .table-bordered > tbody > tr > td:first-child, + .table-responsive > .table-bordered > tfoot > tr > td:first-child { + border-left: 0; + } + + .table-responsive > .table-bordered > thead > tr > th:last-child, + .table-responsive > .table-bordered > tbody > tr > th:last-child, + .table-responsive > .table-bordered > tfoot > tr > th:last-child, + .table-responsive > .table-bordered > thead > tr > td:last-child, + .table-responsive > .table-bordered > tbody > tr > td:last-child, + .table-responsive > .table-bordered > tfoot > tr > td:last-child { + border-right: 0; + } + + .table-responsive > .table-bordered > tbody > tr:last-child > th, + .table-responsive > .table-bordered > tfoot > tr:last-child > th, + .table-responsive > .table-bordered > tbody > tr:last-child > td, + .table-responsive > .table-bordered > tfoot > tr:last-child > td { + border-bottom: 0; + } } + fieldset { - min-width: 0; - padding: 0; - margin: 0; - border: 0; + min-width: 0; + padding: 0; + margin: 0; + border: 0; } + legend { - display: block; - width: 100%; - padding: 0; - margin-bottom: 20px; - font-size: 21px; - line-height: inherit; - color: #333; - border: 0; - border-bottom: 1px solid #e5e5e5; + display: block; + width: 100%; + padding: 0; + margin-bottom: 20px; + font-size: 21px; + line-height: inherit; + color: #333; + border: 0; + border-bottom: 1px solid #e5e5e5; } + label { - display: inline-block; - max-width: 100%; - margin-bottom: 5px; - font-weight: bold; + display: inline-block; + max-width: 100%; + margin-bottom: 5px; + font-weight: bold; } + input[type="search"] { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } + input[type="radio"], input[type="checkbox"] { - margin: 4px 0 0; - margin-top: 1px \9; - line-height: normal; + margin: 4px 0 0; + margin-top: 1px \9; + line-height: normal; } + input[type="file"] { - display: block; + display: block; } + input[type="range"] { - display: block; - width: 100%; + display: block; + width: 100%; } + select[multiple], select[size] { - height: auto; + height: auto; } + input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { - outline: thin dotted; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } + output { - display: block; - padding-top: 7px; - font-size: 14px; - line-height: 1.42857143; - color: #555; + display: block; + padding-top: 7px; + font-size: 14px; + line-height: 1.42857143; + color: #555; } + .form-control { - display: block; - width: 100%; - height: 34px; - padding: 6px 12px; - font-size: 14px; - line-height: 1.42857143; - color: #555; - background-color: #fff; - background-image: none; - border: 1px solid #ccc; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); - -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; - -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; - transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; + display: block; + width: 100%; + height: 34px; + padding: 6px 12px; + font-size: 14px; + line-height: 1.42857143; + color: #555; + background-color: #fff; + background-image: none; + border: 1px solid #ccc; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; + -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; + transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } + .form-control:focus { - border-color: #66afe9; - outline: 0; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); - box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); + border-color: #66afe9; + outline: 0; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6); } + .form-control::-moz-placeholder { - color: #999; - opacity: 1; + color: #999; + opacity: 1; } + .form-control:-ms-input-placeholder { - color: #999; + color: #999; } + .form-control::-webkit-input-placeholder { - color: #999; + color: #999; } + .form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control { - cursor: not-allowed; - background-color: #eee; - opacity: 1; + cursor: not-allowed; + background-color: #eee; + opacity: 1; } + textarea.form-control { - height: auto; + height: auto; } + input[type="search"] { - -webkit-appearance: none; + -webkit-appearance: none; } + @media screen and (-webkit-min-device-pixel-ratio: 0) { - input[type="date"], - input[type="time"], - input[type="datetime-local"], - input[type="month"] { - line-height: 34px; - } - input[type="date"].input-sm, - input[type="time"].input-sm, - input[type="datetime-local"].input-sm, - input[type="month"].input-sm { - line-height: 30px; - } - input[type="date"].input-lg, - input[type="time"].input-lg, - input[type="datetime-local"].input-lg, - input[type="month"].input-lg { - line-height: 46px; - } + input[type="date"], + input[type="time"], + input[type="datetime-local"], + input[type="month"] { + line-height: 34px; + } + + input[type="date"].input-sm, + input[type="time"].input-sm, + input[type="datetime-local"].input-sm, + input[type="month"].input-sm { + line-height: 30px; + } + + input[type="date"].input-lg, + input[type="time"].input-lg, + input[type="datetime-local"].input-lg, + input[type="month"].input-lg { + line-height: 46px; + } } + .form-group { - margin-bottom: 15px; + margin-bottom: 15px; } + .radio, .checkbox { - position: relative; - display: block; - margin-top: 10px; - margin-bottom: 10px; + position: relative; + display: block; + margin-top: 10px; + margin-bottom: 10px; } + .radio label, .checkbox label { - min-height: 20px; - padding-left: 20px; - margin-bottom: 0; - font-weight: normal; - cursor: pointer; + min-height: 20px; + padding-left: 20px; + margin-bottom: 0; + font-weight: normal; + cursor: pointer; } + .radio input[type="radio"], .radio-inline input[type="radio"], .checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"] { - position: absolute; - margin-top: 4px \9; - margin-left: -20px; + position: absolute; + margin-top: 4px \9; + margin-left: -20px; } + .radio + .radio, .checkbox + .checkbox { - margin-top: -5px; + margin-top: -5px; } + .radio-inline, .checkbox-inline { - display: inline-block; - padding-left: 20px; - margin-bottom: 0; - font-weight: normal; - vertical-align: middle; - cursor: pointer; + display: inline-block; + padding-left: 20px; + margin-bottom: 0; + font-weight: normal; + vertical-align: middle; + cursor: pointer; } + .radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline { - margin-top: 0; - margin-left: 10px; + margin-top: 0; + margin-left: 10px; } + input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"].disabled, input[type="checkbox"].disabled, fieldset[disabled] input[type="radio"], fieldset[disabled] input[type="checkbox"] { - cursor: not-allowed; + cursor: not-allowed; } + .radio-inline.disabled, .checkbox-inline.disabled, fieldset[disabled] .radio-inline, fieldset[disabled] .checkbox-inline { - cursor: not-allowed; + cursor: not-allowed; } + .radio.disabled label, .checkbox.disabled label, fieldset[disabled] .radio label, fieldset[disabled] .checkbox label { - cursor: not-allowed; + cursor: not-allowed; } + .form-control-static { - padding-top: 7px; - padding-bottom: 7px; - margin-bottom: 0; + padding-top: 7px; + padding-bottom: 7px; + margin-bottom: 0; } + .form-control-static.input-lg, .form-control-static.input-sm { - padding-right: 0; - padding-left: 0; + padding-right: 0; + padding-left: 0; } + .input-sm, .form-group-sm .form-control { - height: 30px; - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + height: 30px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + select.input-sm, select.form-group-sm .form-control { - height: 30px; - line-height: 30px; + height: 30px; + line-height: 30px; } + textarea.input-sm, textarea.form-group-sm .form-control, select[multiple].input-sm, select[multiple].form-group-sm .form-control { - height: auto; + height: auto; } + .input-lg, .form-group-lg .form-control { - height: 46px; - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px; + height: 46px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.33; + border-radius: 6px; } + select.input-lg, select.form-group-lg .form-control { - height: 46px; - line-height: 46px; + height: 46px; + line-height: 46px; } + textarea.input-lg, textarea.form-group-lg .form-control, select[multiple].input-lg, select[multiple].form-group-lg .form-control { - height: auto; + height: auto; } + .has-feedback { - position: relative; + position: relative; } + .has-feedback .form-control { - padding-right: 42.5px; + padding-right: 42.5px; } + .form-control-feedback { - position: absolute; - top: 0; - right: 0; - z-index: 2; - display: block; - width: 34px; - height: 34px; - line-height: 34px; - text-align: center; - pointer-events: none; + position: absolute; + top: 0; + right: 0; + z-index: 2; + display: block; + width: 34px; + height: 34px; + line-height: 34px; + text-align: center; + pointer-events: none; } + .input-lg + .form-control-feedback { - width: 46px; - height: 46px; - line-height: 46px; + width: 46px; + height: 46px; + line-height: 46px; } + .input-sm + .form-control-feedback { - width: 30px; - height: 30px; - line-height: 30px; + width: 30px; + height: 30px; + line-height: 30px; } + .has-success .help-block, .has-success .control-label, .has-success .radio, @@ -2570,26 +3216,31 @@ select[multiple].form-group-lg .form-control { .has-success.checkbox label, .has-success.radio-inline label, .has-success.checkbox-inline label { - color: #3c763d; + color: #3c763d; } + .has-success .form-control { - border-color: #3c763d; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + border-color: #3c763d; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } + .has-success .form-control:focus { - border-color: #2b542c; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; + border-color: #2b542c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; } + .has-success .input-group-addon { - color: #3c763d; - background-color: #dff0d8; - border-color: #3c763d; + color: #3c763d; + background-color: #dff0d8; + border-color: #3c763d; } + .has-success .form-control-feedback { - color: #3c763d; + color: #3c763d; } + .has-warning .help-block, .has-warning .control-label, .has-warning .radio, @@ -2600,26 +3251,31 @@ select[multiple].form-group-lg .form-control { .has-warning.checkbox label, .has-warning.radio-inline label, .has-warning.checkbox-inline label { - color: #8a6d3b; + color: #8a6d3b; } + .has-warning .form-control { - border-color: #8a6d3b; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + border-color: #8a6d3b; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } + .has-warning .form-control:focus { - border-color: #66512c; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; + border-color: #66512c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; } + .has-warning .input-group-addon { - color: #8a6d3b; - background-color: #fcf8e3; - border-color: #8a6d3b; + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #8a6d3b; } + .has-warning .form-control-feedback { - color: #8a6d3b; + color: #8a6d3b; } + .has-error .help-block, .has-error .control-label, .has-error .radio, @@ -2630,198 +3286,232 @@ select[multiple].form-group-lg .form-control { .has-error.checkbox label, .has-error.radio-inline label, .has-error.checkbox-inline label { - color: #a94442; + color: #a94442; } + .has-error .form-control { - border-color: #a94442; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + border-color: #a94442; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } + .has-error .form-control:focus { - border-color: #843534; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; + border-color: #843534; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; } + .has-error .input-group-addon { - color: #a94442; - background-color: #f2dede; - border-color: #a94442; + color: #a94442; + background-color: #f2dede; + border-color: #a94442; } + .has-error .form-control-feedback { - color: #a94442; + color: #a94442; } + .has-feedback label ~ .form-control-feedback { - top: 25px; + top: 25px; } + .has-feedback label.sr-only ~ .form-control-feedback { - top: 0; + top: 0; } + .help-block { - display: block; - margin-top: 5px; - margin-bottom: 10px; - color: #737373; + display: block; + margin-top: 5px; + margin-bottom: 10px; + color: #737373; } + @media (min-width: 768px) { - .form-inline .form-group { - display: inline-block; - margin-bottom: 0; - vertical-align: middle; - } - .form-inline .form-control { - display: inline-block; - width: auto; - vertical-align: middle; - } - .form-inline .form-control-static { - display: inline-block; - } - .form-inline .input-group { - display: inline-table; - vertical-align: middle; - } - .form-inline .input-group .input-group-addon, - .form-inline .input-group .input-group-btn, - .form-inline .input-group .form-control { - width: auto; - } - .form-inline .input-group > .form-control { - width: 100%; - } - .form-inline .control-label { - margin-bottom: 0; - vertical-align: middle; - } - .form-inline .radio, - .form-inline .checkbox { - display: inline-block; - margin-top: 0; - margin-bottom: 0; - vertical-align: middle; - } - .form-inline .radio label, - .form-inline .checkbox label { - padding-left: 0; - } - .form-inline .radio input[type="radio"], - .form-inline .checkbox input[type="checkbox"] { - position: relative; - margin-left: 0; - } - .form-inline .has-feedback .form-control-feedback { - top: 0; - } + .form-inline .form-group { + display: inline-block; + margin-bottom: 0; + vertical-align: middle; + } + + .form-inline .form-control { + display: inline-block; + width: auto; + vertical-align: middle; + } + + .form-inline .form-control-static { + display: inline-block; + } + + .form-inline .input-group { + display: inline-table; + vertical-align: middle; + } + + .form-inline .input-group .input-group-addon, + .form-inline .input-group .input-group-btn, + .form-inline .input-group .form-control { + width: auto; + } + + .form-inline .input-group > .form-control { + width: 100%; + } + + .form-inline .control-label { + margin-bottom: 0; + vertical-align: middle; + } + + .form-inline .radio, + .form-inline .checkbox { + display: inline-block; + margin-top: 0; + margin-bottom: 0; + vertical-align: middle; + } + + .form-inline .radio label, + .form-inline .checkbox label { + padding-left: 0; + } + + .form-inline .radio input[type="radio"], + .form-inline .checkbox input[type="checkbox"] { + position: relative; + margin-left: 0; + } + + .form-inline .has-feedback .form-control-feedback { + top: 0; + } } + .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { - padding-top: 7px; - margin-top: 0; - margin-bottom: 0; + padding-top: 7px; + margin-top: 0; + margin-bottom: 0; } + .form-horizontal .radio, .form-horizontal .checkbox { - min-height: 27px; + min-height: 27px; } + .form-horizontal .form-group { - margin-right: -15px; - margin-left: -15px; + margin-right: -15px; + margin-left: -15px; } + @media (min-width: 768px) { - .form-horizontal .control-label { - padding-top: 7px; - margin-bottom: 0; - text-align: right; - } + .form-horizontal .control-label { + padding-top: 7px; + margin-bottom: 0; + text-align: right; + } } + .form-horizontal .has-feedback .form-control-feedback { - right: 15px; + right: 15px; } + @media (min-width: 768px) { - .form-horizontal .form-group-lg .control-label { - padding-top: 14.3px; - } + .form-horizontal .form-group-lg .control-label { + padding-top: 14.3px; + } } + @media (min-width: 768px) { - .form-horizontal .form-group-sm .control-label { - padding-top: 6px; - } + .form-horizontal .form-group-sm .control-label { + padding-top: 6px; + } } + .btn { - display: inline-block; - padding: 6px 12px; - margin-bottom: 0; - font-size: 14px; - font-weight: normal; - line-height: 1.42857143; - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; + display: inline-block; + padding: 6px 12px; + margin-bottom: 0; + font-size: 14px; + font-weight: normal; + line-height: 1.42857143; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; } + .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn.active.focus { - outline: thin dotted; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } + .btn:hover, .btn:focus, .btn.focus { - color: #333; - text-decoration: none; + color: #333; + text-decoration: none; } + .btn:active, .btn.active { - background-image: none; - outline: 0; - -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); - box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); } + .btn.disabled, .btn[disabled], fieldset[disabled] .btn { - pointer-events: none; - cursor: not-allowed; - filter: alpha(opacity=65); - -webkit-box-shadow: none; - box-shadow: none; - opacity: .65; + pointer-events: none; + cursor: not-allowed; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + box-shadow: none; + opacity: .65; } + .btn-default { - color: #333; - background-color: #fff; - border-color: #ccc; + color: #333; + background-color: #fff; + border-color: #ccc; } + .btn-default:hover, .btn-default:focus, .btn-default.focus, .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { - color: #333; - background-color: #e6e6e6; - border-color: #adadad; + color: #333; + background-color: #e6e6e6; + border-color: #adadad; } + .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { - background-image: none; + background-image: none; } + .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, @@ -2840,33 +3530,38 @@ fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { - background-color: #fff; - border-color: #ccc; + background-color: #fff; + border-color: #ccc; } + .btn-default .badge { - color: #fff; - background-color: #333; + color: #fff; + background-color: #333; } + .btn-primary { - color: #fff; - background-color: #337ab7; - border-color: #2e6da4; + color: #fff; + background-color: #337ab7; + border-color: #2e6da4; } + .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { - color: #fff; - background-color: #286090; - border-color: #204d74; + color: #fff; + background-color: #286090; + border-color: #204d74; } + .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { - background-image: none; + background-image: none; } + .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, @@ -2885,33 +3580,38 @@ fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { - background-color: #337ab7; - border-color: #2e6da4; + background-color: #337ab7; + border-color: #2e6da4; } + .btn-primary .badge { - color: #337ab7; - background-color: #fff; + color: #337ab7; + background-color: #fff; } + .btn-success { - color: #fff; - background-color: #5cb85c; - border-color: #4cae4c; + color: #fff; + background-color: #5cb85c; + border-color: #4cae4c; } + .btn-success:hover, .btn-success:focus, .btn-success.focus, .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { - color: #fff; - background-color: #449d44; - border-color: #398439; + color: #fff; + background-color: #449d44; + border-color: #398439; } + .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { - background-image: none; + background-image: none; } + .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, @@ -2930,33 +3630,38 @@ fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { - background-color: #5cb85c; - border-color: #4cae4c; + background-color: #5cb85c; + border-color: #4cae4c; } + .btn-success .badge { - color: #5cb85c; - background-color: #fff; + color: #5cb85c; + background-color: #fff; } + .btn-info { - color: #fff; - background-color: #5bc0de; - border-color: #46b8da; + color: #fff; + background-color: #5bc0de; + border-color: #46b8da; } + .btn-info:hover, .btn-info:focus, .btn-info.focus, .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { - color: #fff; - background-color: #31b0d5; - border-color: #269abc; + color: #fff; + background-color: #31b0d5; + border-color: #269abc; } + .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { - background-image: none; + background-image: none; } + .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, @@ -2975,33 +3680,38 @@ fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { - background-color: #5bc0de; - border-color: #46b8da; + background-color: #5bc0de; + border-color: #46b8da; } + .btn-info .badge { - color: #5bc0de; - background-color: #fff; + color: #5bc0de; + background-color: #fff; } + .btn-warning { - color: #fff; - background-color: #f0ad4e; - border-color: #eea236; + color: #fff; + background-color: #f0ad4e; + border-color: #eea236; } + .btn-warning:hover, .btn-warning:focus, .btn-warning.focus, .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { - color: #fff; - background-color: #ec971f; - border-color: #d58512; + color: #fff; + background-color: #ec971f; + border-color: #d58512; } + .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { - background-image: none; + background-image: none; } + .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, @@ -3020,33 +3730,38 @@ fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { - background-color: #f0ad4e; - border-color: #eea236; + background-color: #f0ad4e; + border-color: #eea236; } + .btn-warning .badge { - color: #f0ad4e; - background-color: #fff; + color: #f0ad4e; + background-color: #fff; } + .btn-danger { - color: #fff; - background-color: #d9534f; - border-color: #d43f3a; + color: #fff; + background-color: #d9534f; + border-color: #d43f3a; } + .btn-danger:hover, .btn-danger:focus, .btn-danger.focus, .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { - color: #fff; - background-color: #c9302c; - border-color: #ac2925; + color: #fff; + background-color: #c9302c; + border-color: #ac2925; } + .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { - background-image: none; + background-image: none; } + .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, @@ -3065,267 +3780,311 @@ fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { - background-color: #d9534f; - border-color: #d43f3a; + background-color: #d9534f; + border-color: #d43f3a; } + .btn-danger .badge { - color: #d9534f; - background-color: #fff; + color: #d9534f; + background-color: #fff; } + .btn-link { - font-weight: normal; - color: #337ab7; - border-radius: 0; + font-weight: normal; + color: #337ab7; + border-radius: 0; } + .btn-link, .btn-link:active, .btn-link.active, .btn-link[disabled], fieldset[disabled] .btn-link { - background-color: transparent; - -webkit-box-shadow: none; - box-shadow: none; + background-color: transparent; + -webkit-box-shadow: none; + box-shadow: none; } + .btn-link, .btn-link:hover, .btn-link:focus, .btn-link:active { - border-color: transparent; + border-color: transparent; } + .btn-link:hover, .btn-link:focus { - color: #23527c; - text-decoration: underline; - background-color: transparent; + color: #23527c; + text-decoration: underline; + background-color: transparent; } + .btn-link[disabled]:hover, fieldset[disabled] .btn-link:hover, .btn-link[disabled]:focus, fieldset[disabled] .btn-link:focus { - color: #777; - text-decoration: none; + color: #777; + text-decoration: none; } + .btn-lg, .btn-group-lg > .btn { - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.33; + border-radius: 6px; } + .btn-sm, .btn-group-sm > .btn { - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + .btn-xs, .btn-group-xs > .btn { - padding: 1px 5px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + padding: 1px 5px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + .btn-block { - display: block; - width: 100%; + display: block; + width: 100%; } + .btn-block + .btn-block { - margin-top: 5px; + margin-top: 5px; } + input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { - width: 100%; + width: 100%; } + .fade { - opacity: 0; - -webkit-transition: opacity .15s linear; - -o-transition: opacity .15s linear; - transition: opacity .15s linear; + opacity: 0; + -webkit-transition: opacity .15s linear; + -o-transition: opacity .15s linear; + transition: opacity .15s linear; } + .fade.in { - opacity: 1; + opacity: 1; } + .collapse { - display: none; - visibility: hidden; + display: none; + visibility: hidden; } + .collapse.in { - display: block; - visibility: visible; + display: block; + visibility: visible; } + tr.collapse.in { - display: table-row; + display: table-row; } + tbody.collapse.in { - display: table-row-group; + display: table-row-group; } + .collapsing { - position: relative; - height: 0; - overflow: hidden; - -webkit-transition-timing-function: ease; - -o-transition-timing-function: ease; - transition-timing-function: ease; - -webkit-transition-duration: .35s; - -o-transition-duration: .35s; - transition-duration: .35s; - -webkit-transition-property: height, visibility; - -o-transition-property: height, visibility; - transition-property: height, visibility; + position: relative; + height: 0; + overflow: hidden; + -webkit-transition-timing-function: ease; + -o-transition-timing-function: ease; + transition-timing-function: ease; + -webkit-transition-duration: .35s; + -o-transition-duration: .35s; + transition-duration: .35s; + -webkit-transition-property: height, visibility; + -o-transition-property: height, visibility; + transition-property: height, visibility; } + .caret { - display: inline-block; - width: 0; - height: 0; - margin-left: 2px; - vertical-align: middle; - border-top: 4px solid; - border-right: 4px solid transparent; - border-left: 4px solid transparent; + display: inline-block; + width: 0; + height: 0; + margin-left: 2px; + vertical-align: middle; + border-top: 4px solid; + border-right: 4px solid transparent; + border-left: 4px solid transparent; } + .dropdown { - position: relative; + position: relative; } + .dropdown-toggle:focus { - outline: 0; + outline: 0; } + .dropdown-menu { - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 5px 0; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, .15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); - box-shadow: 0 6px 12px rgba(0, 0, 0, .175); + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, .15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); + box-shadow: 0 6px 12px rgba(0, 0, 0, .175); } + .dropdown-menu.pull-right { - right: 0; - left: auto; + right: 0; + left: auto; } + .dropdown-menu .divider { - height: 1px; - margin: 9px 0; - overflow: hidden; - background-color: #e5e5e5; + height: 1px; + margin: 9px 0; + overflow: hidden; + background-color: #e5e5e5; } + .dropdown-menu > li > a { - display: block; - padding: 3px 20px; - clear: both; - font-weight: normal; - line-height: 1.42857143; - color: #333; - white-space: nowrap; + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 1.42857143; + color: #333; + white-space: nowrap; } + .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { - color: #262626; - text-decoration: none; - background-color: #f5f5f5; + color: #262626; + text-decoration: none; + background-color: #f5f5f5; } + .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { - color: #fff; - text-decoration: none; - background-color: #337ab7; - outline: 0; + color: #fff; + text-decoration: none; + background-color: #337ab7; + outline: 0; } + .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { - color: #777; + color: #777; } + .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { - text-decoration: none; - cursor: not-allowed; - background-color: transparent; - background-image: none; - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + text-decoration: none; + cursor: not-allowed; + background-color: transparent; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } + .open > .dropdown-menu { - display: block; + display: block; } + .open > a { - outline: 0; + outline: 0; } + .dropdown-menu-right { - right: 0; - left: auto; + right: 0; + left: auto; } + .dropdown-menu-left { - right: auto; - left: 0; + right: auto; + left: 0; } + .dropdown-header { - display: block; - padding: 3px 20px; - font-size: 12px; - line-height: 1.42857143; - color: #777; - white-space: nowrap; + display: block; + padding: 3px 20px; + font-size: 12px; + line-height: 1.42857143; + color: #777; + white-space: nowrap; } + .dropdown-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 990; + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 990; } + .pull-right > .dropdown-menu { - right: 0; - left: auto; + right: 0; + left: auto; } + .dropup .caret, .navbar-fixed-bottom .dropdown .caret { - content: ""; - border-top: 0; - border-bottom: 4px solid; + content: ""; + border-top: 0; + border-bottom: 4px solid; } + .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { - top: auto; - bottom: 100%; - margin-bottom: 1px; + top: auto; + bottom: 100%; + margin-bottom: 1px; } + @media (min-width: 768px) { - .navbar-right .dropdown-menu { - right: 0; - left: auto; - } - .navbar-right .dropdown-menu-left { - right: auto; - left: 0; - } + .navbar-right .dropdown-menu { + right: 0; + left: auto; + } + + .navbar-right .dropdown-menu-left { + right: auto; + left: 0; + } } + .btn-group, .btn-group-vertical { - position: relative; - display: inline-block; - vertical-align: middle; + position: relative; + display: inline-block; + vertical-align: middle; } + .btn-group > .btn, .btn-group-vertical > .btn { - position: relative; - float: left; + position: relative; + float: left; } + .btn-group > .btn:hover, .btn-group-vertical > .btn:hover, .btn-group > .btn:focus, @@ -3334,259 +4093,310 @@ tbody.collapse.in { .btn-group-vertical > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn.active { - z-index: 2; + z-index: 2; } + .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group { - margin-left: -1px; + margin-left: -1px; } + .btn-toolbar { - margin-left: -5px; + margin-left: -5px; } + .btn-toolbar .btn-group, .btn-toolbar .input-group { - float: left; + float: left; } + .btn-toolbar > .btn, .btn-toolbar > .btn-group, .btn-toolbar > .input-group { - margin-left: 5px; + margin-left: 5px; } + .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { - border-radius: 0; + border-radius: 0; } + .btn-group > .btn:first-child { - margin-left: 0; + margin-left: 0; } + .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { - border-top-right-radius: 0; - border-bottom-right-radius: 0; + border-top-right-radius: 0; + border-bottom-right-radius: 0; } + .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { - border-top-left-radius: 0; - border-bottom-left-radius: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; } + .btn-group > .btn-group { - float: left; + float: left; } + .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { - border-radius: 0; + border-radius: 0; } + .btn-group > .btn-group:first-child > .btn:last-child, .btn-group > .btn-group:first-child > .dropdown-toggle { - border-top-right-radius: 0; - border-bottom-right-radius: 0; + border-top-right-radius: 0; + border-bottom-right-radius: 0; } + .btn-group > .btn-group:last-child > .btn:first-child { - border-top-left-radius: 0; - border-bottom-left-radius: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; } + .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { - outline: 0; + outline: 0; } + .btn-group > .btn + .dropdown-toggle { - padding-right: 8px; - padding-left: 8px; + padding-right: 8px; + padding-left: 8px; } + .btn-group > .btn-lg + .dropdown-toggle { - padding-right: 12px; - padding-left: 12px; + padding-right: 12px; + padding-left: 12px; } + .btn-group.open .dropdown-toggle { - -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); - box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); } + .btn-group.open .dropdown-toggle.btn-link { - -webkit-box-shadow: none; - box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; } + .btn .caret { - margin-left: 0; + margin-left: 0; } + .btn-lg .caret { - border-width: 5px 5px 0; - border-bottom-width: 0; + border-width: 5px 5px 0; + border-bottom-width: 0; } + .dropup .btn-lg .caret { - border-width: 0 5px 5px; + border-width: 0 5px 5px; } + .btn-group-vertical > .btn, .btn-group-vertical > .btn-group, .btn-group-vertical > .btn-group > .btn { - display: block; - float: none; - width: 100%; - max-width: 100%; + display: block; + float: none; + width: 100%; + max-width: 100%; } + .btn-group-vertical > .btn-group > .btn { - float: none; + float: none; } + .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { - margin-top: -1px; - margin-left: 0; + margin-top: -1px; + margin-left: 0; } + .btn-group-vertical > .btn:not(:first-child):not(:last-child) { - border-radius: 0; + border-radius: 0; } + .btn-group-vertical > .btn:first-child:not(:last-child) { - border-top-right-radius: 4px; - border-bottom-right-radius: 0; - border-bottom-left-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; } + .btn-group-vertical > .btn:last-child:not(:first-child) { - border-top-left-radius: 0; - border-top-right-radius: 0; - border-bottom-left-radius: 4px; + border-top-left-radius: 0; + border-top-right-radius: 0; + border-bottom-left-radius: 4px; } + .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { - border-radius: 0; + border-radius: 0; } + .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { - border-bottom-right-radius: 0; - border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; } + .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { - border-top-left-radius: 0; - border-top-right-radius: 0; + border-top-left-radius: 0; + border-top-right-radius: 0; } + .btn-group-justified { - display: table; - width: 100%; - table-layout: fixed; - border-collapse: separate; + display: table; + width: 100%; + table-layout: fixed; + border-collapse: separate; } + .btn-group-justified > .btn, .btn-group-justified > .btn-group { - display: table-cell; - float: none; - width: 1%; + display: table-cell; + float: none; + width: 1%; } + .btn-group-justified > .btn-group .btn { - width: 100%; + width: 100%; } + .btn-group-justified > .btn-group .dropdown-menu { - left: auto; + left: auto; } + [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { - position: absolute; - clip: rect(0, 0, 0, 0); - pointer-events: none; + position: absolute; + clip: rect(0, 0, 0, 0); + pointer-events: none; } + .input-group { - position: relative; - display: table; - border-collapse: separate; + position: relative; + display: table; + border-collapse: separate; } + .input-group[class*="col-"] { - float: none; - padding-right: 0; - padding-left: 0; + float: none; + padding-right: 0; + padding-left: 0; } + .input-group .form-control { - position: relative; - z-index: 2; - float: left; - width: 100%; - margin-bottom: 0; + position: relative; + z-index: 2; + float: left; + width: 100%; + margin-bottom: 0; } + .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { - height: 46px; - padding: 10px 16px; - font-size: 18px; - line-height: 1.33; - border-radius: 6px; + height: 46px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.33; + border-radius: 6px; } + select.input-group-lg > .form-control, select.input-group-lg > .input-group-addon, select.input-group-lg > .input-group-btn > .btn { - height: 46px; - line-height: 46px; + height: 46px; + line-height: 46px; } + textarea.input-group-lg > .form-control, textarea.input-group-lg > .input-group-addon, textarea.input-group-lg > .input-group-btn > .btn, select[multiple].input-group-lg > .form-control, select[multiple].input-group-lg > .input-group-addon, select[multiple].input-group-lg > .input-group-btn > .btn { - height: auto; + height: auto; } + .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { - height: 30px; - padding: 5px 10px; - font-size: 12px; - line-height: 1.5; - border-radius: 3px; + height: 30px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; } + select.input-group-sm > .form-control, select.input-group-sm > .input-group-addon, select.input-group-sm > .input-group-btn > .btn { - height: 30px; - line-height: 30px; + height: 30px; + line-height: 30px; } + textarea.input-group-sm > .form-control, textarea.input-group-sm > .input-group-addon, textarea.input-group-sm > .input-group-btn > .btn, select[multiple].input-group-sm > .form-control, select[multiple].input-group-sm > .input-group-addon, select[multiple].input-group-sm > .input-group-btn > .btn { - height: auto; + height: auto; } + .input-group-addon, .input-group-btn, .input-group .form-control { - display: table-cell; + display: table-cell; } + .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { - border-radius: 0; + border-radius: 0; } + .input-group-addon, .input-group-btn { - width: 1%; - white-space: nowrap; - vertical-align: middle; + width: 1%; + white-space: nowrap; + vertical-align: middle; } + .input-group-addon { - padding: 6px 12px; - font-size: 14px; - font-weight: normal; - line-height: 1; - color: #555; - text-align: center; - background-color: #eee; - border: 1px solid #ccc; - border-radius: 4px; + padding: 6px 12px; + font-size: 14px; + font-weight: normal; + line-height: 1; + color: #555; + text-align: center; + background-color: #eee; + border: 1px solid #ccc; + border-radius: 4px; } + .input-group-addon.input-sm { - padding: 5px 10px; - font-size: 12px; - border-radius: 3px; + padding: 5px 10px; + font-size: 12px; + border-radius: 3px; } + .input-group-addon.input-lg { - padding: 10px 16px; - font-size: 18px; - border-radius: 6px; + padding: 10px 16px; + font-size: 18px; + border-radius: 6px; } + .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { - margin-top: 0; + margin-top: 0; } + .input-group .form-control:first-child, .input-group-addon:first-child, .input-group-btn:first-child > .btn, @@ -3594,12 +4404,14 @@ select[multiple].input-group-sm > .input-group-btn > .btn { .input-group-btn:first-child > .dropdown-toggle, .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:last-child > .btn-group:not(:last-child) > .btn { - border-top-right-radius: 0; - border-bottom-right-radius: 0; + border-top-right-radius: 0; + border-bottom-right-radius: 0; } + .input-group-addon:first-child { - border-right: 0; + border-right: 0; } + .input-group .form-control:last-child, .input-group-addon:last-child, .input-group-btn:last-child > .btn, @@ -3607,1326 +4419,1599 @@ select[multiple].input-group-sm > .input-group-btn > .btn { .input-group-btn:last-child > .dropdown-toggle, .input-group-btn:first-child > .btn:not(:first-child), .input-group-btn:first-child > .btn-group:not(:first-child) > .btn { - border-top-left-radius: 0; - border-bottom-left-radius: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; } + .input-group-addon:last-child { - border-left: 0; + border-left: 0; } + .input-group-btn { - position: relative; - font-size: 0; - white-space: nowrap; + position: relative; + font-size: 0; + white-space: nowrap; } + .input-group-btn > .btn { - position: relative; + position: relative; } + .input-group-btn > .btn + .btn { - margin-left: -1px; + margin-left: -1px; } + .input-group-btn > .btn:hover, .input-group-btn > .btn:focus, .input-group-btn > .btn:active { - z-index: 2; + z-index: 2; } + .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group { - margin-right: -1px; + margin-right: -1px; } + .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group { - margin-left: -1px; + margin-left: -1px; } + .nav { - padding-left: 0; - margin-bottom: 0; - list-style: none; + padding-left: 0; + margin-bottom: 0; + list-style: none; } + .nav > li { - position: relative; - display: block; + position: relative; + display: block; } + .nav > li > a { - position: relative; - display: block; - padding: 10px 15px; + position: relative; + display: block; + padding: 10px 15px; } + .nav > li > a:hover, .nav > li > a:focus { - text-decoration: none; - background-color: #eee; + text-decoration: none; + background-color: #eee; } + .nav > li.disabled > a { - color: #777; + color: #777; } + .nav > li.disabled > a:hover, .nav > li.disabled > a:focus { - color: #777; - text-decoration: none; - cursor: not-allowed; - background-color: transparent; + color: #777; + text-decoration: none; + cursor: not-allowed; + background-color: transparent; } + .nav .open > a, .nav .open > a:hover, .nav .open > a:focus { - background-color: #eee; - border-color: #337ab7; + background-color: #eee; + border-color: #337ab7; } + .nav .nav-divider { - height: 1px; - margin: 9px 0; - overflow: hidden; - background-color: #e5e5e5; + height: 1px; + margin: 9px 0; + overflow: hidden; + background-color: #e5e5e5; } + .nav > li > a > img { - max-width: none; + max-width: none; } + .nav-tabs { - border-bottom: 1px solid #ddd; + border-bottom: 1px solid #ddd; } + .nav-tabs > li { - float: left; - margin-bottom: -1px; + float: left; + margin-bottom: -1px; } + .nav-tabs > li > a { - margin-right: 2px; - line-height: 1.42857143; - border: 1px solid transparent; - border-radius: 4px 4px 0 0; + margin-right: 2px; + line-height: 1.42857143; + border: 1px solid transparent; + border-radius: 4px 4px 0 0; } + .nav-tabs > li > a:hover { - border-color: #eee #eee #ddd; + border-color: #eee #eee #ddd; } + .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus { - color: #555; - cursor: default; - background-color: #fff; - border: 1px solid #ddd; - border-bottom-color: transparent; + color: #555; + cursor: default; + background-color: #fff; + border: 1px solid #ddd; + border-bottom-color: transparent; } + .nav-tabs.nav-justified { - width: 100%; - border-bottom: 0; + width: 100%; + border-bottom: 0; } + .nav-tabs.nav-justified > li { - float: none; + float: none; } + .nav-tabs.nav-justified > li > a { - margin-bottom: 5px; - text-align: center; + margin-bottom: 5px; + text-align: center; } + .nav-tabs.nav-justified > .dropdown .dropdown-menu { - top: auto; - left: auto; + top: auto; + left: auto; } + @media (min-width: 768px) { - .nav-tabs.nav-justified > li { - display: table-cell; - width: 1%; - } - .nav-tabs.nav-justified > li > a { - margin-bottom: 0; - } + .nav-tabs.nav-justified > li { + display: table-cell; + width: 1%; + } + + .nav-tabs.nav-justified > li > a { + margin-bottom: 0; + } } + .nav-tabs.nav-justified > li > a { - margin-right: 0; - border-radius: 4px; + margin-right: 0; + border-radius: 4px; } + .nav-tabs.nav-justified > .active > a, .nav-tabs.nav-justified > .active > a:hover, .nav-tabs.nav-justified > .active > a:focus { - border: 1px solid #ddd; + border: 1px solid #ddd; } + @media (min-width: 768px) { - .nav-tabs.nav-justified > li > a { - border-bottom: 1px solid #ddd; - border-radius: 4px 4px 0 0; - } - .nav-tabs.nav-justified > .active > a, - .nav-tabs.nav-justified > .active > a:hover, - .nav-tabs.nav-justified > .active > a:focus { - border-bottom-color: #fff; - } + .nav-tabs.nav-justified > li > a { + border-bottom: 1px solid #ddd; + border-radius: 4px 4px 0 0; + } + + .nav-tabs.nav-justified > .active > a, + .nav-tabs.nav-justified > .active > a:hover, + .nav-tabs.nav-justified > .active > a:focus { + border-bottom-color: #fff; + } } + .nav-pills > li { - float: left; + float: left; } + .nav-pills > li > a { - border-radius: 4px; + border-radius: 4px; } + .nav-pills > li + li { - margin-left: 2px; + margin-left: 2px; } + .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { - color: #fff; - background-color: #337ab7; + color: #fff; + background-color: #337ab7; } + .nav-stacked > li { - float: none; + float: none; } + .nav-stacked > li + li { - margin-top: 2px; - margin-left: 0; + margin-top: 2px; + margin-left: 0; } + .nav-justified { - width: 100%; + width: 100%; } + .nav-justified > li { - float: none; + float: none; } + .nav-justified > li > a { - margin-bottom: 5px; - text-align: center; + margin-bottom: 5px; + text-align: center; } + .nav-justified > .dropdown .dropdown-menu { - top: auto; - left: auto; + top: auto; + left: auto; } + @media (min-width: 768px) { - .nav-justified > li { - display: table-cell; - width: 1%; - } - .nav-justified > li > a { - margin-bottom: 0; - } + .nav-justified > li { + display: table-cell; + width: 1%; + } + + .nav-justified > li > a { + margin-bottom: 0; + } } + .nav-tabs-justified { - border-bottom: 0; + border-bottom: 0; } + .nav-tabs-justified > li > a { - margin-right: 0; - border-radius: 4px; + margin-right: 0; + border-radius: 4px; } + .nav-tabs-justified > .active > a, .nav-tabs-justified > .active > a:hover, .nav-tabs-justified > .active > a:focus { - border: 1px solid #ddd; + border: 1px solid #ddd; } + @media (min-width: 768px) { - .nav-tabs-justified > li > a { - border-bottom: 1px solid #ddd; - border-radius: 4px 4px 0 0; - } - .nav-tabs-justified > .active > a, - .nav-tabs-justified > .active > a:hover, - .nav-tabs-justified > .active > a:focus { - border-bottom-color: #fff; - } + .nav-tabs-justified > li > a { + border-bottom: 1px solid #ddd; + border-radius: 4px 4px 0 0; + } + + .nav-tabs-justified > .active > a, + .nav-tabs-justified > .active > a:hover, + .nav-tabs-justified > .active > a:focus { + border-bottom-color: #fff; + } } + .tab-content > .tab-pane { - display: none; - visibility: hidden; + display: none; + visibility: hidden; } + .tab-content > .active { - display: block; - visibility: visible; + display: block; + visibility: visible; } + .nav-tabs .dropdown-menu { - margin-top: -1px; - border-top-left-radius: 0; - border-top-right-radius: 0; + margin-top: -1px; + border-top-left-radius: 0; + border-top-right-radius: 0; } + .navbar { - position: relative; - min-height: 50px; - margin-bottom: 20px; - border: 1px solid transparent; + position: relative; + min-height: 50px; + margin-bottom: 20px; + border: 1px solid transparent; } + @media (min-width: 768px) { - .navbar { - border-radius: 4px; - } + .navbar { + border-radius: 4px; + } } + @media (min-width: 768px) { - .navbar-header { - float: left; - } + .navbar-header { + float: left; + } } + .navbar-collapse { - padding-right: 15px; - padding-left: 15px; - overflow-x: visible; - -webkit-overflow-scrolling: touch; - border-top: 1px solid transparent; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); + padding-right: 15px; + padding-left: 15px; + overflow-x: visible; + -webkit-overflow-scrolling: touch; + border-top: 1px solid transparent; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); } + .navbar-collapse.in { - overflow-y: auto; + overflow-y: auto; } + @media (min-width: 768px) { - .navbar-collapse { - width: auto; - border-top: 0; - -webkit-box-shadow: none; - box-shadow: none; - } - .navbar-collapse.collapse { - display: block !important; - height: auto !important; - padding-bottom: 0; - overflow: visible !important; - visibility: visible !important; - } - .navbar-collapse.in { - overflow-y: visible; - } - .navbar-fixed-top .navbar-collapse, - .navbar-static-top .navbar-collapse, - .navbar-fixed-bottom .navbar-collapse { - padding-right: 0; - padding-left: 0; - } + .navbar-collapse { + width: auto; + border-top: 0; + -webkit-box-shadow: none; + box-shadow: none; + } + + .navbar-collapse.collapse { + display: block !important; + height: auto !important; + padding-bottom: 0; + overflow: visible !important; + visibility: visible !important; + } + + .navbar-collapse.in { + overflow-y: visible; + } + + .navbar-fixed-top .navbar-collapse, + .navbar-static-top .navbar-collapse, + .navbar-fixed-bottom .navbar-collapse { + padding-right: 0; + padding-left: 0; + } } + .navbar-fixed-top .navbar-collapse, .navbar-fixed-bottom .navbar-collapse { - max-height: 340px; + max-height: 340px; } + @media (max-device-width: 480px) and (orientation: landscape) { - .navbar-fixed-top .navbar-collapse, - .navbar-fixed-bottom .navbar-collapse { - max-height: 200px; - } + .navbar-fixed-top .navbar-collapse, + .navbar-fixed-bottom .navbar-collapse { + max-height: 200px; + } } + .container > .navbar-header, .container-fluid > .navbar-header, .container > .navbar-collapse, .container-fluid > .navbar-collapse { - margin-right: -15px; - margin-left: -15px; + margin-right: -15px; + margin-left: -15px; } + @media (min-width: 768px) { - .container > .navbar-header, - .container-fluid > .navbar-header, - .container > .navbar-collapse, - .container-fluid > .navbar-collapse { - margin-right: 0; - margin-left: 0; - } + .container > .navbar-header, + .container-fluid > .navbar-header, + .container > .navbar-collapse, + .container-fluid > .navbar-collapse { + margin-right: 0; + margin-left: 0; + } } + .navbar-static-top { - z-index: 1000; - border-width: 0 0 1px; + z-index: 1000; + border-width: 0 0 1px; } + @media (min-width: 768px) { - .navbar-static-top { - border-radius: 0; - } + .navbar-static-top { + border-radius: 0; + } } + .navbar-fixed-top, .navbar-fixed-bottom { - position: fixed; - right: 0; - left: 0; - z-index: 1030; + position: fixed; + right: 0; + left: 0; + z-index: 1030; } + @media (min-width: 768px) { - .navbar-fixed-top, - .navbar-fixed-bottom { - border-radius: 0; - } + .navbar-fixed-top, + .navbar-fixed-bottom { + border-radius: 0; + } } + .navbar-fixed-top { - top: 0; - border-width: 0 0 1px; + top: 0; + border-width: 0 0 1px; } + .navbar-fixed-bottom { - bottom: 0; - margin-bottom: 0; - border-width: 1px 0 0; + bottom: 0; + margin-bottom: 0; + border-width: 1px 0 0; } + .navbar-brand { - float: left; - height: 50px; - padding: 15px 15px; - font-size: 18px; - line-height: 20px; + float: left; + height: 50px; + padding: 15px 15px; + font-size: 18px; + line-height: 20px; } + .navbar-brand:hover, .navbar-brand:focus { - text-decoration: none; + text-decoration: none; } + .navbar-brand > img { - display: block; + display: block; } + @media (min-width: 768px) { - .navbar > .container .navbar-brand, - .navbar > .container-fluid .navbar-brand { - margin-left: -15px; - } + .navbar > .container .navbar-brand, + .navbar > .container-fluid .navbar-brand { + margin-left: -15px; + } } + .navbar-toggle { - position: relative; - float: right; - padding: 9px 10px; - margin-top: 8px; - margin-right: 15px; - margin-bottom: 8px; - background-color: transparent; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; + position: relative; + float: right; + padding: 9px 10px; + margin-top: 8px; + margin-right: 15px; + margin-bottom: 8px; + background-color: transparent; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; } + .navbar-toggle:focus { - outline: 0; + outline: 0; } + .navbar-toggle .icon-bar { - display: block; - width: 22px; - height: 2px; - border-radius: 1px; + display: block; + width: 22px; + height: 2px; + border-radius: 1px; } + .navbar-toggle .icon-bar + .icon-bar { - margin-top: 4px; + margin-top: 4px; } + @media (min-width: 768px) { - .navbar-toggle { - display: none; - } + .navbar-toggle { + display: none; + } } + .navbar-nav { - margin: 7.5px -15px; + margin: 7.5px -15px; } + .navbar-nav > li > a { - padding-top: 10px; - padding-bottom: 10px; - line-height: 20px; + padding-top: 10px; + padding-bottom: 10px; + line-height: 20px; } + @media (max-width: 767px) { - .navbar-nav .open .dropdown-menu { - position: static; - float: none; - width: auto; - margin-top: 0; - background-color: transparent; - border: 0; - -webkit-box-shadow: none; - box-shadow: none; - } - .navbar-nav .open .dropdown-menu > li > a, - .navbar-nav .open .dropdown-menu .dropdown-header { - padding: 5px 15px 5px 25px; - } - .navbar-nav .open .dropdown-menu > li > a { - line-height: 20px; - } - .navbar-nav .open .dropdown-menu > li > a:hover, - .navbar-nav .open .dropdown-menu > li > a:focus { - background-image: none; - } + .navbar-nav .open .dropdown-menu { + position: static; + float: none; + width: auto; + margin-top: 0; + background-color: transparent; + border: 0; + -webkit-box-shadow: none; + box-shadow: none; + } + + .navbar-nav .open .dropdown-menu > li > a, + .navbar-nav .open .dropdown-menu .dropdown-header { + padding: 5px 15px 5px 25px; + } + + .navbar-nav .open .dropdown-menu > li > a { + line-height: 20px; + } + + .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-nav .open .dropdown-menu > li > a:focus { + background-image: none; + } } + @media (min-width: 768px) { - .navbar-nav { - float: left; - margin: 0; - } - .navbar-nav > li { - float: left; - } - .navbar-nav > li > a { - padding-top: 15px; - padding-bottom: 15px; - } + .navbar-nav { + float: left; + margin: 0; + } + + .navbar-nav > li { + float: left; + } + + .navbar-nav > li > a { + padding-top: 15px; + padding-bottom: 15px; + } } + .navbar-form { - padding: 10px 15px; - margin-top: 8px; - margin-right: -15px; - margin-bottom: 8px; - margin-left: -15px; - border-top: 1px solid transparent; - border-bottom: 1px solid transparent; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); + padding: 10px 15px; + margin-top: 8px; + margin-right: -15px; + margin-bottom: 8px; + margin-left: -15px; + border-top: 1px solid transparent; + border-bottom: 1px solid transparent; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); } + @media (min-width: 768px) { - .navbar-form .form-group { - display: inline-block; - margin-bottom: 0; - vertical-align: middle; - } - .navbar-form .form-control { - display: inline-block; - width: auto; - vertical-align: middle; - } - .navbar-form .form-control-static { - display: inline-block; - } - .navbar-form .input-group { - display: inline-table; - vertical-align: middle; - } - .navbar-form .input-group .input-group-addon, - .navbar-form .input-group .input-group-btn, - .navbar-form .input-group .form-control { - width: auto; - } - .navbar-form .input-group > .form-control { - width: 100%; - } - .navbar-form .control-label { - margin-bottom: 0; - vertical-align: middle; - } - .navbar-form .radio, - .navbar-form .checkbox { - display: inline-block; - margin-top: 0; - margin-bottom: 0; - vertical-align: middle; - } - .navbar-form .radio label, - .navbar-form .checkbox label { - padding-left: 0; - } - .navbar-form .radio input[type="radio"], - .navbar-form .checkbox input[type="checkbox"] { - position: relative; - margin-left: 0; - } - .navbar-form .has-feedback .form-control-feedback { - top: 0; - } + .navbar-form .form-group { + display: inline-block; + margin-bottom: 0; + vertical-align: middle; + } + + .navbar-form .form-control { + display: inline-block; + width: auto; + vertical-align: middle; + } + + .navbar-form .form-control-static { + display: inline-block; + } + + .navbar-form .input-group { + display: inline-table; + vertical-align: middle; + } + + .navbar-form .input-group .input-group-addon, + .navbar-form .input-group .input-group-btn, + .navbar-form .input-group .form-control { + width: auto; + } + + .navbar-form .input-group > .form-control { + width: 100%; + } + + .navbar-form .control-label { + margin-bottom: 0; + vertical-align: middle; + } + + .navbar-form .radio, + .navbar-form .checkbox { + display: inline-block; + margin-top: 0; + margin-bottom: 0; + vertical-align: middle; + } + + .navbar-form .radio label, + .navbar-form .checkbox label { + padding-left: 0; + } + + .navbar-form .radio input[type="radio"], + .navbar-form .checkbox input[type="checkbox"] { + position: relative; + margin-left: 0; + } + + .navbar-form .has-feedback .form-control-feedback { + top: 0; + } } + @media (max-width: 767px) { - .navbar-form .form-group { - margin-bottom: 5px; - } - .navbar-form .form-group:last-child { - margin-bottom: 0; - } + .navbar-form .form-group { + margin-bottom: 5px; + } + + .navbar-form .form-group:last-child { + margin-bottom: 0; + } } + @media (min-width: 768px) { - .navbar-form { - width: auto; - padding-top: 0; - padding-bottom: 0; - margin-right: 0; - margin-left: 0; - border: 0; - -webkit-box-shadow: none; - box-shadow: none; - } + .navbar-form { + width: auto; + padding-top: 0; + padding-bottom: 0; + margin-right: 0; + margin-left: 0; + border: 0; + -webkit-box-shadow: none; + box-shadow: none; + } } + .navbar-nav > li > .dropdown-menu { - margin-top: 0; - border-top-left-radius: 0; - border-top-right-radius: 0; + margin-top: 0; + border-top-left-radius: 0; + border-top-right-radius: 0; } + .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu { - border-top-left-radius: 4px; - border-top-right-radius: 4px; - border-bottom-right-radius: 0; - border-bottom-left-radius: 0; + border-top-left-radius: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; } + .navbar-btn { - margin-top: 8px; - margin-bottom: 8px; + margin-top: 8px; + margin-bottom: 8px; } + .navbar-btn.btn-sm { - margin-top: 10px; - margin-bottom: 10px; + margin-top: 10px; + margin-bottom: 10px; } + .navbar-btn.btn-xs { - margin-top: 14px; - margin-bottom: 14px; + margin-top: 14px; + margin-bottom: 14px; } + .navbar-text { - margin-top: 15px; - margin-bottom: 15px; + margin-top: 15px; + margin-bottom: 15px; } + @media (min-width: 768px) { - .navbar-text { - float: left; - margin-right: 15px; - margin-left: 15px; - } + .navbar-text { + float: left; + margin-right: 15px; + margin-left: 15px; + } } + @media (min-width: 768px) { - .navbar-left { - float: left !important; - } - .navbar-right { - float: right !important; - margin-right: -15px; - } - .navbar-right ~ .navbar-right { - margin-right: 0; - } + .navbar-left { + float: left !important; + } + + .navbar-right { + float: right !important; + margin-right: -15px; + } + + .navbar-right ~ .navbar-right { + margin-right: 0; + } } + .navbar-default { - background-color: #f8f8f8; - border-color: #e7e7e7; + background-color: #f8f8f8; + border-color: #e7e7e7; } + .navbar-default .navbar-brand { - color: #777; + color: #777; } + .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { - color: #5e5e5e; - background-color: transparent; + color: #5e5e5e; + background-color: transparent; } + .navbar-default .navbar-text { - color: #777; + color: #777; } + .navbar-default .navbar-nav > li > a { - color: #777; + color: #777; } + .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { - color: #333; - background-color: transparent; + color: #333; + background-color: transparent; } + .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { - color: #555; - background-color: #e7e7e7; + color: #555; + background-color: #e7e7e7; } + .navbar-default .navbar-nav > .disabled > a, .navbar-default .navbar-nav > .disabled > a:hover, .navbar-default .navbar-nav > .disabled > a:focus { - color: #ccc; - background-color: transparent; + color: #ccc; + background-color: transparent; } + .navbar-default .navbar-toggle { - border-color: #ddd; + border-color: #ddd; } + .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { - background-color: #ddd; + background-color: #ddd; } + .navbar-default .navbar-toggle .icon-bar { - background-color: #888; + background-color: #888; } + .navbar-default .navbar-collapse, .navbar-default .navbar-form { - border-color: #e7e7e7; + border-color: #e7e7e7; } + .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { - color: #555; - background-color: #e7e7e7; -} -@media (max-width: 767px) { - .navbar-default .navbar-nav .open .dropdown-menu > li > a { - color: #777; - } - .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, - .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { - color: #333; - background-color: transparent; - } - .navbar-default .navbar-nav .open .dropdown-menu > .active > a, - .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, - .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { color: #555; background-color: #e7e7e7; - } - .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, - .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, - .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { - color: #ccc; - background-color: transparent; - } } + +@media (max-width: 767px) { + .navbar-default .navbar-nav .open .dropdown-menu > li > a { + color: #777; + } + + .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { + color: #333; + background-color: transparent; + } + + .navbar-default .navbar-nav .open .dropdown-menu > .active > a, + .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { + color: #555; + background-color: #e7e7e7; + } + + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { + color: #ccc; + background-color: transparent; + } +} + .navbar-default .navbar-link { - color: #777; + color: #777; } + .navbar-default .navbar-link:hover { - color: #333; + color: #333; } + .navbar-default .btn-link { - color: #777; + color: #777; } + .navbar-default .btn-link:hover, .navbar-default .btn-link:focus { - color: #333; + color: #333; } + .navbar-default .btn-link[disabled]:hover, fieldset[disabled] .navbar-default .btn-link:hover, .navbar-default .btn-link[disabled]:focus, fieldset[disabled] .navbar-default .btn-link:focus { - color: #ccc; + color: #ccc; } + .navbar-inverse { - background-color: #222; - border-color: #080808; + background-color: #222; + border-color: #080808; } + .navbar-inverse .navbar-brand { - color: #9d9d9d; + color: #9d9d9d; } + .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus { - color: #fff; - background-color: transparent; + color: #fff; + background-color: transparent; } + .navbar-inverse .navbar-text { - color: #9d9d9d; + color: #9d9d9d; } + .navbar-inverse .navbar-nav > li > a { - color: #9d9d9d; + color: #9d9d9d; } + .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { - color: #fff; - background-color: transparent; + color: #fff; + background-color: transparent; } + .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { - color: #fff; - background-color: #080808; + color: #fff; + background-color: #080808; } + .navbar-inverse .navbar-nav > .disabled > a, .navbar-inverse .navbar-nav > .disabled > a:hover, .navbar-inverse .navbar-nav > .disabled > a:focus { - color: #444; - background-color: transparent; + color: #444; + background-color: transparent; } + .navbar-inverse .navbar-toggle { - border-color: #333; + border-color: #333; } + .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus { - background-color: #333; + background-color: #333; } + .navbar-inverse .navbar-toggle .icon-bar { - background-color: #fff; + background-color: #fff; } + .navbar-inverse .navbar-collapse, .navbar-inverse .navbar-form { - border-color: #101010; + border-color: #101010; } + .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus { - color: #fff; - background-color: #080808; -} -@media (max-width: 767px) { - .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header { - border-color: #080808; - } - .navbar-inverse .navbar-nav .open .dropdown-menu .divider { - background-color: #080808; - } - .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { - color: #9d9d9d; - } - .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, - .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { - color: #fff; - background-color: transparent; - } - .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a, - .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover, - .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus { color: #fff; background-color: #080808; - } - .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a, - .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover, - .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus { - color: #444; - background-color: transparent; - } } + +@media (max-width: 767px) { + .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header { + border-color: #080808; + } + + .navbar-inverse .navbar-nav .open .dropdown-menu .divider { + background-color: #080808; + } + + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { + color: #9d9d9d; + } + + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { + color: #fff; + background-color: transparent; + } + + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a, + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus { + color: #fff; + background-color: #080808; + } + + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a, + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus { + color: #444; + background-color: transparent; + } +} + .navbar-inverse .navbar-link { - color: #9d9d9d; + color: #9d9d9d; } + .navbar-inverse .navbar-link:hover { - color: #fff; + color: #fff; } + .navbar-inverse .btn-link { - color: #9d9d9d; + color: #9d9d9d; } + .navbar-inverse .btn-link:hover, .navbar-inverse .btn-link:focus { - color: #fff; + color: #fff; } + .navbar-inverse .btn-link[disabled]:hover, fieldset[disabled] .navbar-inverse .btn-link:hover, .navbar-inverse .btn-link[disabled]:focus, fieldset[disabled] .navbar-inverse .btn-link:focus { - color: #444; + color: #444; } + .pagination { - display: inline-block; - padding-left: 0; - margin: 20px 0; - border-radius: 4px; + display: inline-block; + padding-left: 0; + margin: 20px 0; + border-radius: 4px; } + .pagination > li { - display: inline; + display: inline; } + .pagination > li > a, .pagination > li > span { - position: relative; - float: left; - padding: 6px 12px; - margin-left: -1px; - line-height: 1.42857143; - color: #337ab7; - text-decoration: none; - background-color: #fff; - border: 1px solid #ddd; + position: relative; + float: left; + padding: 6px 12px; + margin-left: -1px; + line-height: 1.42857143; + color: #337ab7; + text-decoration: none; + background-color: #fff; + border: 1px solid #ddd; } + .pagination > li:first-child > a, .pagination > li:first-child > span { - margin-left: 0; - border-top-left-radius: 4px; - border-bottom-left-radius: 4px; + margin-left: 0; + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; } + .pagination > li:last-child > a, .pagination > li:last-child > span { - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; } + .pagination > li > a:hover, .pagination > li > span:hover, .pagination > li > a:focus, .pagination > li > span:focus { - color: #23527c; - background-color: #eee; - border-color: #ddd; + color: #23527c; + background-color: #eee; + border-color: #ddd; } + .pagination > .active > a, .pagination > .active > span, .pagination > .active > a:hover, .pagination > .active > span:hover, .pagination > .active > a:focus, .pagination > .active > span:focus { - z-index: 2; - color: #fff; - cursor: default; - background-color: #337ab7; - border-color: #337ab7; + z-index: 2; + color: #fff; + cursor: default; + background-color: #337ab7; + border-color: #337ab7; } + .pagination > .disabled > span, .pagination > .disabled > span:hover, .pagination > .disabled > span:focus, .pagination > .disabled > a, .pagination > .disabled > a:hover, .pagination > .disabled > a:focus { - color: #777; - cursor: not-allowed; - background-color: #fff; - border-color: #ddd; + color: #777; + cursor: not-allowed; + background-color: #fff; + border-color: #ddd; } + .pagination-lg > li > a, .pagination-lg > li > span { - padding: 10px 16px; - font-size: 18px; + padding: 10px 16px; + font-size: 18px; } + .pagination-lg > li:first-child > a, .pagination-lg > li:first-child > span { - border-top-left-radius: 6px; - border-bottom-left-radius: 6px; + border-top-left-radius: 6px; + border-bottom-left-radius: 6px; } + .pagination-lg > li:last-child > a, .pagination-lg > li:last-child > span { - border-top-right-radius: 6px; - border-bottom-right-radius: 6px; + border-top-right-radius: 6px; + border-bottom-right-radius: 6px; } + .pagination-sm > li > a, .pagination-sm > li > span { - padding: 5px 10px; - font-size: 12px; + padding: 5px 10px; + font-size: 12px; } + .pagination-sm > li:first-child > a, .pagination-sm > li:first-child > span { - border-top-left-radius: 3px; - border-bottom-left-radius: 3px; + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; } + .pagination-sm > li:last-child > a, .pagination-sm > li:last-child > span { - border-top-right-radius: 3px; - border-bottom-right-radius: 3px; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; } + .pager { - padding-left: 0; - margin: 20px 0; - text-align: center; - list-style: none; + padding-left: 0; + margin: 20px 0; + text-align: center; + list-style: none; } + .pager li { - display: inline; + display: inline; } + .pager li > a, .pager li > span { - display: inline-block; - padding: 5px 14px; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 15px; + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 15px; } + .pager li > a:hover, .pager li > a:focus { - text-decoration: none; - background-color: #eee; + text-decoration: none; + background-color: #eee; } + .pager .next > a, .pager .next > span { - float: right; + float: right; } + .pager .previous > a, .pager .previous > span { - float: left; + float: left; } + .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { - color: #777; - cursor: not-allowed; - background-color: #fff; + color: #777; + cursor: not-allowed; + background-color: #fff; } + .label { - display: inline; - padding: .2em .6em .3em; - font-size: 75%; - font-weight: bold; - line-height: 1; - color: #fff; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - border-radius: .25em; + display: inline; + padding: .2em .6em .3em; + font-size: 75%; + font-weight: bold; + line-height: 1; + color: #fff; + text-align: center; + white-space: nowrap; + vertical-align: baseline; + border-radius: .25em; } + a.label:hover, a.label:focus { - color: #fff; - text-decoration: none; - cursor: pointer; + color: #fff; + text-decoration: none; + cursor: pointer; } + .label:empty { - display: none; + display: none; } + .btn .label { - position: relative; - top: -1px; + position: relative; + top: -1px; } + .label-default { - background-color: #777; + background-color: #777; } + .label-default[href]:hover, .label-default[href]:focus { - background-color: #5e5e5e; + background-color: #5e5e5e; } + .label-primary { - background-color: #337ab7; + background-color: #337ab7; } + .label-primary[href]:hover, .label-primary[href]:focus { - background-color: #286090; + background-color: #286090; } + .label-success { - background-color: #5cb85c; + background-color: #5cb85c; } + .label-success[href]:hover, .label-success[href]:focus { - background-color: #449d44; + background-color: #449d44; } + .label-info { - background-color: #5bc0de; + background-color: #5bc0de; } + .label-info[href]:hover, .label-info[href]:focus { - background-color: #31b0d5; + background-color: #31b0d5; } + .label-warning { - background-color: #f0ad4e; + background-color: #f0ad4e; } + .label-warning[href]:hover, .label-warning[href]:focus { - background-color: #ec971f; + background-color: #ec971f; } + .label-danger { - background-color: #d9534f; + background-color: #d9534f; } + .label-danger[href]:hover, .label-danger[href]:focus { - background-color: #c9302c; + background-color: #c9302c; } + .badge { - display: inline-block; - min-width: 10px; - padding: 3px 7px; - font-size: 12px; - font-weight: bold; - line-height: 1; - color: #fff; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - background-color: #777; - border-radius: 10px; + display: inline-block; + min-width: 10px; + padding: 3px 7px; + font-size: 12px; + font-weight: bold; + line-height: 1; + color: #fff; + text-align: center; + white-space: nowrap; + vertical-align: baseline; + background-color: #777; + border-radius: 10px; } + .badge:empty { - display: none; + display: none; } + .btn .badge { - position: relative; - top: -1px; + position: relative; + top: -1px; } + .btn-xs .badge { - top: 0; - padding: 1px 5px; + top: 0; + padding: 1px 5px; } + a.badge:hover, a.badge:focus { - color: #fff; - text-decoration: none; - cursor: pointer; + color: #fff; + text-decoration: none; + cursor: pointer; } + .list-group-item.active > .badge, .nav-pills > .active > a > .badge { - color: #337ab7; - background-color: #fff; + color: #337ab7; + background-color: #fff; } + .list-group-item > .badge { - float: right; + float: right; } + .list-group-item > .badge + .badge { - margin-right: 5px; + margin-right: 5px; } + .nav-pills > li > a > .badge { - margin-left: 3px; + margin-left: 3px; } + .jumbotron { - padding: 30px 15px; - margin-bottom: 30px; - color: inherit; - background-color: #eee; + padding: 30px 15px; + margin-bottom: 30px; + color: inherit; + background-color: #eee; } + .jumbotron h1, .jumbotron .h1 { - color: inherit; + color: inherit; } + .jumbotron p { - margin-bottom: 15px; - font-size: 21px; - font-weight: 200; + margin-bottom: 15px; + font-size: 21px; + font-weight: 200; } + .jumbotron > hr { - border-top-color: #d5d5d5; + border-top-color: #d5d5d5; } + .container .jumbotron, .container-fluid .jumbotron { - border-radius: 6px; + border-radius: 6px; } + .jumbotron .container { - max-width: 100%; + max-width: 100%; } + @media screen and (min-width: 768px) { - .jumbotron { - padding: 48px 0; - } - .container .jumbotron, - .container-fluid .jumbotron { - padding-right: 60px; - padding-left: 60px; - } - .jumbotron h1, - .jumbotron .h1 { - font-size: 63px; - } + .jumbotron { + padding: 48px 0; + } + + .container .jumbotron, + .container-fluid .jumbotron { + padding-right: 60px; + padding-left: 60px; + } + + .jumbotron h1, + .jumbotron .h1 { + font-size: 63px; + } } + .thumbnail { - display: block; - padding: 4px; - margin-bottom: 20px; - line-height: 1.42857143; - background-color: #fff; - border: 1px solid #ddd; - border-radius: 4px; - -webkit-transition: border .2s ease-in-out; - -o-transition: border .2s ease-in-out; - transition: border .2s ease-in-out; + display: block; + padding: 4px; + margin-bottom: 20px; + line-height: 1.42857143; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + -webkit-transition: border .2s ease-in-out; + -o-transition: border .2s ease-in-out; + transition: border .2s ease-in-out; } + .thumbnail > img, .thumbnail a > img { - margin-right: auto; - margin-left: auto; + margin-right: auto; + margin-left: auto; } + a.thumbnail:hover, a.thumbnail:focus, a.thumbnail.active { - border-color: #337ab7; + border-color: #337ab7; } + .thumbnail .caption { - padding: 9px; - color: #333; + padding: 9px; + color: #333; } + .alert { - padding: 15px; - margin-bottom: 20px; - border: 1px solid transparent; - border-radius: 4px; + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; } + .alert h4 { - margin-top: 0; - color: inherit; + margin-top: 0; + color: inherit; } + .alert .alert-link { - font-weight: bold; + font-weight: bold; } + .alert > p, .alert > ul { - margin-bottom: 0; + margin-bottom: 0; } + .alert > p + p { - margin-top: 5px; + margin-top: 5px; } + .alert-dismissable, .alert-dismissible { - padding-right: 35px; + padding-right: 35px; } + .alert-dismissable .close, .alert-dismissible .close { - position: relative; - top: -2px; - right: -21px; - color: inherit; + position: relative; + top: -2px; + right: -21px; + color: inherit; } + .alert-success { - color: #3c763d; - background-color: #dff0d8; - border-color: #d6e9c6; + color: #3c763d; + background-color: #dff0d8; + border-color: #d6e9c6; } + .alert-success hr { - border-top-color: #c9e2b3; + border-top-color: #c9e2b3; } + .alert-success .alert-link { - color: #2b542c; + color: #2b542c; } + .alert-info { - color: #31708f; - background-color: #d9edf7; - border-color: #bce8f1; + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; } + .alert-info hr { - border-top-color: #a6e1ec; + border-top-color: #a6e1ec; } + .alert-info .alert-link { - color: #245269; + color: #245269; } + .alert-warning { - color: #8a6d3b; - background-color: #fcf8e3; - border-color: #faebcc; + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; } + .alert-warning hr { - border-top-color: #f7e1b5; + border-top-color: #f7e1b5; } + .alert-warning .alert-link { - color: #66512c; + color: #66512c; } + .alert-danger { - color: #a94442; - background-color: #f2dede; - border-color: #ebccd1; + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; } + .alert-danger hr { - border-top-color: #e4b9c0; + border-top-color: #e4b9c0; } + .alert-danger .alert-link { - color: #843534; + color: #843534; } + @-webkit-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } + @-o-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } + @keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } + .progress { - height: 20px; - margin-bottom: 20px; - overflow: hidden; - background-color: #f5f5f5; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); + height: 20px; + margin-bottom: 20px; + overflow: hidden; + background-color: #f5f5f5; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); } + .progress-bar { - float: left; - width: 0; - height: 100%; - font-size: 12px; - line-height: 20px; - color: #fff; - text-align: center; - background-color: #337ab7; - -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); - box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); - -webkit-transition: width .6s ease; - -o-transition: width .6s ease; - transition: width .6s ease; + float: left; + width: 0; + height: 100%; + font-size: 12px; + line-height: 20px; + color: #fff; + text-align: center; + background-color: #337ab7; + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); + -webkit-transition: width .6s ease; + -o-transition: width .6s ease; + transition: width .6s ease; } + .progress-striped .progress-bar, .progress-bar-striped { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - -webkit-background-size: 40px 40px; - background-size: 40px 40px; + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + -webkit-background-size: 40px 40px; + background-size: 40px 40px; } + .progress.active .progress-bar, .progress-bar.active { - -webkit-animation: progress-bar-stripes 2s linear infinite; - -o-animation: progress-bar-stripes 2s linear infinite; - animation: progress-bar-stripes 2s linear infinite; + -webkit-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; } + .progress-bar-success { - background-color: #5cb85c; + background-color: #5cb85c; } + .progress-striped .progress-bar-success { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } + .progress-bar-info { - background-color: #5bc0de; + background-color: #5bc0de; } + .progress-striped .progress-bar-info { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } + .progress-bar-warning { - background-color: #f0ad4e; + background-color: #f0ad4e; } + .progress-striped .progress-bar-warning { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } + .progress-bar-danger { - background-color: #d9534f; + background-color: #d9534f; } + .progress-striped .progress-bar-danger { - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } + .media { - margin-top: 15px; + margin-top: 15px; } + .media:first-child { - margin-top: 0; + margin-top: 0; } + .media-right, .media > .pull-right { - padding-left: 10px; + padding-left: 10px; } + .media-left, .media > .pull-left { - padding-right: 10px; + padding-right: 10px; } + .media-left, .media-right, .media-body { - display: table-cell; - vertical-align: top; + display: table-cell; + vertical-align: top; } + .media-middle { - vertical-align: middle; + vertical-align: middle; } + .media-bottom { - vertical-align: bottom; + vertical-align: bottom; } + .media-heading { - margin-top: 0; - margin-bottom: 5px; + margin-top: 0; + margin-bottom: 5px; } + .media-list { - padding-left: 0; - list-style: none; + padding-left: 0; + list-style: none; } + .list-group { - padding-left: 0; - margin-bottom: 20px; + padding-left: 0; + margin-bottom: 20px; } + .list-group-item { - position: relative; - display: block; - padding: 10px 15px; - margin-bottom: -1px; - background-color: #fff; - border: 1px solid #ddd; + position: relative; + display: block; + padding: 10px 15px; + margin-bottom: -1px; + background-color: #fff; + border: 1px solid #ddd; } + .list-group-item:first-child { - border-top-left-radius: 4px; - border-top-right-radius: 4px; + border-top-left-radius: 4px; + border-top-right-radius: 4px; } + .list-group-item:last-child { - margin-bottom: 0; - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; + margin-bottom: 0; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; } + a.list-group-item { - color: #555; + color: #555; } + a.list-group-item .list-group-item-heading { - color: #333; + color: #333; } + a.list-group-item:hover, a.list-group-item:focus { - color: #555; - text-decoration: none; - background-color: #f5f5f5; + color: #555; + text-decoration: none; + background-color: #f5f5f5; } + .list-group-item.disabled, .list-group-item.disabled:hover, .list-group-item.disabled:focus { - color: #777; - cursor: not-allowed; - background-color: #eee; + color: #777; + cursor: not-allowed; + background-color: #eee; } + .list-group-item.disabled .list-group-item-heading, .list-group-item.disabled:hover .list-group-item-heading, .list-group-item.disabled:focus .list-group-item-heading { - color: inherit; + color: inherit; } + .list-group-item.disabled .list-group-item-text, .list-group-item.disabled:hover .list-group-item-text, .list-group-item.disabled:focus .list-group-item-text { - color: #777; + color: #777; } + .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { - z-index: 2; - color: #fff; - background-color: #337ab7; - border-color: #337ab7; + z-index: 2; + color: #fff; + background-color: #337ab7; + border-color: #337ab7; } + .list-group-item.active .list-group-item-heading, .list-group-item.active:hover .list-group-item-heading, .list-group-item.active:focus .list-group-item-heading, @@ -4936,195 +6021,236 @@ a.list-group-item:focus { .list-group-item.active .list-group-item-heading > .small, .list-group-item.active:hover .list-group-item-heading > .small, .list-group-item.active:focus .list-group-item-heading > .small { - color: inherit; + color: inherit; } + .list-group-item.active .list-group-item-text, .list-group-item.active:hover .list-group-item-text, .list-group-item.active:focus .list-group-item-text { - color: #c7ddef; + color: #c7ddef; } + .list-group-item-success { - color: #3c763d; - background-color: #dff0d8; + color: #3c763d; + background-color: #dff0d8; } + a.list-group-item-success { - color: #3c763d; + color: #3c763d; } + a.list-group-item-success .list-group-item-heading { - color: inherit; + color: inherit; } + a.list-group-item-success:hover, a.list-group-item-success:focus { - color: #3c763d; - background-color: #d0e9c6; + color: #3c763d; + background-color: #d0e9c6; } + a.list-group-item-success.active, a.list-group-item-success.active:hover, a.list-group-item-success.active:focus { - color: #fff; - background-color: #3c763d; - border-color: #3c763d; + color: #fff; + background-color: #3c763d; + border-color: #3c763d; } + .list-group-item-info { - color: #31708f; - background-color: #d9edf7; + color: #31708f; + background-color: #d9edf7; } + a.list-group-item-info { - color: #31708f; + color: #31708f; } + a.list-group-item-info .list-group-item-heading { - color: inherit; + color: inherit; } + a.list-group-item-info:hover, a.list-group-item-info:focus { - color: #31708f; - background-color: #c4e3f3; + color: #31708f; + background-color: #c4e3f3; } + a.list-group-item-info.active, a.list-group-item-info.active:hover, a.list-group-item-info.active:focus { - color: #fff; - background-color: #31708f; - border-color: #31708f; + color: #fff; + background-color: #31708f; + border-color: #31708f; } + .list-group-item-warning { - color: #8a6d3b; - background-color: #fcf8e3; + color: #8a6d3b; + background-color: #fcf8e3; } + a.list-group-item-warning { - color: #8a6d3b; + color: #8a6d3b; } + a.list-group-item-warning .list-group-item-heading { - color: inherit; + color: inherit; } + a.list-group-item-warning:hover, a.list-group-item-warning:focus { - color: #8a6d3b; - background-color: #faf2cc; + color: #8a6d3b; + background-color: #faf2cc; } + a.list-group-item-warning.active, a.list-group-item-warning.active:hover, a.list-group-item-warning.active:focus { - color: #fff; - background-color: #8a6d3b; - border-color: #8a6d3b; + color: #fff; + background-color: #8a6d3b; + border-color: #8a6d3b; } + .list-group-item-danger { - color: #a94442; - background-color: #f2dede; + color: #a94442; + background-color: #f2dede; } + a.list-group-item-danger { - color: #a94442; + color: #a94442; } + a.list-group-item-danger .list-group-item-heading { - color: inherit; + color: inherit; } + a.list-group-item-danger:hover, a.list-group-item-danger:focus { - color: #a94442; - background-color: #ebcccc; + color: #a94442; + background-color: #ebcccc; } + a.list-group-item-danger.active, a.list-group-item-danger.active:hover, a.list-group-item-danger.active:focus { - color: #fff; - background-color: #a94442; - border-color: #a94442; + color: #fff; + background-color: #a94442; + border-color: #a94442; } + .list-group-item-heading { - margin-top: 0; - margin-bottom: 5px; + margin-top: 0; + margin-bottom: 5px; } + .list-group-item-text { - margin-bottom: 0; - line-height: 1.3; + margin-bottom: 0; + line-height: 1.3; } + .panel { - margin-bottom: 20px; - background-color: #fff; - border: 1px solid transparent; - border-radius: 4px; - -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05); - box-shadow: 0 1px 1px rgba(0, 0, 0, .05); + margin-bottom: 20px; + background-color: #fff; + border: 1px solid transparent; + border-radius: 4px; + -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05); + box-shadow: 0 1px 1px rgba(0, 0, 0, .05); } + .panel-body { - padding: 15px; + padding: 15px; } + .panel-heading { - padding: 10px 15px; - border-bottom: 1px solid transparent; - border-top-left-radius: 3px; - border-top-right-radius: 3px; + padding: 10px 15px; + border-bottom: 1px solid transparent; + border-top-left-radius: 3px; + border-top-right-radius: 3px; } + .panel-heading > .dropdown .dropdown-toggle { - color: inherit; + color: inherit; } + .panel-title { - margin-top: 0; - margin-bottom: 0; - font-size: 16px; - color: inherit; + margin-top: 0; + margin-bottom: 0; + font-size: 16px; + color: inherit; } + .panel-title > a { - color: inherit; + color: inherit; } + .panel-footer { - padding: 10px 15px; - background-color: #f5f5f5; - border-top: 1px solid #ddd; - border-bottom-right-radius: 3px; - border-bottom-left-radius: 3px; + padding: 10px 15px; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; } + .panel > .list-group, .panel > .panel-collapse > .list-group { - margin-bottom: 0; + margin-bottom: 0; } + .panel > .list-group .list-group-item, .panel > .panel-collapse > .list-group .list-group-item { - border-width: 1px 0; - border-radius: 0; + border-width: 1px 0; + border-radius: 0; } + .panel > .list-group:first-child .list-group-item:first-child, .panel > .panel-collapse > .list-group:first-child .list-group-item:first-child { - border-top: 0; - border-top-left-radius: 3px; - border-top-right-radius: 3px; + border-top: 0; + border-top-left-radius: 3px; + border-top-right-radius: 3px; } + .panel > .list-group:last-child .list-group-item:last-child, .panel > .panel-collapse > .list-group:last-child .list-group-item:last-child { - border-bottom: 0; - border-bottom-right-radius: 3px; - border-bottom-left-radius: 3px; + border-bottom: 0; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; } + .panel-heading + .list-group .list-group-item:first-child { - border-top-width: 0; + border-top-width: 0; } + .list-group + .panel-footer { - border-top-width: 0; + border-top-width: 0; } + .panel > .table, .panel > .table-responsive > .table, .panel > .panel-collapse > .table { - margin-bottom: 0; + margin-bottom: 0; } + .panel > .table caption, .panel > .table-responsive > .table caption, .panel > .panel-collapse > .table caption { - padding-right: 15px; - padding-left: 15px; + padding-right: 15px; + padding-left: 15px; } + .panel > .table:first-child, .panel > .table-responsive:first-child > .table:first-child { - border-top-left-radius: 3px; - border-top-right-radius: 3px; + border-top-left-radius: 3px; + border-top-right-radius: 3px; } + .panel > .table:first-child > thead:first-child > tr:first-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child { - border-top-left-radius: 3px; - border-top-right-radius: 3px; + border-top-left-radius: 3px; + border-top-right-radius: 3px; } + .panel > .table:first-child > thead:first-child > tr:first-child td:first-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child td:first-child, @@ -5133,8 +6259,9 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child th:first-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child { - border-top-left-radius: 3px; + border-top-left-radius: 3px; } + .panel > .table:first-child > thead:first-child > tr:first-child td:last-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child, .panel > .table:first-child > tbody:first-child > tr:first-child td:last-child, @@ -5143,20 +6270,23 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child, .panel > .table:first-child > tbody:first-child > tr:first-child th:last-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child { - border-top-right-radius: 3px; + border-top-right-radius: 3px; } + .panel > .table:last-child, .panel > .table-responsive:last-child > .table:last-child { - border-bottom-right-radius: 3px; - border-bottom-left-radius: 3px; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; } + .panel > .table:last-child > tbody:last-child > tr:last-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child { - border-bottom-right-radius: 3px; - border-bottom-left-radius: 3px; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; } + .panel > .table:last-child > tbody:last-child > tr:last-child td:first-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child, .panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child, @@ -5165,8 +6295,9 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child, .panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child { - border-bottom-left-radius: 3px; + border-bottom-left-radius: 3px; } + .panel > .table:last-child > tbody:last-child > tr:last-child td:last-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child, @@ -5175,22 +6306,26 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child { - border-bottom-right-radius: 3px; + border-bottom-right-radius: 3px; } + .panel > .panel-body + .table, .panel > .panel-body + .table-responsive, .panel > .table + .panel-body, .panel > .table-responsive + .panel-body { - border-top: 1px solid #ddd; + border-top: 1px solid #ddd; } + .panel > .table > tbody:first-child > tr:first-child th, .panel > .table > tbody:first-child > tr:first-child td { - border-top: 0; + border-top: 0; } + .panel > .table-bordered, .panel > .table-responsive > .table-bordered { - border: 0; + border: 0; } + .panel > .table-bordered > thead > tr > th:first-child, .panel > .table-responsive > .table-bordered > thead > tr > th:first-child, .panel > .table-bordered > tbody > tr > th:first-child, @@ -5203,8 +6338,9 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive > .table-bordered > tbody > tr > td:first-child, .panel > .table-bordered > tfoot > tr > td:first-child, .panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child { - border-left: 0; + border-left: 0; } + .panel > .table-bordered > thead > tr > th:last-child, .panel > .table-responsive > .table-bordered > thead > tr > th:last-child, .panel > .table-bordered > tbody > tr > th:last-child, @@ -5217,8 +6353,9 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive > .table-bordered > tbody > tr > td:last-child, .panel > .table-bordered > tfoot > tr > td:last-child, .panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child { - border-right: 0; + border-right: 0; } + .panel > .table-bordered > thead > tr:first-child > td, .panel > .table-responsive > .table-bordered > thead > tr:first-child > td, .panel > .table-bordered > tbody > tr:first-child > td, @@ -5227,8 +6364,9 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive > .table-bordered > thead > tr:first-child > th, .panel > .table-bordered > tbody > tr:first-child > th, .panel > .table-responsive > .table-bordered > tbody > tr:first-child > th { - border-bottom: 0; + border-bottom: 0; } + .panel > .table-bordered > tbody > tr:last-child > td, .panel > .table-responsive > .table-bordered > tbody > tr:last-child > td, .panel > .table-bordered > tfoot > tr:last-child > td, @@ -5237,786 +6375,929 @@ a.list-group-item-danger.active:focus { .panel > .table-responsive > .table-bordered > tbody > tr:last-child > th, .panel > .table-bordered > tfoot > tr:last-child > th, .panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th { - border-bottom: 0; + border-bottom: 0; } + .panel > .table-responsive { - margin-bottom: 0; - border: 0; + margin-bottom: 0; + border: 0; } + .panel-group { - margin-bottom: 20px; + margin-bottom: 20px; } + .panel-group .panel { - margin-bottom: 0; - border-radius: 4px; + margin-bottom: 0; + border-radius: 4px; } + .panel-group .panel + .panel { - margin-top: 5px; + margin-top: 5px; } + .panel-group .panel-heading { - border-bottom: 0; + border-bottom: 0; } + .panel-group .panel-heading + .panel-collapse > .panel-body, .panel-group .panel-heading + .panel-collapse > .list-group { - border-top: 1px solid #ddd; + border-top: 1px solid #ddd; } + .panel-group .panel-footer { - border-top: 0; + border-top: 0; } + .panel-group .panel-footer + .panel-collapse .panel-body { - border-bottom: 1px solid #ddd; + border-bottom: 1px solid #ddd; } + .panel-default { - border-color: #ddd; + border-color: #ddd; } + .panel-default > .panel-heading { - color: #333; - background-color: #f5f5f5; - border-color: #ddd; + color: #333; + background-color: #f5f5f5; + border-color: #ddd; } + .panel-default > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #ddd; + border-top-color: #ddd; } + .panel-default > .panel-heading .badge { - color: #f5f5f5; - background-color: #333; + color: #f5f5f5; + background-color: #333; } + .panel-default > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #ddd; + border-bottom-color: #ddd; } + .panel-primary { - border-color: #337ab7; + border-color: #337ab7; } + .panel-primary > .panel-heading { - color: #fff; - background-color: #337ab7; - border-color: #337ab7; + color: #fff; + background-color: #337ab7; + border-color: #337ab7; } + .panel-primary > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #337ab7; + border-top-color: #337ab7; } + .panel-primary > .panel-heading .badge { - color: #337ab7; - background-color: #fff; + color: #337ab7; + background-color: #fff; } + .panel-primary > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #337ab7; + border-bottom-color: #337ab7; } + .panel-success { - border-color: #d6e9c6; + border-color: #d6e9c6; } + .panel-success > .panel-heading { - color: #3c763d; - background-color: #dff0d8; - border-color: #d6e9c6; + color: #3c763d; + background-color: #dff0d8; + border-color: #d6e9c6; } + .panel-success > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #d6e9c6; + border-top-color: #d6e9c6; } + .panel-success > .panel-heading .badge { - color: #dff0d8; - background-color: #3c763d; + color: #dff0d8; + background-color: #3c763d; } + .panel-success > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #d6e9c6; + border-bottom-color: #d6e9c6; } + .panel-info { - border-color: #bce8f1; + border-color: #bce8f1; } + .panel-info > .panel-heading { - color: #31708f; - background-color: #d9edf7; - border-color: #bce8f1; + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; } + .panel-info > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #bce8f1; + border-top-color: #bce8f1; } + .panel-info > .panel-heading .badge { - color: #d9edf7; - background-color: #31708f; + color: #d9edf7; + background-color: #31708f; } + .panel-info > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #bce8f1; + border-bottom-color: #bce8f1; } + .panel-warning { - border-color: #faebcc; + border-color: #faebcc; } + .panel-warning > .panel-heading { - color: #8a6d3b; - background-color: #fcf8e3; - border-color: #faebcc; + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; } + .panel-warning > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #faebcc; + border-top-color: #faebcc; } + .panel-warning > .panel-heading .badge { - color: #fcf8e3; - background-color: #8a6d3b; + color: #fcf8e3; + background-color: #8a6d3b; } + .panel-warning > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #faebcc; + border-bottom-color: #faebcc; } + .panel-danger { - border-color: #ebccd1; + border-color: #ebccd1; } + .panel-danger > .panel-heading { - color: #a94442; - background-color: #f2dede; - border-color: #ebccd1; + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; } + .panel-danger > .panel-heading + .panel-collapse > .panel-body { - border-top-color: #ebccd1; + border-top-color: #ebccd1; } + .panel-danger > .panel-heading .badge { - color: #f2dede; - background-color: #a94442; + color: #f2dede; + background-color: #a94442; } + .panel-danger > .panel-footer + .panel-collapse > .panel-body { - border-bottom-color: #ebccd1; + border-bottom-color: #ebccd1; } + .embed-responsive { - position: relative; - display: block; - height: 0; - padding: 0; - overflow: hidden; + position: relative; + display: block; + height: 0; + padding: 0; + overflow: hidden; } + .embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 100%; - height: 100%; - border: 0; + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 100%; + height: 100%; + border: 0; } + .embed-responsive.embed-responsive-16by9 { - padding-bottom: 56.25%; + padding-bottom: 56.25%; } + .embed-responsive.embed-responsive-4by3 { - padding-bottom: 75%; + padding-bottom: 75%; } + .well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #e3e3e3; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #e3e3e3; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); } + .well blockquote { - border-color: #ddd; - border-color: rgba(0, 0, 0, .15); + border-color: #ddd; + border-color: rgba(0, 0, 0, .15); } + .well-lg { - padding: 24px; - border-radius: 6px; + padding: 24px; + border-radius: 6px; } + .well-sm { - padding: 9px; - border-radius: 3px; + padding: 9px; + border-radius: 3px; } + .close { - float: right; - font-size: 21px; - font-weight: bold; - line-height: 1; - color: #000; - text-shadow: 0 1px 0 #fff; - filter: alpha(opacity=20); - opacity: .2; + float: right; + font-size: 21px; + font-weight: bold; + line-height: 1; + color: #000; + text-shadow: 0 1px 0 #fff; + filter: alpha(opacity=20); + opacity: .2; } + .close:hover, .close:focus { - color: #000; - text-decoration: none; - cursor: pointer; - filter: alpha(opacity=50); - opacity: .5; + color: #000; + text-decoration: none; + cursor: pointer; + filter: alpha(opacity=50); + opacity: .5; } + button.close { - -webkit-appearance: none; - padding: 0; - cursor: pointer; - background: transparent; - border: 0; + -webkit-appearance: none; + padding: 0; + cursor: pointer; + background: transparent; + border: 0; } + .modal-open { - overflow: hidden; + overflow: hidden; } + .modal { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - display: none; - overflow: hidden; - -webkit-overflow-scrolling: touch; - outline: 0; + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + display: none; + overflow: hidden; + -webkit-overflow-scrolling: touch; + outline: 0; } + .modal.fade .modal-dialog { - -webkit-transition: -webkit-transform .3s ease-out; - -o-transition: -o-transform .3s ease-out; - transition: transform .3s ease-out; - -webkit-transform: translate(0, -25%); - -ms-transform: translate(0, -25%); - -o-transform: translate(0, -25%); - transform: translate(0, -25%); + -webkit-transition: -webkit-transform .3s ease-out; + -o-transition: -o-transform .3s ease-out; + transition: transform .3s ease-out; + -webkit-transform: translate(0, -25%); + -ms-transform: translate(0, -25%); + -o-transform: translate(0, -25%); + transform: translate(0, -25%); } + .modal.in .modal-dialog { - -webkit-transform: translate(0, 0); - -ms-transform: translate(0, 0); - -o-transform: translate(0, 0); - transform: translate(0, 0); + -webkit-transform: translate(0, 0); + -ms-transform: translate(0, 0); + -o-transform: translate(0, 0); + transform: translate(0, 0); } + .modal-open .modal { - overflow-x: hidden; - overflow-y: auto; + overflow-x: hidden; + overflow-y: auto; } + .modal-dialog { - position: relative; - width: auto; - margin: 10px; + position: relative; + width: auto; + margin: 10px; } + .modal-content { - position: relative; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #999; - border: 1px solid rgba(0, 0, 0, .2); - border-radius: 6px; - outline: 0; - -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5); - box-shadow: 0 3px 9px rgba(0, 0, 0, .5); + position: relative; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, .2); + border-radius: 6px; + outline: 0; + -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5); + box-shadow: 0 3px 9px rgba(0, 0, 0, .5); } + .modal-backdrop { - position: absolute; - top: 0; - right: 0; - left: 0; - background-color: #000; + position: absolute; + top: 0; + right: 0; + left: 0; + background-color: #000; } + .modal-backdrop.fade { - filter: alpha(opacity=0); - opacity: 0; + filter: alpha(opacity=0); + opacity: 0; } + .modal-backdrop.in { - filter: alpha(opacity=50); - opacity: .5; + filter: alpha(opacity=50); + opacity: .5; } + .modal-header { - min-height: 16.42857143px; - padding: 15px; - border-bottom: 1px solid #e5e5e5; + min-height: 16.42857143px; + padding: 15px; + border-bottom: 1px solid #e5e5e5; } + .modal-header .close { - margin-top: -2px; + margin-top: -2px; } + .modal-title { - margin: 0; - line-height: 1.42857143; + margin: 0; + line-height: 1.42857143; } + .modal-body { - position: relative; - padding: 15px; + position: relative; + padding: 15px; } + .modal-footer { - padding: 15px; - text-align: right; - border-top: 1px solid #e5e5e5; + padding: 15px; + text-align: right; + border-top: 1px solid #e5e5e5; } + .modal-footer .btn + .btn { - margin-bottom: 0; - margin-left: 5px; + margin-bottom: 0; + margin-left: 5px; } + .modal-footer .btn-group .btn + .btn { - margin-left: -1px; + margin-left: -1px; } + .modal-footer .btn-block + .btn-block { - margin-left: 0; + margin-left: 0; } + .modal-scrollbar-measure { - position: absolute; - top: -9999px; - width: 50px; - height: 50px; - overflow: scroll; + position: absolute; + top: -9999px; + width: 50px; + height: 50px; + overflow: scroll; } + @media (min-width: 768px) { - .modal-dialog { - width: 600px; - margin: 30px auto; - } - .modal-content { - -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5); - box-shadow: 0 5px 15px rgba(0, 0, 0, .5); - } - .modal-sm { - width: 300px; - } + .modal-dialog { + width: 600px; + margin: 30px auto; + } + + .modal-content { + -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5); + box-shadow: 0 5px 15px rgba(0, 0, 0, .5); + } + + .modal-sm { + width: 300px; + } } + @media (min-width: 992px) { - .modal-lg { - width: 900px; - } + .modal-lg { + width: 900px; + } } + .tooltip { - position: absolute; - z-index: 1070; - display: block; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 12px; - font-weight: normal; - line-height: 1.4; - visibility: visible; - filter: alpha(opacity=0); - opacity: 0; + position: absolute; + z-index: 1070; + display: block; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 12px; + font-weight: normal; + line-height: 1.4; + visibility: visible; + filter: alpha(opacity=0); + opacity: 0; } + .tooltip.in { - filter: alpha(opacity=90); - opacity: .9; + filter: alpha(opacity=90); + opacity: .9; } + .tooltip.top { - padding: 5px 0; - margin-top: -3px; + padding: 5px 0; + margin-top: -3px; } + .tooltip.right { - padding: 0 5px; - margin-left: 3px; + padding: 0 5px; + margin-left: 3px; } + .tooltip.bottom { - padding: 5px 0; - margin-top: 3px; + padding: 5px 0; + margin-top: 3px; } + .tooltip.left { - padding: 0 5px; - margin-left: -3px; + padding: 0 5px; + margin-left: -3px; } + .tooltip-inner { - max-width: 200px; - padding: 3px 8px; - color: #fff; - text-align: center; - text-decoration: none; - background-color: #000; - border-radius: 4px; + max-width: 200px; + padding: 3px 8px; + color: #fff; + text-align: center; + text-decoration: none; + background-color: #000; + border-radius: 4px; } + .tooltip-arrow { - position: absolute; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; + position: absolute; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; } + .tooltip.top .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-width: 5px 5px 0; - border-top-color: #000; + bottom: 0; + left: 50%; + margin-left: -5px; + border-width: 5px 5px 0; + border-top-color: #000; } + .tooltip.top-left .tooltip-arrow { - right: 5px; - bottom: 0; - margin-bottom: -5px; - border-width: 5px 5px 0; - border-top-color: #000; + right: 5px; + bottom: 0; + margin-bottom: -5px; + border-width: 5px 5px 0; + border-top-color: #000; } + .tooltip.top-right .tooltip-arrow { - bottom: 0; - left: 5px; - margin-bottom: -5px; - border-width: 5px 5px 0; - border-top-color: #000; + bottom: 0; + left: 5px; + margin-bottom: -5px; + border-width: 5px 5px 0; + border-top-color: #000; } + .tooltip.right .tooltip-arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-width: 5px 5px 5px 0; - border-right-color: #000; + top: 50%; + left: 0; + margin-top: -5px; + border-width: 5px 5px 5px 0; + border-right-color: #000; } + .tooltip.left .tooltip-arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-width: 5px 0 5px 5px; - border-left-color: #000; + top: 50%; + right: 0; + margin-top: -5px; + border-width: 5px 0 5px 5px; + border-left-color: #000; } + .tooltip.bottom .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000; + top: 0; + left: 50%; + margin-left: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; } + .tooltip.bottom-left .tooltip-arrow { - top: 0; - right: 5px; - margin-top: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000; + top: 0; + right: 5px; + margin-top: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; } + .tooltip.bottom-right .tooltip-arrow { - top: 0; - left: 5px; - margin-top: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000; + top: 0; + left: 5px; + margin-top: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; } + .popover { - position: absolute; - top: 0; - left: 0; - z-index: 1060; - display: none; - max-width: 276px; - padding: 1px; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - font-weight: normal; - line-height: 1.42857143; - text-align: left; - white-space: normal; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, .2); - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); - box-shadow: 0 5px 10px rgba(0, 0, 0, .2); + position: absolute; + top: 0; + left: 0; + z-index: 1060; + display: none; + max-width: 276px; + padding: 1px; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + font-weight: normal; + line-height: 1.42857143; + text-align: left; + white-space: normal; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, .2); + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); + box-shadow: 0 5px 10px rgba(0, 0, 0, .2); } + .popover.top { - margin-top: -10px; + margin-top: -10px; } + .popover.right { - margin-left: 10px; + margin-left: 10px; } + .popover.bottom { - margin-top: 10px; + margin-top: 10px; } + .popover.left { - margin-left: -10px; + margin-left: -10px; } + .popover-title { - padding: 8px 14px; - margin: 0; - font-size: 14px; - background-color: #f7f7f7; - border-bottom: 1px solid #ebebeb; - border-radius: 5px 5px 0 0; + padding: 8px 14px; + margin: 0; + font-size: 14px; + background-color: #f7f7f7; + border-bottom: 1px solid #ebebeb; + border-radius: 5px 5px 0 0; } + .popover-content { - padding: 9px 14px; + padding: 9px 14px; } + .popover > .arrow, .popover > .arrow:after { - position: absolute; - display: block; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; } + .popover > .arrow { - border-width: 11px; + border-width: 11px; } + .popover > .arrow:after { - content: ""; - border-width: 10px; + content: ""; + border-width: 10px; } + .popover.top > .arrow { - bottom: -11px; - left: 50%; - margin-left: -11px; - border-top-color: #999; - border-top-color: rgba(0, 0, 0, .25); - border-bottom-width: 0; + bottom: -11px; + left: 50%; + margin-left: -11px; + border-top-color: #999; + border-top-color: rgba(0, 0, 0, .25); + border-bottom-width: 0; } + .popover.top > .arrow:after { - bottom: 1px; - margin-left: -10px; - content: " "; - border-top-color: #fff; - border-bottom-width: 0; + bottom: 1px; + margin-left: -10px; + content: " "; + border-top-color: #fff; + border-bottom-width: 0; } + .popover.right > .arrow { - top: 50%; - left: -11px; - margin-top: -11px; - border-right-color: #999; - border-right-color: rgba(0, 0, 0, .25); - border-left-width: 0; + top: 50%; + left: -11px; + margin-top: -11px; + border-right-color: #999; + border-right-color: rgba(0, 0, 0, .25); + border-left-width: 0; } + .popover.right > .arrow:after { - bottom: -10px; - left: 1px; - content: " "; - border-right-color: #fff; - border-left-width: 0; + bottom: -10px; + left: 1px; + content: " "; + border-right-color: #fff; + border-left-width: 0; } + .popover.bottom > .arrow { - top: -11px; - left: 50%; - margin-left: -11px; - border-top-width: 0; - border-bottom-color: #999; - border-bottom-color: rgba(0, 0, 0, .25); + top: -11px; + left: 50%; + margin-left: -11px; + border-top-width: 0; + border-bottom-color: #999; + border-bottom-color: rgba(0, 0, 0, .25); } + .popover.bottom > .arrow:after { - top: 1px; - margin-left: -10px; - content: " "; - border-top-width: 0; - border-bottom-color: #fff; + top: 1px; + margin-left: -10px; + content: " "; + border-top-width: 0; + border-bottom-color: #fff; } + .popover.left > .arrow { - top: 50%; - right: -11px; - margin-top: -11px; - border-right-width: 0; - border-left-color: #999; - border-left-color: rgba(0, 0, 0, .25); + top: 50%; + right: -11px; + margin-top: -11px; + border-right-width: 0; + border-left-color: #999; + border-left-color: rgba(0, 0, 0, .25); } + .popover.left > .arrow:after { - right: 1px; - bottom: -10px; - content: " "; - border-right-width: 0; - border-left-color: #fff; + right: 1px; + bottom: -10px; + content: " "; + border-right-width: 0; + border-left-color: #fff; } + .carousel { - position: relative; + position: relative; } + .carousel-inner { - position: relative; - width: 100%; - overflow: hidden; + position: relative; + width: 100%; + overflow: hidden; } + .carousel-inner > .item { - position: relative; - display: none; - -webkit-transition: .6s ease-in-out left; - -o-transition: .6s ease-in-out left; - transition: .6s ease-in-out left; + position: relative; + display: none; + -webkit-transition: .6s ease-in-out left; + -o-transition: .6s ease-in-out left; + transition: .6s ease-in-out left; } + .carousel-inner > .item > img, .carousel-inner > .item > a > img { - line-height: 1; + line-height: 1; } + @media all and (transform-3d), (-webkit-transform-3d) { - .carousel-inner > .item { - -webkit-transition: -webkit-transform .6s ease-in-out; - -o-transition: -o-transform .6s ease-in-out; - transition: transform .6s ease-in-out; - - -webkit-backface-visibility: hidden; - backface-visibility: hidden; - -webkit-perspective: 1000; - perspective: 1000; - } - .carousel-inner > .item.next, - .carousel-inner > .item.active.right { - left: 0; - -webkit-transform: translate3d(100%, 0, 0); - transform: translate3d(100%, 0, 0); - } - .carousel-inner > .item.prev, - .carousel-inner > .item.active.left { - left: 0; - -webkit-transform: translate3d(-100%, 0, 0); - transform: translate3d(-100%, 0, 0); - } - .carousel-inner > .item.next.left, - .carousel-inner > .item.prev.right, - .carousel-inner > .item.active { - left: 0; - -webkit-transform: translate3d(0, 0, 0); - transform: translate3d(0, 0, 0); - } + .carousel-inner > .item { + -webkit-transition: -webkit-transform .6s ease-in-out; + -o-transition: -o-transform .6s ease-in-out; + transition: transform .6s ease-in-out; + + -webkit-backface-visibility: hidden; + backface-visibility: hidden; + -webkit-perspective: 1000; + perspective: 1000; + } + + .carousel-inner > .item.next, + .carousel-inner > .item.active.right { + left: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } + + .carousel-inner > .item.prev, + .carousel-inner > .item.active.left { + left: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } + + .carousel-inner > .item.next.left, + .carousel-inner > .item.prev.right, + .carousel-inner > .item.active { + left: 0; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } } + .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { - display: block; + display: block; } + .carousel-inner > .active { - left: 0; + left: 0; } + .carousel-inner > .next, .carousel-inner > .prev { - position: absolute; - top: 0; - width: 100%; + position: absolute; + top: 0; + width: 100%; } + .carousel-inner > .next { - left: 100%; + left: 100%; } + .carousel-inner > .prev { - left: -100%; + left: -100%; } + .carousel-inner > .next.left, .carousel-inner > .prev.right { - left: 0; + left: 0; } + .carousel-inner > .active.left { - left: -100%; + left: -100%; } + .carousel-inner > .active.right { - left: 100%; + left: 100%; } + .carousel-control { - position: absolute; - top: 0; - bottom: 0; - left: 0; - width: 15%; - font-size: 20px; - color: #fff; - text-align: center; - text-shadow: 0 1px 2px rgba(0, 0, 0, .6); - filter: alpha(opacity=50); - opacity: .5; + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 15%; + font-size: 20px; + color: #fff; + text-align: center; + text-shadow: 0 1px 2px rgba(0, 0, 0, .6); + filter: alpha(opacity=50); + opacity: .5; } + .carousel-control.left { - background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); - background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); - background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001))); - background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1); - background-repeat: repeat-x; + background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001))); + background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1); + background-repeat: repeat-x; } + .carousel-control.right { - right: 0; - left: auto; - background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); - background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); - background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5))); - background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1); - background-repeat: repeat-x; + right: 0; + left: auto; + background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5))); + background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1); + background-repeat: repeat-x; } + .carousel-control:hover, .carousel-control:focus { - color: #fff; - text-decoration: none; - filter: alpha(opacity=90); - outline: 0; - opacity: .9; + color: #fff; + text-decoration: none; + filter: alpha(opacity=90); + outline: 0; + opacity: .9; } + .carousel-control .icon-prev, .carousel-control .icon-next, .carousel-control .glyphicon-chevron-left, .carousel-control .glyphicon-chevron-right { - position: absolute; - top: 50%; - z-index: 5; - display: inline-block; + position: absolute; + top: 50%; + z-index: 5; + display: inline-block; } + .carousel-control .icon-prev, .carousel-control .glyphicon-chevron-left { - left: 50%; - margin-left: -10px; + left: 50%; + margin-left: -10px; } + .carousel-control .icon-next, .carousel-control .glyphicon-chevron-right { - right: 50%; - margin-right: -10px; + right: 50%; + margin-right: -10px; } + .carousel-control .icon-prev, .carousel-control .icon-next { - width: 20px; - height: 20px; - margin-top: -10px; - font-family: serif; + width: 20px; + height: 20px; + margin-top: -10px; + font-family: serif; } + .carousel-control .icon-prev:before { - content: '\2039'; + content: '\2039'; } + .carousel-control .icon-next:before { - content: '\203a'; + content: '\203a'; } + .carousel-indicators { - position: absolute; - bottom: 10px; - left: 50%; - z-index: 15; - width: 60%; - padding-left: 0; - margin-left: -30%; - text-align: center; - list-style: none; + position: absolute; + bottom: 10px; + left: 50%; + z-index: 15; + width: 60%; + padding-left: 0; + margin-left: -30%; + text-align: center; + list-style: none; } + .carousel-indicators li { - display: inline-block; - width: 10px; - height: 10px; - margin: 1px; - text-indent: -999px; - cursor: pointer; - background-color: #000 \9; - background-color: rgba(0, 0, 0, 0); - border: 1px solid #fff; - border-radius: 10px; + display: inline-block; + width: 10px; + height: 10px; + margin: 1px; + text-indent: -999px; + cursor: pointer; + background-color: #000 \9; + background-color: rgba(0, 0, 0, 0); + border: 1px solid #fff; + border-radius: 10px; } + .carousel-indicators .active { - width: 12px; - height: 12px; - margin: 0; - background-color: #fff; + width: 12px; + height: 12px; + margin: 0; + background-color: #fff; } + .carousel-caption { - position: absolute; - right: 15%; - bottom: 20px; - left: 15%; - z-index: 10; - padding-top: 20px; - padding-bottom: 20px; - color: #fff; - text-align: center; - text-shadow: 0 1px 2px rgba(0, 0, 0, .6); + position: absolute; + right: 15%; + bottom: 20px; + left: 15%; + z-index: 10; + padding-top: 20px; + padding-bottom: 20px; + color: #fff; + text-align: center; + text-shadow: 0 1px 2px rgba(0, 0, 0, .6); } + .carousel-caption .btn { - text-shadow: none; + text-shadow: none; } + @media screen and (min-width: 768px) { - .carousel-control .glyphicon-chevron-left, - .carousel-control .glyphicon-chevron-right, - .carousel-control .icon-prev, - .carousel-control .icon-next { - width: 30px; - height: 30px; - margin-top: -15px; - font-size: 30px; - } - .carousel-control .glyphicon-chevron-left, - .carousel-control .icon-prev { - margin-left: -15px; - } - .carousel-control .glyphicon-chevron-right, - .carousel-control .icon-next { - margin-right: -15px; - } - .carousel-caption { - right: 20%; - left: 20%; - padding-bottom: 30px; - } - .carousel-indicators { - bottom: 20px; - } + .carousel-control .glyphicon-chevron-left, + .carousel-control .glyphicon-chevron-right, + .carousel-control .icon-prev, + .carousel-control .icon-next { + width: 30px; + height: 30px; + margin-top: -15px; + font-size: 30px; + } + + .carousel-control .glyphicon-chevron-left, + .carousel-control .icon-prev { + margin-left: -15px; + } + + .carousel-control .glyphicon-chevron-right, + .carousel-control .icon-next { + margin-right: -15px; + } + + .carousel-caption { + right: 20%; + left: 20%; + padding-bottom: 30px; + } + + .carousel-indicators { + bottom: 20px; + } } + .clearfix:before, .clearfix:after, .dl-horizontal dd:before, @@ -6047,9 +7328,10 @@ button.close { .panel-body:after, .modal-footer:before, .modal-footer:after { - display: table; - content: " "; + display: table; + content: " "; } + .clearfix:after, .dl-horizontal dd:after, .container:after, @@ -6065,51 +7347,63 @@ button.close { .pager:after, .panel-body:after, .modal-footer:after { - clear: both; + clear: both; } + .center-block { - display: block; - margin-right: auto; - margin-left: auto; + display: block; + margin-right: auto; + margin-left: auto; } + .pull-right { - float: right !important; + float: right !important; } + .pull-left { - float: left !important; + float: left !important; } + .hide { - display: none !important; + display: none !important; } + .show { - display: block !important; + display: block !important; } + .invisible { - visibility: hidden; + visibility: hidden; } + .text-hide { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; } + .hidden { - display: none !important; - visibility: hidden !important; + display: none !important; + visibility: hidden !important; } + .affix { - position: fixed; + position: fixed; } + @-ms-viewport { - width: device-width; + width: device-width; } + .visible-xs, .visible-sm, .visible-md, .visible-lg { - display: none !important; + display: none !important; } + .visible-xs-block, .visible-xs-inline, .visible-xs-inline-block, @@ -6122,193 +7416,238 @@ button.close { .visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { - display: none !important; + display: none !important; } + @media (max-width: 767px) { - .visible-xs { - display: block !important; - } - table.visible-xs { - display: table; - } - tr.visible-xs { - display: table-row !important; - } - th.visible-xs, - td.visible-xs { - display: table-cell !important; - } + .visible-xs { + display: block !important; + } + + table.visible-xs { + display: table; + } + + tr.visible-xs { + display: table-row !important; + } + + th.visible-xs, + td.visible-xs { + display: table-cell !important; + } } + @media (max-width: 767px) { - .visible-xs-block { - display: block !important; - } + .visible-xs-block { + display: block !important; + } } + @media (max-width: 767px) { - .visible-xs-inline { - display: inline !important; - } + .visible-xs-inline { + display: inline !important; + } } + @media (max-width: 767px) { - .visible-xs-inline-block { - display: inline-block !important; - } + .visible-xs-inline-block { + display: inline-block !important; + } } + @media (min-width: 768px) and (max-width: 991px) { - .visible-sm { - display: block !important; - } - table.visible-sm { - display: table; - } - tr.visible-sm { - display: table-row !important; - } - th.visible-sm, - td.visible-sm { - display: table-cell !important; - } + .visible-sm { + display: block !important; + } + + table.visible-sm { + display: table; + } + + tr.visible-sm { + display: table-row !important; + } + + th.visible-sm, + td.visible-sm { + display: table-cell !important; + } } + @media (min-width: 768px) and (max-width: 991px) { - .visible-sm-block { - display: block !important; - } + .visible-sm-block { + display: block !important; + } } + @media (min-width: 768px) and (max-width: 991px) { - .visible-sm-inline { - display: inline !important; - } + .visible-sm-inline { + display: inline !important; + } } + @media (min-width: 768px) and (max-width: 991px) { - .visible-sm-inline-block { - display: inline-block !important; - } + .visible-sm-inline-block { + display: inline-block !important; + } } + @media (min-width: 992px) and (max-width: 1199px) { - .visible-md { - display: block !important; - } - table.visible-md { - display: table; - } - tr.visible-md { - display: table-row !important; - } - th.visible-md, - td.visible-md { - display: table-cell !important; - } + .visible-md { + display: block !important; + } + + table.visible-md { + display: table; + } + + tr.visible-md { + display: table-row !important; + } + + th.visible-md, + td.visible-md { + display: table-cell !important; + } } + @media (min-width: 992px) and (max-width: 1199px) { - .visible-md-block { - display: block !important; - } + .visible-md-block { + display: block !important; + } } + @media (min-width: 992px) and (max-width: 1199px) { - .visible-md-inline { - display: inline !important; - } + .visible-md-inline { + display: inline !important; + } } + @media (min-width: 992px) and (max-width: 1199px) { - .visible-md-inline-block { - display: inline-block !important; - } + .visible-md-inline-block { + display: inline-block !important; + } } + @media (min-width: 1200px) { - .visible-lg { - display: block !important; - } - table.visible-lg { - display: table; - } - tr.visible-lg { - display: table-row !important; - } - th.visible-lg, - td.visible-lg { - display: table-cell !important; - } + .visible-lg { + display: block !important; + } + + table.visible-lg { + display: table; + } + + tr.visible-lg { + display: table-row !important; + } + + th.visible-lg, + td.visible-lg { + display: table-cell !important; + } } + @media (min-width: 1200px) { - .visible-lg-block { - display: block !important; - } + .visible-lg-block { + display: block !important; + } } + @media (min-width: 1200px) { - .visible-lg-inline { - display: inline !important; - } + .visible-lg-inline { + display: inline !important; + } } + @media (min-width: 1200px) { - .visible-lg-inline-block { - display: inline-block !important; - } + .visible-lg-inline-block { + display: inline-block !important; + } } + @media (max-width: 767px) { - .hidden-xs { - display: none !important; - } + .hidden-xs { + display: none !important; + } } + @media (min-width: 768px) and (max-width: 991px) { - .hidden-sm { - display: none !important; - } + .hidden-sm { + display: none !important; + } } + @media (min-width: 992px) and (max-width: 1199px) { - .hidden-md { - display: none !important; - } + .hidden-md { + display: none !important; + } } + @media (min-width: 1200px) { - .hidden-lg { - display: none !important; - } + .hidden-lg { + display: none !important; + } } + .visible-print { - display: none !important; + display: none !important; } + @media print { - .visible-print { - display: block !important; - } - table.visible-print { - display: table; - } - tr.visible-print { - display: table-row !important; - } - th.visible-print, - td.visible-print { - display: table-cell !important; - } + .visible-print { + display: block !important; + } + + table.visible-print { + display: table; + } + + tr.visible-print { + display: table-row !important; + } + + th.visible-print, + td.visible-print { + display: table-cell !important; + } } + .visible-print-block { - display: none !important; + display: none !important; } + @media print { - .visible-print-block { - display: block !important; - } + .visible-print-block { + display: block !important; + } } + .visible-print-inline { - display: none !important; + display: none !important; } + @media print { - .visible-print-inline { - display: inline !important; - } + .visible-print-inline { + display: inline !important; + } } + .visible-print-inline-block { - display: none !important; + display: none !important; } + @media print { - .visible-print-inline-block { - display: inline-block !important; - } + .visible-print-inline-block { + display: inline-block !important; + } } + @media print { - .hidden-print { - display: none !important; - } + .hidden-print { + display: none !important; + } } + /*# sourceMappingURL=bootstrap.css.map */ \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css.map b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css.map index ff579ff5..0b195b84 100644 --- a/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css.map +++ b/projects/webui/base/src/main/resources/css/libs/bootstrap/bootstrap.css.map @@ -1 +1,140 @@ -{"version":3,"sources":["bootstrap.css","less/normalize.less","less/print.less","less/glyphicons.less","less/scaffolding.less","less/mixins/vendor-prefixes.less","less/mixins/tab-focus.less","less/mixins/image.less","less/type.less","less/mixins/text-emphasis.less","less/mixins/background-variant.less","less/mixins/text-overflow.less","less/code.less","less/grid.less","less/mixins/grid.less","less/mixins/grid-framework.less","less/tables.less","less/mixins/table-row.less","less/forms.less","less/mixins/forms.less","less/buttons.less","less/mixins/buttons.less","less/mixins/opacity.less","less/component-animations.less","less/dropdowns.less","less/mixins/nav-divider.less","less/mixins/reset-filter.less","less/button-groups.less","less/mixins/border-radius.less","less/input-groups.less","less/navs.less","less/navbar.less","less/mixins/nav-vertical-align.less","less/utilities.less","less/breadcrumbs.less","less/pagination.less","less/mixins/pagination.less","less/pager.less","less/labels.less","less/mixins/labels.less","less/badges.less","less/jumbotron.less","less/thumbnails.less","less/alerts.less","less/mixins/alerts.less","less/progress-bars.less","less/mixins/gradients.less","less/mixins/progress-bar.less","less/media.less","less/list-group.less","less/mixins/list-group.less","less/panels.less","less/mixins/panels.less","less/responsive-embed.less","less/wells.less","less/close.less","less/modals.less","less/tooltip.less","less/popovers.less","less/carousel.less","less/mixins/clearfix.less","less/mixins/center-block.less","less/mixins/hide-text.less","less/responsive-utilities.less","less/mixins/responsive-visibility.less"],"names":[],"mappings":"AAAA,6DAA4D;ACQ5D;EACE,yBAAA;EACA,4BAAA;EACA,gCAAA;EDND;ACaD;EACE,WAAA;EDXD;ACwBD;;;;;;;;;;;;;EAaE,gBAAA;EDtBD;AC8BD;;;;EAIE,uBAAA;EACA,0BAAA;ED5BD;ACoCD;EACE,eAAA;EACA,WAAA;EDlCD;AC0CD;;EAEE,eAAA;EDxCD;ACkDD;EACE,+BAAA;EDhDD;ACuDD;;EAEE,YAAA;EDrDD;AC+DD;EACE,2BAAA;ED7DD;ACoED;;EAEE,mBAAA;EDlED;ACyED;EACE,oBAAA;EDvED;AC+ED;EACE,gBAAA;EACA,kBAAA;ED7ED;ACoFD;EACE,kBAAA;EACA,aAAA;EDlFD;ACyFD;EACE,gBAAA;EDvFD;AC8FD;;EAEE,gBAAA;EACA,gBAAA;EACA,oBAAA;EACA,0BAAA;ED5FD;AC+FD;EACE,aAAA;ED7FD;ACgGD;EACE,iBAAA;ED9FD;ACwGD;EACE,WAAA;EDtGD;AC6GD;EACE,kBAAA;ED3GD;ACqHD;EACE,kBAAA;EDnHD;AC0HD;EACE,8BAAA;EACA,iCAAA;UAAA,yBAAA;EACA,WAAA;EDxHD;AC+HD;EACE,gBAAA;ED7HD;ACoID;;;;EAIE,mCAAA;EACA,gBAAA;EDlID;ACoJD;;;;;EAKE,gBAAA;EACA,eAAA;EACA,WAAA;EDlJD;ACyJD;EACE,mBAAA;EDvJD;ACiKD;;EAEE,sBAAA;ED/JD;AC0KD;;;;EAIE,4BAAA;EACA,iBAAA;EDxKD;AC+KD;;EAEE,iBAAA;ED7KD;ACoLD;;EAEE,WAAA;EACA,YAAA;EDlLD;AC0LD;EACE,qBAAA;EDxLD;ACmMD;;EAEE,gCAAA;KAAA,6BAAA;UAAA,wBAAA;EACA,YAAA;EDjMD;AC0MD;;EAEE,cAAA;EDxMD;ACiND;EACE,+BAAA;EACA,8BAAA;EACA,iCAAA;EACA,yBAAA;ED/MD;ACwND;;EAEE,0BAAA;EDtND;AC6ND;EACE,2BAAA;EACA,eAAA;EACA,gCAAA;ED3ND;ACmOD;EACE,WAAA;EACA,YAAA;EDjOD;ACwOD;EACE,gBAAA;EDtOD;AC8OD;EACE,mBAAA;ED5OD;ACsPD;EACE,2BAAA;EACA,mBAAA;EDpPD;ACuPD;;EAEE,YAAA;EDrPD;AACD,sFAAqF;AE1ErF;EAnGI;;;IAGI,oCAAA;IACA,wBAAA;IACA,qCAAA;YAAA,6BAAA;IACA,8BAAA;IFgLL;EE7KC;;IAEI,4BAAA;IF+KL;EE5KC;IACI,8BAAA;IF8KL;EE3KC;IACI,+BAAA;IF6KL;EExKC;;IAEI,aAAA;IF0KL;EEvKC;;IAEI,wBAAA;IACA,0BAAA;IFyKL;EEtKC;IACI,6BAAA;IFwKL;EErKC;;IAEI,0BAAA;IFuKL;EEpKC;IACI,4BAAA;IFsKL;EEnKC;;;IAGI,YAAA;IACA,WAAA;IFqKL;EElKC;;IAEI,yBAAA;IFoKL;EE7JC;IACI,6BAAA;IF+JL;EE3JC;IACI,eAAA;IF6JL;EE3JC;;IAGQ,mCAAA;IF4JT;EEzJC;IACI,wBAAA;IF2JL;EExJC;IACI,sCAAA;IF0JL;EE3JC;;IAKQ,mCAAA;IF0JT;EEvJC;;IAGQ,mCAAA;IFwJT;EACF;AGpPD;EACE,qCAAA;EACA,uDAAA;EACA,iYAAA;EHsPD;AG9OD;EACE,oBAAA;EACA,UAAA;EACA,uBAAA;EACA,qCAAA;EACA,oBAAA;EACA,qBAAA;EACA,gBAAA;EACA,qCAAA;EACA,oCAAA;EHgPD;AG5OmC;EAAW,gBAAA;EH+O9C;AG9OmC;EAAW,gBAAA;EHiP9C;AG/OmC;;EAAW,kBAAA;EHmP9C;AGlPmC;EAAW,kBAAA;EHqP9C;AGpPmC;EAAW,kBAAA;EHuP9C;AGtPmC;EAAW,kBAAA;EHyP9C;AGxPmC;EAAW,kBAAA;EH2P9C;AG1PmC;EAAW,kBAAA;EH6P9C;AG5PmC;EAAW,kBAAA;EH+P9C;AG9PmC;EAAW,kBAAA;EHiQ9C;AGhQmC;EAAW,kBAAA;EHmQ9C;AGlQmC;EAAW,kBAAA;EHqQ9C;AGpQmC;EAAW,kBAAA;EHuQ9C;AGtQmC;EAAW,kBAAA;EHyQ9C;AGxQmC;EAAW,kBAAA;EH2Q9C;AG1QmC;EAAW,kBAAA;EH6Q9C;AG5QmC;EAAW,kBAAA;EH+Q9C;AG9QmC;EAAW,kBAAA;EHiR9C;AGhRmC;EAAW,kBAAA;EHmR9C;AGlRmC;EAAW,kBAAA;EHqR9C;AGpRmC;EAAW,kBAAA;EHuR9C;AGtRmC;EAAW,kBAAA;EHyR9C;AGxRmC;EAAW,kBAAA;EH2R9C;AG1RmC;EAAW,kBAAA;EH6R9C;AG5RmC;EAAW,kBAAA;EH+R9C;AG9RmC;EAAW,kBAAA;EHiS9C;AGhSmC;EAAW,kBAAA;EHmS9C;AGlSmC;EAAW,kBAAA;EHqS9C;AGpSmC;EAAW,kBAAA;EHuS9C;AGtSmC;EAAW,kBAAA;EHyS9C;AGxSmC;EAAW,kBAAA;EH2S9C;AG1SmC;EAAW,kBAAA;EH6S9C;AG5SmC;EAAW,kBAAA;EH+S9C;AG9SmC;EAAW,kBAAA;EHiT9C;AGhTmC;EAAW,kBAAA;EHmT9C;AGlTmC;EAAW,kBAAA;EHqT9C;AGpTmC;EAAW,kBAAA;EHuT9C;AGtTmC;EAAW,kBAAA;EHyT9C;AGxTmC;EAAW,kBAAA;EH2T9C;AG1TmC;EAAW,kBAAA;EH6T9C;AG5TmC;EAAW,kBAAA;EH+T9C;AG9TmC;EAAW,kBAAA;EHiU9C;AGhUmC;EAAW,kBAAA;EHmU9C;AGlUmC;EAAW,kBAAA;EHqU9C;AGpUmC;EAAW,kBAAA;EHuU9C;AGtUmC;EAAW,kBAAA;EHyU9C;AGxUmC;EAAW,kBAAA;EH2U9C;AG1UmC;EAAW,kBAAA;EH6U9C;AG5UmC;EAAW,kBAAA;EH+U9C;AG9UmC;EAAW,kBAAA;EHiV9C;AGhVmC;EAAW,kBAAA;EHmV9C;AGlVmC;EAAW,kBAAA;EHqV9C;AGpVmC;EAAW,kBAAA;EHuV9C;AGtVmC;EAAW,kBAAA;EHyV9C;AGxVmC;EAAW,kBAAA;EH2V9C;AG1VmC;EAAW,kBAAA;EH6V9C;AG5VmC;EAAW,kBAAA;EH+V9C;AG9VmC;EAAW,kBAAA;EHiW9C;AGhWmC;EAAW,kBAAA;EHmW9C;AGlWmC;EAAW,kBAAA;EHqW9C;AGpWmC;EAAW,kBAAA;EHuW9C;AGtWmC;EAAW,kBAAA;EHyW9C;AGxWmC;EAAW,kBAAA;EH2W9C;AG1WmC;EAAW,kBAAA;EH6W9C;AG5WmC;EAAW,kBAAA;EH+W9C;AG9WmC;EAAW,kBAAA;EHiX9C;AGhXmC;EAAW,kBAAA;EHmX9C;AGlXmC;EAAW,kBAAA;EHqX9C;AGpXmC;EAAW,kBAAA;EHuX9C;AGtXmC;EAAW,kBAAA;EHyX9C;AGxXmC;EAAW,kBAAA;EH2X9C;AG1XmC;EAAW,kBAAA;EH6X9C;AG5XmC;EAAW,kBAAA;EH+X9C;AG9XmC;EAAW,kBAAA;EHiY9C;AGhYmC;EAAW,kBAAA;EHmY9C;AGlYmC;EAAW,kBAAA;EHqY9C;AGpYmC;EAAW,kBAAA;EHuY9C;AGtYmC;EAAW,kBAAA;EHyY9C;AGxYmC;EAAW,kBAAA;EH2Y9C;AG1YmC;EAAW,kBAAA;EH6Y9C;AG5YmC;EAAW,kBAAA;EH+Y9C;AG9YmC;EAAW,kBAAA;EHiZ9C;AGhZmC;EAAW,kBAAA;EHmZ9C;AGlZmC;EAAW,kBAAA;EHqZ9C;AGpZmC;EAAW,kBAAA;EHuZ9C;AGtZmC;EAAW,kBAAA;EHyZ9C;AGxZmC;EAAW,kBAAA;EH2Z9C;AG1ZmC;EAAW,kBAAA;EH6Z9C;AG5ZmC;EAAW,kBAAA;EH+Z9C;AG9ZmC;EAAW,kBAAA;EHia9C;AGhamC;EAAW,kBAAA;EHma9C;AGlamC;EAAW,kBAAA;EHqa9C;AGpamC;EAAW,kBAAA;EHua9C;AGtamC;EAAW,kBAAA;EHya9C;AGxamC;EAAW,kBAAA;EH2a9C;AG1amC;EAAW,kBAAA;EH6a9C;AG5amC;EAAW,kBAAA;EH+a9C;AG9amC;EAAW,kBAAA;EHib9C;AGhbmC;EAAW,kBAAA;EHmb9C;AGlbmC;EAAW,kBAAA;EHqb9C;AGpbmC;EAAW,kBAAA;EHub9C;AGtbmC;EAAW,kBAAA;EHyb9C;AGxbmC;EAAW,kBAAA;EH2b9C;AG1bmC;EAAW,kBAAA;EH6b9C;AG5bmC;EAAW,kBAAA;EH+b9C;AG9bmC;EAAW,kBAAA;EHic9C;AGhcmC;EAAW,kBAAA;EHmc9C;AGlcmC;EAAW,kBAAA;EHqc9C;AGpcmC;EAAW,kBAAA;EHuc9C;AGtcmC;EAAW,kBAAA;EHyc9C;AGxcmC;EAAW,kBAAA;EH2c9C;AG1cmC;EAAW,kBAAA;EH6c9C;AG5cmC;EAAW,kBAAA;EH+c9C;AG9cmC;EAAW,kBAAA;EHid9C;AGhdmC;EAAW,kBAAA;EHmd9C;AGldmC;EAAW,kBAAA;EHqd9C;AGpdmC;EAAW,kBAAA;EHud9C;AGtdmC;EAAW,kBAAA;EHyd9C;AGxdmC;EAAW,kBAAA;EH2d9C;AG1dmC;EAAW,kBAAA;EH6d9C;AG5dmC;EAAW,kBAAA;EH+d9C;AG9dmC;EAAW,kBAAA;EHie9C;AGhemC;EAAW,kBAAA;EHme9C;AGlemC;EAAW,kBAAA;EHqe9C;AGpemC;EAAW,kBAAA;EHue9C;AGtemC;EAAW,kBAAA;EHye9C;AGxemC;EAAW,kBAAA;EH2e9C;AG1emC;EAAW,kBAAA;EH6e9C;AG5emC;EAAW,kBAAA;EH+e9C;AG9emC;EAAW,kBAAA;EHif9C;AGhfmC;EAAW,kBAAA;EHmf9C;AGlfmC;EAAW,kBAAA;EHqf9C;AGpfmC;EAAW,kBAAA;EHuf9C;AGtfmC;EAAW,kBAAA;EHyf9C;AGxfmC;EAAW,kBAAA;EH2f9C;AG1fmC;EAAW,kBAAA;EH6f9C;AG5fmC;EAAW,kBAAA;EH+f9C;AG9fmC;EAAW,kBAAA;EHigB9C;AGhgBmC;EAAW,kBAAA;EHmgB9C;AGlgBmC;EAAW,kBAAA;EHqgB9C;AGpgBmC;EAAW,kBAAA;EHugB9C;AGtgBmC;EAAW,kBAAA;EHygB9C;AGxgBmC;EAAW,kBAAA;EH2gB9C;AG1gBmC;EAAW,kBAAA;EH6gB9C;AG5gBmC;EAAW,kBAAA;EH+gB9C;AG9gBmC;EAAW,kBAAA;EHihB9C;AGhhBmC;EAAW,kBAAA;EHmhB9C;AGlhBmC;EAAW,kBAAA;EHqhB9C;AGphBmC;EAAW,kBAAA;EHuhB9C;AGthBmC;EAAW,kBAAA;EHyhB9C;AGxhBmC;EAAW,kBAAA;EH2hB9C;AG1hBmC;EAAW,kBAAA;EH6hB9C;AG5hBmC;EAAW,kBAAA;EH+hB9C;AG9hBmC;EAAW,kBAAA;EHiiB9C;AGhiBmC;EAAW,kBAAA;EHmiB9C;AGliBmC;EAAW,kBAAA;EHqiB9C;AGpiBmC;EAAW,kBAAA;EHuiB9C;AGtiBmC;EAAW,kBAAA;EHyiB9C;AGxiBmC;EAAW,kBAAA;EH2iB9C;AG1iBmC;EAAW,kBAAA;EH6iB9C;AG5iBmC;EAAW,kBAAA;EH+iB9C;AG9iBmC;EAAW,kBAAA;EHijB9C;AGhjBmC;EAAW,kBAAA;EHmjB9C;AGljBmC;EAAW,kBAAA;EHqjB9C;AGpjBmC;EAAW,kBAAA;EHujB9C;AGtjBmC;EAAW,kBAAA;EHyjB9C;AGxjBmC;EAAW,kBAAA;EH2jB9C;AG1jBmC;EAAW,kBAAA;EH6jB9C;AG5jBmC;EAAW,kBAAA;EH+jB9C;AG9jBmC;EAAW,kBAAA;EHikB9C;AGhkBmC;EAAW,kBAAA;EHmkB9C;AGlkBmC;EAAW,kBAAA;EHqkB9C;AGpkBmC;EAAW,kBAAA;EHukB9C;AGtkBmC;EAAW,kBAAA;EHykB9C;AGxkBmC;EAAW,kBAAA;EH2kB9C;AG1kBmC;EAAW,kBAAA;EH6kB9C;AG5kBmC;EAAW,kBAAA;EH+kB9C;AG9kBmC;EAAW,kBAAA;EHilB9C;AGhlBmC;EAAW,kBAAA;EHmlB9C;AGllBmC;EAAW,kBAAA;EHqlB9C;AGplBmC;EAAW,kBAAA;EHulB9C;AGtlBmC;EAAW,kBAAA;EHylB9C;AGxlBmC;EAAW,kBAAA;EH2lB9C;AG1lBmC;EAAW,kBAAA;EH6lB9C;AG5lBmC;EAAW,kBAAA;EH+lB9C;AG9lBmC;EAAW,kBAAA;EHimB9C;AGhmBmC;EAAW,kBAAA;EHmmB9C;AGlmBmC;EAAW,kBAAA;EHqmB9C;AGpmBmC;EAAW,kBAAA;EHumB9C;AGtmBmC;EAAW,kBAAA;EHymB9C;AGxmBmC;EAAW,kBAAA;EH2mB9C;AG1mBmC;EAAW,kBAAA;EH6mB9C;AG5mBmC;EAAW,kBAAA;EH+mB9C;AG9mBmC;EAAW,kBAAA;EHinB9C;AGhnBmC;EAAW,kBAAA;EHmnB9C;AGlnBmC;EAAW,kBAAA;EHqnB9C;AGpnBmC;EAAW,kBAAA;EHunB9C;AGtnBmC;EAAW,kBAAA;EHynB9C;AGxnBmC;EAAW,kBAAA;EH2nB9C;AG1nBmC;EAAW,kBAAA;EH6nB9C;AG5nBmC;EAAW,kBAAA;EH+nB9C;AG9nBmC;EAAW,kBAAA;EHioB9C;AGhoBmC;EAAW,kBAAA;EHmoB9C;AGloBmC;EAAW,kBAAA;EHqoB9C;AGpoBmC;EAAW,kBAAA;EHuoB9C;AGtoBmC;EAAW,kBAAA;EHyoB9C;AGhoBmC;EAAW,kBAAA;EHmoB9C;AGloBmC;EAAW,kBAAA;EHqoB9C;AGpoBmC;EAAW,kBAAA;EHuoB9C;AGtoBmC;EAAW,kBAAA;EHyoB9C;AGxoBmC;EAAW,kBAAA;EH2oB9C;AG1oBmC;EAAW,kBAAA;EH6oB9C;AG5oBmC;EAAW,kBAAA;EH+oB9C;AG9oBmC;EAAW,kBAAA;EHipB9C;AGhpBmC;EAAW,kBAAA;EHmpB9C;AGlpBmC;EAAW,kBAAA;EHqpB9C;AGppBmC;EAAW,kBAAA;EHupB9C;AGtpBmC;EAAW,kBAAA;EHypB9C;AGxpBmC;EAAW,kBAAA;EH2pB9C;AG1pBmC;EAAW,kBAAA;EH6pB9C;AG5pBmC;EAAW,kBAAA;EH+pB9C;AG9pBmC;EAAW,kBAAA;EHiqB9C;AGhqBmC;EAAW,kBAAA;EHmqB9C;AGlqBmC;EAAW,kBAAA;EHqqB9C;AGpqBmC;EAAW,kBAAA;EHuqB9C;AGtqBmC;EAAW,kBAAA;EHyqB9C;AGxqBmC;EAAW,kBAAA;EH2qB9C;AG1qBmC;EAAW,kBAAA;EH6qB9C;AG5qBmC;EAAW,kBAAA;EH+qB9C;AG9qBmC;EAAW,kBAAA;EHirB9C;AGhrBmC;EAAW,kBAAA;EHmrB9C;AGlrBmC;EAAW,kBAAA;EHqrB9C;AGprBmC;EAAW,kBAAA;EHurB9C;AGtrBmC;EAAW,kBAAA;EHyrB9C;AGxrBmC;EAAW,kBAAA;EH2rB9C;AG1rBmC;EAAW,kBAAA;EH6rB9C;AG5rBmC;EAAW,kBAAA;EH+rB9C;AG9rBmC;EAAW,kBAAA;EHisB9C;AGhsBmC;EAAW,kBAAA;EHmsB9C;AGlsBmC;EAAW,kBAAA;EHqsB9C;AGpsBmC;EAAW,kBAAA;EHusB9C;AGtsBmC;EAAW,kBAAA;EHysB9C;AGxsBmC;EAAW,kBAAA;EH2sB9C;AG1sBmC;EAAW,kBAAA;EH6sB9C;AG5sBmC;EAAW,kBAAA;EH+sB9C;AG9sBmC;EAAW,kBAAA;EHitB9C;AGhtBmC;EAAW,kBAAA;EHmtB9C;AGltBmC;EAAW,kBAAA;EHqtB9C;AGptBmC;EAAW,kBAAA;EHutB9C;AGttBmC;EAAW,kBAAA;EHytB9C;AGxtBmC;EAAW,kBAAA;EH2tB9C;AG1tBmC;EAAW,kBAAA;EH6tB9C;AG5tBmC;EAAW,kBAAA;EH+tB9C;AG9tBmC;EAAW,kBAAA;EHiuB9C;AGhuBmC;EAAW,kBAAA;EHmuB9C;AGluBmC;EAAW,kBAAA;EHquB9C;AGpuBmC;EAAW,kBAAA;EHuuB9C;AGtuBmC;EAAW,kBAAA;EHyuB9C;AI3gCD;ECgEE,gCAAA;EACG,6BAAA;EACK,wBAAA;EL88BT;AI7gCD;;EC6DE,gCAAA;EACG,6BAAA;EACK,wBAAA;ELo9BT;AI3gCD;EACE,iBAAA;EACA,+CAAA;EJ6gCD;AI1gCD;EACE,6DAAA;EACA,iBAAA;EACA,yBAAA;EACA,gBAAA;EACA,2BAAA;EJ4gCD;AIxgCD;;;;EAIE,sBAAA;EACA,oBAAA;EACA,sBAAA;EJ0gCD;AIpgCD;EACE,gBAAA;EACA,uBAAA;EJsgCD;AIpgCC;;EAEE,gBAAA;EACA,4BAAA;EJsgCH;AIngCC;EErDA,sBAAA;EAEA,4CAAA;EACA,sBAAA;EN0jCD;AI7/BD;EACE,WAAA;EJ+/BD;AIz/BD;EACE,wBAAA;EJ2/BD;AIv/BD;;;;;EGvEE,gBAAA;EACA,iBAAA;EACA,cAAA;EPqkCD;AI3/BD;EACE,oBAAA;EJ6/BD;AIv/BD;EACE,cAAA;EACA,yBAAA;EACA,2BAAA;EACA,2BAAA;EACA,oBAAA;EC6FA,0CAAA;EACK,qCAAA;EACG,kCAAA;EEvLR,uBAAA;EACA,iBAAA;EACA,cAAA;EPqlCD;AIv/BD;EACE,oBAAA;EJy/BD;AIn/BD;EACE,kBAAA;EACA,qBAAA;EACA,WAAA;EACA,+BAAA;EJq/BD;AI7+BD;EACE,oBAAA;EACA,YAAA;EACA,aAAA;EACA,cAAA;EACA,YAAA;EACA,kBAAA;EACA,wBAAA;EACA,WAAA;EJ++BD;AIv+BC;;EAEE,kBAAA;EACA,aAAA;EACA,cAAA;EACA,WAAA;EACA,mBAAA;EACA,YAAA;EJy+BH;AQpnCD;;;;;;;;;;;;EAEE,sBAAA;EACA,kBAAA;EACA,kBAAA;EACA,gBAAA;ERgoCD;AQroCD;;;;;;;;;;;;;;;;;;;;;;;;EASI,qBAAA;EACA,gBAAA;EACA,gBAAA;ERspCH;AQlpCD;;;;;;EAGE,kBAAA;EACA,qBAAA;ERupCD;AQ3pCD;;;;;;;;;;;;EAQI,gBAAA;ERiqCH;AQ9pCD;;;;;;EAGE,kBAAA;EACA,qBAAA;ERmqCD;AQvqCD;;;;;;;;;;;;EAQI,gBAAA;ER6qCH;AQzqCD;;EAAU,iBAAA;ER6qCT;AQ5qCD;;EAAU,iBAAA;ERgrCT;AQ/qCD;;EAAU,iBAAA;ERmrCT;AQlrCD;;EAAU,iBAAA;ERsrCT;AQrrCD;;EAAU,iBAAA;ERyrCT;AQxrCD;;EAAU,iBAAA;ER4rCT;AQtrCD;EACE,kBAAA;ERwrCD;AQrrCD;EACE,qBAAA;EACA,iBAAA;EACA,kBAAA;EACA,kBAAA;ERurCD;AQlrCD;EAAA;IAFI,iBAAA;IRwrCD;EACF;AQhrCD;;EAEE,gBAAA;ERkrCD;AQ/qCD;;EAEE,2BAAA;EACA,eAAA;ERirCD;AQ7qCD;EAAuB,kBAAA;ERgrCtB;AQ/qCD;EAAuB,mBAAA;ERkrCtB;AQjrCD;EAAuB,oBAAA;ERorCtB;AQnrCD;EAAuB,qBAAA;ERsrCtB;AQrrCD;EAAuB,qBAAA;ERwrCtB;AQrrCD;EAAuB,2BAAA;ERwrCtB;AQvrCD;EAAuB,2BAAA;ER0rCtB;AQzrCD;EAAuB,4BAAA;ER4rCtB;AQzrCD;EACE,gBAAA;ER2rCD;AQzrCD;ECrGE,gBAAA;ETiyCD;AShyCC;EACE,gBAAA;ETkyCH;AQ5rCD;ECxGE,gBAAA;ETuyCD;AStyCC;EACE,gBAAA;ETwyCH;AQ/rCD;EC3GE,gBAAA;ET6yCD;AS5yCC;EACE,gBAAA;ET8yCH;AQlsCD;EC9GE,gBAAA;ETmzCD;ASlzCC;EACE,gBAAA;ETozCH;AQrsCD;ECjHE,gBAAA;ETyzCD;ASxzCC;EACE,gBAAA;ET0zCH;AQpsCD;EAGE,aAAA;EE3HA,2BAAA;EVg0CD;AU/zCC;EACE,2BAAA;EVi0CH;AQrsCD;EE9HE,2BAAA;EVs0CD;AUr0CC;EACE,2BAAA;EVu0CH;AQxsCD;EEjIE,2BAAA;EV40CD;AU30CC;EACE,2BAAA;EV60CH;AQ3sCD;EEpIE,2BAAA;EVk1CD;AUj1CC;EACE,2BAAA;EVm1CH;AQ9sCD;EEvIE,2BAAA;EVw1CD;AUv1CC;EACE,2BAAA;EVy1CH;AQ5sCD;EACE,qBAAA;EACA,qBAAA;EACA,kCAAA;ER8sCD;AQtsCD;;EAEE,eAAA;EACA,qBAAA;ERwsCD;AQ3sCD;;;;EAMI,kBAAA;ER2sCH;AQpsCD;EACE,iBAAA;EACA,kBAAA;ERssCD;AQlsCD;EALE,iBAAA;EACA,kBAAA;EAMA,mBAAA;ERqsCD;AQvsCD;EAKI,uBAAA;EACA,mBAAA;EACA,oBAAA;ERqsCH;AQhsCD;EACE,eAAA;EACA,qBAAA;ERksCD;AQhsCD;;EAEE,yBAAA;ERksCD;AQhsCD;EACE,mBAAA;ERksCD;AQhsCD;EACE,gBAAA;ERksCD;AQzqCD;EAAA;IAVM,aAAA;IACA,cAAA;IACA,aAAA;IACA,mBAAA;IGtNJ,kBAAA;IACA,yBAAA;IACA,qBAAA;IX84CC;EQnrCH;IAHM,oBAAA;IRyrCH;EACF;AQhrCD;;EAGE,cAAA;EACA,mCAAA;ERirCD;AQ/qCD;EACE,gBAAA;EACA,2BAAA;ERirCD;AQ7qCD;EACE,oBAAA;EACA,kBAAA;EACA,mBAAA;EACA,gCAAA;ER+qCD;AQ1qCG;;;EACE,kBAAA;ER8qCL;AQxrCD;;;EAmBI,gBAAA;EACA,gBAAA;EACA,yBAAA;EACA,gBAAA;ER0qCH;AQxqCG;;;EACE,wBAAA;ER4qCL;AQpqCD;;EAEE,qBAAA;EACA,iBAAA;EACA,iCAAA;EACA,gBAAA;EACA,mBAAA;ERsqCD;AQhqCG;;;;;;EAAW,aAAA;ERwqCd;AQvqCG;;;;;;EACE,wBAAA;ER8qCL;AQxqCD;EACE,qBAAA;EACA,oBAAA;EACA,yBAAA;ER0qCD;AYh9CD;;;;EAIE,gEAAA;EZk9CD;AY98CD;EACE,kBAAA;EACA,gBAAA;EACA,gBAAA;EACA,2BAAA;EACA,oBAAA;EZg9CD;AY58CD;EACE,kBAAA;EACA,gBAAA;EACA,gBAAA;EACA,2BAAA;EACA,oBAAA;EACA,wDAAA;UAAA,gDAAA;EZ88CD;AYp9CD;EASI,YAAA;EACA,iBAAA;EACA,mBAAA;EACA,0BAAA;UAAA,kBAAA;EZ88CH;AYz8CD;EACE,gBAAA;EACA,gBAAA;EACA,kBAAA;EACA,iBAAA;EACA,yBAAA;EACA,uBAAA;EACA,uBAAA;EACA,gBAAA;EACA,2BAAA;EACA,2BAAA;EACA,oBAAA;EZ28CD;AYt9CD;EAeI,YAAA;EACA,oBAAA;EACA,gBAAA;EACA,uBAAA;EACA,+BAAA;EACA,kBAAA;EZ08CH;AYr8CD;EACE,mBAAA;EACA,oBAAA;EZu8CD;AajgDD;ECHE,oBAAA;EACA,mBAAA;EACA,oBAAA;EACA,qBAAA;EdugDD;AajgDC;EAAA;IAFE,cAAA;IbugDD;EACF;AangDC;EAAA;IAFE,cAAA;IbygDD;EACF;AargDD;EAAA;IAFI,eAAA;Ib2gDD;EACF;AalgDD;ECvBE,oBAAA;EACA,mBAAA;EACA,oBAAA;EACA,qBAAA;Ed4hDD;Aa//CD;ECvBE,oBAAA;EACA,qBAAA;EdyhDD;AezhDG;EACE,oBAAA;EAEA,iBAAA;EAEA,oBAAA;EACA,qBAAA;EfyhDL;AezgDG;EACE,aAAA;Ef2gDL;AepgDC;EACE,aAAA;EfsgDH;AevgDC;EACE,qBAAA;EfygDH;Ae1gDC;EACE,qBAAA;Ef4gDH;Ae7gDC;EACE,YAAA;Ef+gDH;AehhDC;EACE,qBAAA;EfkhDH;AenhDC;EACE,qBAAA;EfqhDH;AethDC;EACE,YAAA;EfwhDH;AezhDC;EACE,qBAAA;Ef2hDH;Ae5hDC;EACE,qBAAA;Ef8hDH;Ae/hDC;EACE,YAAA;EfiiDH;AeliDC;EACE,qBAAA;EfoiDH;AeriDC;EACE,oBAAA;EfuiDH;AezhDC;EACE,aAAA;Ef2hDH;Ae5hDC;EACE,qBAAA;Ef8hDH;Ae/hDC;EACE,qBAAA;EfiiDH;AeliDC;EACE,YAAA;EfoiDH;AeriDC;EACE,qBAAA;EfuiDH;AexiDC;EACE,qBAAA;Ef0iDH;Ae3iDC;EACE,YAAA;Ef6iDH;Ae9iDC;EACE,qBAAA;EfgjDH;AejjDC;EACE,qBAAA;EfmjDH;AepjDC;EACE,YAAA;EfsjDH;AevjDC;EACE,qBAAA;EfyjDH;Ae1jDC;EACE,oBAAA;Ef4jDH;AexjDC;EACE,aAAA;Ef0jDH;Ae1kDC;EACE,YAAA;Ef4kDH;Ae7kDC;EACE,oBAAA;Ef+kDH;AehlDC;EACE,oBAAA;EfklDH;AenlDC;EACE,WAAA;EfqlDH;AetlDC;EACE,oBAAA;EfwlDH;AezlDC;EACE,oBAAA;Ef2lDH;Ae5lDC;EACE,WAAA;Ef8lDH;Ae/lDC;EACE,oBAAA;EfimDH;AelmDC;EACE,oBAAA;EfomDH;AermDC;EACE,WAAA;EfumDH;AexmDC;EACE,oBAAA;Ef0mDH;Ae3mDC;EACE,mBAAA;Ef6mDH;AezmDC;EACE,YAAA;Ef2mDH;Ae7lDC;EACE,mBAAA;Ef+lDH;AehmDC;EACE,2BAAA;EfkmDH;AenmDC;EACE,2BAAA;EfqmDH;AetmDC;EACE,kBAAA;EfwmDH;AezmDC;EACE,2BAAA;Ef2mDH;Ae5mDC;EACE,2BAAA;Ef8mDH;Ae/mDC;EACE,kBAAA;EfinDH;AelnDC;EACE,2BAAA;EfonDH;AernDC;EACE,2BAAA;EfunDH;AexnDC;EACE,kBAAA;Ef0nDH;Ae3nDC;EACE,2BAAA;Ef6nDH;Ae9nDC;EACE,0BAAA;EfgoDH;AejoDC;EACE,iBAAA;EfmoDH;AanoDD;EElCI;IACE,aAAA;IfwqDH;EejqDD;IACE,aAAA;IfmqDD;EepqDD;IACE,qBAAA;IfsqDD;EevqDD;IACE,qBAAA;IfyqDD;Ee1qDD;IACE,YAAA;If4qDD;Ee7qDD;IACE,qBAAA;If+qDD;EehrDD;IACE,qBAAA;IfkrDD;EenrDD;IACE,YAAA;IfqrDD;EetrDD;IACE,qBAAA;IfwrDD;EezrDD;IACE,qBAAA;If2rDD;Ee5rDD;IACE,YAAA;If8rDD;Ee/rDD;IACE,qBAAA;IfisDD;EelsDD;IACE,oBAAA;IfosDD;EetrDD;IACE,aAAA;IfwrDD;EezrDD;IACE,qBAAA;If2rDD;Ee5rDD;IACE,qBAAA;If8rDD;Ee/rDD;IACE,YAAA;IfisDD;EelsDD;IACE,qBAAA;IfosDD;EersDD;IACE,qBAAA;IfusDD;EexsDD;IACE,YAAA;If0sDD;Ee3sDD;IACE,qBAAA;If6sDD;Ee9sDD;IACE,qBAAA;IfgtDD;EejtDD;IACE,YAAA;IfmtDD;EeptDD;IACE,qBAAA;IfstDD;EevtDD;IACE,oBAAA;IfytDD;EertDD;IACE,aAAA;IfutDD;EevuDD;IACE,YAAA;IfyuDD;Ee1uDD;IACE,oBAAA;If4uDD;Ee7uDD;IACE,oBAAA;If+uDD;EehvDD;IACE,WAAA;IfkvDD;EenvDD;IACE,oBAAA;IfqvDD;EetvDD;IACE,oBAAA;IfwvDD;EezvDD;IACE,WAAA;If2vDD;Ee5vDD;IACE,oBAAA;If8vDD;Ee/vDD;IACE,oBAAA;IfiwDD;EelwDD;IACE,WAAA;IfowDD;EerwDD;IACE,oBAAA;IfuwDD;EexwDD;IACE,mBAAA;If0wDD;EetwDD;IACE,YAAA;IfwwDD;Ee1vDD;IACE,mBAAA;If4vDD;Ee7vDD;IACE,2BAAA;If+vDD;EehwDD;IACE,2BAAA;IfkwDD;EenwDD;IACE,kBAAA;IfqwDD;EetwDD;IACE,2BAAA;IfwwDD;EezwDD;IACE,2BAAA;If2wDD;Ee5wDD;IACE,kBAAA;If8wDD;Ee/wDD;IACE,2BAAA;IfixDD;EelxDD;IACE,2BAAA;IfoxDD;EerxDD;IACE,kBAAA;IfuxDD;EexxDD;IACE,2BAAA;If0xDD;Ee3xDD;IACE,0BAAA;If6xDD;Ee9xDD;IACE,iBAAA;IfgyDD;EACF;AaxxDD;EE3CI;IACE,aAAA;Ifs0DH;Ee/zDD;IACE,aAAA;Ifi0DD;Eel0DD;IACE,qBAAA;Ifo0DD;Eer0DD;IACE,qBAAA;Ifu0DD;Eex0DD;IACE,YAAA;If00DD;Ee30DD;IACE,qBAAA;If60DD;Ee90DD;IACE,qBAAA;Ifg1DD;Eej1DD;IACE,YAAA;Ifm1DD;Eep1DD;IACE,qBAAA;Ifs1DD;Eev1DD;IACE,qBAAA;Ify1DD;Ee11DD;IACE,YAAA;If41DD;Ee71DD;IACE,qBAAA;If+1DD;Eeh2DD;IACE,oBAAA;Ifk2DD;Eep1DD;IACE,aAAA;Ifs1DD;Eev1DD;IACE,qBAAA;Ify1DD;Ee11DD;IACE,qBAAA;If41DD;Ee71DD;IACE,YAAA;If+1DD;Eeh2DD;IACE,qBAAA;Ifk2DD;Een2DD;IACE,qBAAA;Ifq2DD;Eet2DD;IACE,YAAA;Ifw2DD;Eez2DD;IACE,qBAAA;If22DD;Ee52DD;IACE,qBAAA;If82DD;Ee/2DD;IACE,YAAA;Ifi3DD;Eel3DD;IACE,qBAAA;Ifo3DD;Eer3DD;IACE,oBAAA;Ifu3DD;Een3DD;IACE,aAAA;Ifq3DD;Eer4DD;IACE,YAAA;Ifu4DD;Eex4DD;IACE,oBAAA;If04DD;Ee34DD;IACE,oBAAA;If64DD;Ee94DD;IACE,WAAA;Ifg5DD;Eej5DD;IACE,oBAAA;Ifm5DD;Eep5DD;IACE,oBAAA;Ifs5DD;Eev5DD;IACE,WAAA;Ify5DD;Ee15DD;IACE,oBAAA;If45DD;Ee75DD;IACE,oBAAA;If+5DD;Eeh6DD;IACE,WAAA;Ifk6DD;Een6DD;IACE,oBAAA;Ifq6DD;Eet6DD;IACE,mBAAA;Ifw6DD;Eep6DD;IACE,YAAA;Ifs6DD;Eex5DD;IACE,mBAAA;If05DD;Ee35DD;IACE,2BAAA;If65DD;Ee95DD;IACE,2BAAA;Ifg6DD;Eej6DD;IACE,kBAAA;Ifm6DD;Eep6DD;IACE,2BAAA;Ifs6DD;Eev6DD;IACE,2BAAA;Ify6DD;Ee16DD;IACE,kBAAA;If46DD;Ee76DD;IACE,2BAAA;If+6DD;Eeh7DD;IACE,2BAAA;Ifk7DD;Een7DD;IACE,kBAAA;Ifq7DD;Eet7DD;IACE,2BAAA;Ifw7DD;Eez7DD;IACE,0BAAA;If27DD;Ee57DD;IACE,iBAAA;If87DD;EACF;Aan7DD;EE9CI;IACE,aAAA;Ifo+DH;Ee79DD;IACE,aAAA;If+9DD;Eeh+DD;IACE,qBAAA;Ifk+DD;Een+DD;IACE,qBAAA;Ifq+DD;Eet+DD;IACE,YAAA;Ifw+DD;Eez+DD;IACE,qBAAA;If2+DD;Ee5+DD;IACE,qBAAA;If8+DD;Ee/+DD;IACE,YAAA;Ifi/DD;Eel/DD;IACE,qBAAA;Ifo/DD;Eer/DD;IACE,qBAAA;Ifu/DD;Eex/DD;IACE,YAAA;If0/DD;Ee3/DD;IACE,qBAAA;If6/DD;Ee9/DD;IACE,oBAAA;IfggED;Eel/DD;IACE,aAAA;Ifo/DD;Eer/DD;IACE,qBAAA;Ifu/DD;Eex/DD;IACE,qBAAA;If0/DD;Ee3/DD;IACE,YAAA;If6/DD;Ee9/DD;IACE,qBAAA;IfggED;EejgED;IACE,qBAAA;IfmgED;EepgED;IACE,YAAA;IfsgED;EevgED;IACE,qBAAA;IfygED;Ee1gED;IACE,qBAAA;If4gED;Ee7gED;IACE,YAAA;If+gED;EehhED;IACE,qBAAA;IfkhED;EenhED;IACE,oBAAA;IfqhED;EejhED;IACE,aAAA;IfmhED;EeniED;IACE,YAAA;IfqiED;EetiED;IACE,oBAAA;IfwiED;EeziED;IACE,oBAAA;If2iED;Ee5iED;IACE,WAAA;If8iED;Ee/iED;IACE,oBAAA;IfijED;EeljED;IACE,oBAAA;IfojED;EerjED;IACE,WAAA;IfujED;EexjED;IACE,oBAAA;If0jED;Ee3jED;IACE,oBAAA;If6jED;Ee9jED;IACE,WAAA;IfgkED;EejkED;IACE,oBAAA;IfmkED;EepkED;IACE,mBAAA;IfskED;EelkED;IACE,YAAA;IfokED;EetjED;IACE,mBAAA;IfwjED;EezjED;IACE,2BAAA;If2jED;Ee5jED;IACE,2BAAA;If8jED;Ee/jED;IACE,kBAAA;IfikED;EelkED;IACE,2BAAA;IfokED;EerkED;IACE,2BAAA;IfukED;EexkED;IACE,kBAAA;If0kED;Ee3kED;IACE,2BAAA;If6kED;Ee9kED;IACE,2BAAA;IfglED;EejlED;IACE,kBAAA;IfmlED;EeplED;IACE,2BAAA;IfslED;EevlED;IACE,0BAAA;IfylED;Ee1lED;IACE,iBAAA;If4lED;EACF;AgBhqED;EACE,+BAAA;EhBkqED;AgBhqED;EACE,kBAAA;EACA,qBAAA;EACA,gBAAA;EACA,kBAAA;EhBkqED;AgBhqED;EACE,kBAAA;EhBkqED;AgB5pED;EACE,aAAA;EACA,iBAAA;EACA,qBAAA;EhB8pED;AgBjqED;;;;;;EAWQ,cAAA;EACA,yBAAA;EACA,qBAAA;EACA,+BAAA;EhB8pEP;AgB5qED;EAoBI,wBAAA;EACA,kCAAA;EhB2pEH;AgBhrED;;;;;;EA8BQ,eAAA;EhB0pEP;AgBxrED;EAoCI,+BAAA;EhBupEH;AgB3rED;EAyCI,2BAAA;EhBqpEH;AgB9oED;;;;;;EAOQ,cAAA;EhB+oEP;AgBpoED;EACE,2BAAA;EhBsoED;AgBvoED;;;;;;EAQQ,2BAAA;EhBuoEP;AgB/oED;;EAeM,0BAAA;EhBooEL;AgB1nED;EAEI,2BAAA;EhB2nEH;AgBlnED;EAEI,2BAAA;EhBmnEH;AgB1mED;EACE,kBAAA;EACA,aAAA;EACA,uBAAA;EhB4mED;AgBvmEG;;EACE,kBAAA;EACA,aAAA;EACA,qBAAA;EhB0mEL;AiBtvEC;;;;;;;;;;;;EAOI,2BAAA;EjB6vEL;AiBvvEC;;;;;EAMI,2BAAA;EjBwvEL;AiB3wEC;;;;;;;;;;;;EAOI,2BAAA;EjBkxEL;AiB5wEC;;;;;EAMI,2BAAA;EjB6wEL;AiBhyEC;;;;;;;;;;;;EAOI,2BAAA;EjBuyEL;AiBjyEC;;;;;EAMI,2BAAA;EjBkyEL;AiBrzEC;;;;;;;;;;;;EAOI,2BAAA;EjB4zEL;AiBtzEC;;;;;EAMI,2BAAA;EjBuzEL;AiB10EC;;;;;;;;;;;;EAOI,2BAAA;EjBi1EL;AiB30EC;;;;;EAMI,2BAAA;EjB40EL;AgB1rED;EACE,kBAAA;EACA,mBAAA;EhB4rED;AgB/nED;EAAA;IA1DI,aAAA;IACA,qBAAA;IACA,oBAAA;IACA,8CAAA;IACA,2BAAA;IhB6rED;EgBvoEH;IAlDM,kBAAA;IhB4rEH;EgB1oEH;;;;;;IAzCY,qBAAA;IhB2rET;EgBlpEH;IAjCM,WAAA;IhBsrEH;EgBrpEH;;;;;;IAxBY,gBAAA;IhBqrET;EgB7pEH;;;;;;IApBY,iBAAA;IhByrET;EgBrqEH;;;;IAPY,kBAAA;IhBkrET;EACF;AkB54ED;EACE,YAAA;EACA,WAAA;EACA,WAAA;EAIA,cAAA;ElB24ED;AkBx4ED;EACE,gBAAA;EACA,aAAA;EACA,YAAA;EACA,qBAAA;EACA,iBAAA;EACA,sBAAA;EACA,gBAAA;EACA,WAAA;EACA,kCAAA;ElB04ED;AkBv4ED;EACE,uBAAA;EACA,iBAAA;EACA,oBAAA;EACA,mBAAA;ElBy4ED;AkB93ED;Eb4BE,gCAAA;EACG,6BAAA;EACK,wBAAA;ELq2ET;AkB93ED;;EAEE,iBAAA;EACA,oBAAA;EACA,qBAAA;ElBg4ED;AkB53ED;EACE,gBAAA;ElB83ED;AkB13ED;EACE,gBAAA;EACA,aAAA;ElB43ED;AkBx3ED;;EAEE,cAAA;ElB03ED;AkBt3ED;;;EZxEE,sBAAA;EAEA,4CAAA;EACA,sBAAA;ENk8ED;AkBt3ED;EACE,gBAAA;EACA,kBAAA;EACA,iBAAA;EACA,yBAAA;EACA,gBAAA;ElBw3ED;AkB91ED;EACE,gBAAA;EACA,aAAA;EACA,cAAA;EACA,mBAAA;EACA,iBAAA;EACA,yBAAA;EACA,gBAAA;EACA,2BAAA;EACA,wBAAA;EACA,2BAAA;EACA,oBAAA;EbzDA,0DAAA;EACQ,kDAAA;EAyHR,wFAAA;EACK,2EAAA;EACG,wEAAA;ELkyET;AmB16EC;EACE,uBAAA;EACA,YAAA;EdUF,wFAAA;EACQ,gFAAA;ELm6ET;AKl4EC;EACE,gBAAA;EACA,YAAA;ELo4EH;AKl4EC;EAA0B,gBAAA;ELq4E3B;AKp4EC;EAAgC,gBAAA;ELu4EjC;AkBt2EC;;;EAGE,qBAAA;EACA,2BAAA;EACA,YAAA;ElBw2EH;AkBp2EC;EACE,cAAA;ElBs2EH;AkB11ED;EACE,0BAAA;ElB41ED;AkBxzED;EAxBE;;;;IAIE,mBAAA;IlBm1ED;EkBj1EC;;;;;;;;IAEE,mBAAA;IlBy1EH;EkBt1EC;;;;;;;;IAEE,mBAAA;IlB81EH;EACF;AkBp1ED;EACE,qBAAA;ElBs1ED;AkB90ED;;EAEE,oBAAA;EACA,gBAAA;EACA,kBAAA;EACA,qBAAA;ElBg1ED;AkBr1ED;;EAQI,kBAAA;EACA,oBAAA;EACA,kBAAA;EACA,qBAAA;EACA,iBAAA;ElBi1EH;AkB90ED;;;;EAIE,oBAAA;EACA,oBAAA;EACA,oBAAA;ElBg1ED;AkB70ED;;EAEE,kBAAA;ElB+0ED;AkB30ED;;EAEE,uBAAA;EACA,oBAAA;EACA,kBAAA;EACA,wBAAA;EACA,qBAAA;EACA,iBAAA;ElB60ED;AkB30ED;;EAEE,eAAA;EACA,mBAAA;ElB60ED;AkBp0EC;;;;;;EAGE,qBAAA;ElBy0EH;AkBn0EC;;;;EAEE,qBAAA;ElBu0EH;AkBj0EC;;;;EAGI,qBAAA;ElBo0EL;AkBzzED;EAEE,kBAAA;EACA,qBAAA;EAEA,kBAAA;ElByzED;AkBvzEC;;EAEE,iBAAA;EACA,kBAAA;ElByzEH;AkB5yED;ECpPE,cAAA;EACA,mBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;EnBmiFD;AmBjiFC;EACE,cAAA;EACA,mBAAA;EnBmiFH;AmBhiFC;;EAEE,cAAA;EnBkiFH;AkBxzED;ECvPE,cAAA;EACA,mBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;EnBkjFD;AmBhjFC;EACE,cAAA;EACA,mBAAA;EnBkjFH;AmB/iFC;;EAEE,cAAA;EnBijFH;AkBv0ED;EAKI,cAAA;EACA,mBAAA;EACA,iBAAA;EACA,kBAAA;ElBq0EH;AkBj0ED;ECnQE,cAAA;EACA,oBAAA;EACA,iBAAA;EACA,wBAAA;EACA,oBAAA;EnBukFD;AmBrkFC;EACE,cAAA;EACA,mBAAA;EnBukFH;AmBpkFC;;EAEE,cAAA;EnBskFH;AkB70ED;ECtQE,cAAA;EACA,oBAAA;EACA,iBAAA;EACA,wBAAA;EACA,oBAAA;EnBslFD;AmBplFC;EACE,cAAA;EACA,mBAAA;EnBslFH;AmBnlFC;;EAEE,cAAA;EnBqlFH;AkB51ED;EAKI,cAAA;EACA,oBAAA;EACA,iBAAA;EACA,wBAAA;ElB01EH;AkBj1ED;EAEE,oBAAA;ElBk1ED;AkBp1ED;EAMI,uBAAA;ElBi1EH;AkB70ED;EACE,oBAAA;EACA,QAAA;EACA,UAAA;EACA,YAAA;EACA,gBAAA;EACA,aAAA;EACA,cAAA;EACA,mBAAA;EACA,oBAAA;EACA,sBAAA;ElB+0ED;AkB70ED;EACE,aAAA;EACA,cAAA;EACA,mBAAA;ElB+0ED;AkB70ED;EACE,aAAA;EACA,cAAA;EACA,mBAAA;ElB+0ED;AkB30ED;;;;;;;;;;EC7WI,gBAAA;EnBosFH;AkBv1ED;ECzWI,uBAAA;Ed+CF,0DAAA;EACQ,kDAAA;ELqpFT;AmBnsFG;EACE,uBAAA;Ed4CJ,2EAAA;EACQ,mEAAA;EL0pFT;AkBj2ED;EC/VI,gBAAA;EACA,uBAAA;EACA,2BAAA;EnBmsFH;AkBt2ED;ECzVI,gBAAA;EnBksFH;AkBt2ED;;;;;;;;;;EChXI,gBAAA;EnBkuFH;AkBl3ED;EC5WI,uBAAA;Ed+CF,0DAAA;EACQ,kDAAA;ELmrFT;AmBjuFG;EACE,uBAAA;Ed4CJ,2EAAA;EACQ,mEAAA;ELwrFT;AkB53ED;EClWI,gBAAA;EACA,uBAAA;EACA,2BAAA;EnBiuFH;AkBj4ED;EC5VI,gBAAA;EnBguFH;AkBj4ED;;;;;;;;;;ECnXI,gBAAA;EnBgwFH;AkB74ED;EC/WI,uBAAA;Ed+CF,0DAAA;EACQ,kDAAA;ELitFT;AmB/vFG;EACE,uBAAA;Ed4CJ,2EAAA;EACQ,mEAAA;ELstFT;AkBv5ED;ECrWI,gBAAA;EACA,uBAAA;EACA,2BAAA;EnB+vFH;AkB55ED;EC/VI,gBAAA;EnB8vFH;AkBx5EC;EACG,WAAA;ElB05EJ;AkBx5EC;EACG,QAAA;ElB05EJ;AkBh5ED;EACE,gBAAA;EACA,iBAAA;EACA,qBAAA;EACA,gBAAA;ElBk5ED;AkB/zED;EAAA;IA9DM,uBAAA;IACA,kBAAA;IACA,wBAAA;IlBi4EH;EkBr0EH;IAvDM,uBAAA;IACA,aAAA;IACA,wBAAA;IlB+3EH;EkB10EH;IAhDM,uBAAA;IlB63EH;EkB70EH;IA5CM,uBAAA;IACA,wBAAA;IlB43EH;EkBj1EH;;;IAtCQ,aAAA;IlB43EL;EkBt1EH;IAhCM,aAAA;IlBy3EH;EkBz1EH;IA5BM,kBAAA;IACA,wBAAA;IlBw3EH;EkB71EH;;IApBM,uBAAA;IACA,eAAA;IACA,kBAAA;IACA,wBAAA;IlBq3EH;EkBp2EH;;IAdQ,iBAAA;IlBs3EL;EkBx2EH;;IATM,oBAAA;IACA,gBAAA;IlBq3EH;EkB72EH;IAHM,QAAA;IlBm3EH;EACF;AkBz2ED;;;;EASI,eAAA;EACA,kBAAA;EACA,kBAAA;ElBs2EH;AkBj3ED;;EAiBI,kBAAA;ElBo2EH;AkBr3ED;EJzeE,oBAAA;EACA,qBAAA;Edi2FD;AkBl1EC;EAAA;IAVI,mBAAA;IACA,kBAAA;IACA,kBAAA;IlBg2EH;EACF;AkBh4ED;EAwCI,aAAA;ElB21EH;AkB90EC;EAAA;IAHM,0BAAA;IlBq1EL;EACF;AkB50EC;EAAA;IAHM,kBAAA;IlBm1EL;EACF;AoB73FD;EACE,uBAAA;EACA,kBAAA;EACA,qBAAA;EACA,oBAAA;EACA,wBAAA;EACA,gCAAA;MAAA,4BAAA;EACA,iBAAA;EACA,wBAAA;EACA,+BAAA;EACA,qBAAA;EC6BA,mBAAA;EACA,iBAAA;EACA,yBAAA;EACA,oBAAA;EhB4KA,2BAAA;EACG,wBAAA;EACC,uBAAA;EACI,mBAAA;ELwrFT;AoBh4FG;;;;;;EdrBF,sBAAA;EAEA,4CAAA;EACA,sBAAA;EN45FD;AoBp4FC;;;EAGE,gBAAA;EACA,uBAAA;EpBs4FH;AoBn4FC;;EAEE,YAAA;EACA,wBAAA;Ef2BF,0DAAA;EACQ,kDAAA;EL22FT;AoBn4FC;;;EAGE,qBAAA;EACA,sBAAA;EE9CF,eAAA;EAGA,2BAAA;EjB8DA,0BAAA;EACQ,kBAAA;ELq3FT;AoB/3FD;ECrDE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErBu7FD;AqBr7FC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErBu7FP;AqBr7FC;;;EAGE,wBAAA;ErBu7FH;AqBl7FG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErBg8FT;AoBx6FD;ECnBI,gBAAA;EACA,2BAAA;ErB87FH;AoBz6FD;ECxDE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErBo+FD;AqBl+FC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErBo+FP;AqBl+FC;;;EAGE,wBAAA;ErBo+FH;AqB/9FG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErB6+FT;AoBl9FD;ECtBI,gBAAA;EACA,2BAAA;ErB2+FH;AoBl9FD;EC5DE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErBihGD;AqB/gGC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErBihGP;AqB/gGC;;;EAGE,wBAAA;ErBihGH;AqB5gGG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErB0hGT;AoB3/FD;EC1BI,gBAAA;EACA,2BAAA;ErBwhGH;AoB3/FD;EChEE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErB8jGD;AqB5jGC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErB8jGP;AqB5jGC;;;EAGE,wBAAA;ErB8jGH;AqBzjGG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErBukGT;AoBpiGD;EC9BI,gBAAA;EACA,2BAAA;ErBqkGH;AoBpiGD;ECpEE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErB2mGD;AqBzmGC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErB2mGP;AqBzmGC;;;EAGE,wBAAA;ErB2mGH;AqBtmGG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErBonGT;AoB7kGD;EClCI,gBAAA;EACA,2BAAA;ErBknGH;AoB7kGD;ECxEE,gBAAA;EACA,2BAAA;EACA,uBAAA;ErBwpGD;AqBtpGC;;;;;;EAME,gBAAA;EACA,2BAAA;EACI,uBAAA;ErBwpGP;AqBtpGC;;;EAGE,wBAAA;ErBwpGH;AqBnpGG;;;;;;;;;;;;;;;;;;EAME,2BAAA;EACI,uBAAA;ErBiqGT;AoBtnGD;ECtCI,gBAAA;EACA,2BAAA;ErB+pGH;AoBjnGD;EACE,gBAAA;EACA,qBAAA;EACA,kBAAA;EpBmnGD;AoBjnGC;;;;;EAKE,+BAAA;Ef7BF,0BAAA;EACQ,kBAAA;ELipGT;AoBlnGC;;;;EAIE,2BAAA;EpBonGH;AoBlnGC;;EAEE,gBAAA;EACA,4BAAA;EACA,+BAAA;EpBonGH;AoBhnGG;;;;EAEE,gBAAA;EACA,uBAAA;EpBonGL;AoB3mGD;;EC/EE,oBAAA;EACA,iBAAA;EACA,wBAAA;EACA,oBAAA;ErB8rGD;AoB9mGD;;ECnFE,mBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;ErBqsGD;AoBjnGD;;ECvFE,kBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;ErB4sGD;AoBhnGD;EACE,gBAAA;EACA,aAAA;EpBknGD;AoB9mGD;EACE,iBAAA;EpBgnGD;AoBzmGC;;;EACE,aAAA;EpB6mGH;AuBjwGD;EACE,YAAA;ElBoLA,0CAAA;EACK,qCAAA;EACG,kCAAA;ELglGT;AuBpwGC;EACE,YAAA;EvBswGH;AuBlwGD;EACE,eAAA;EACA,oBAAA;EvBowGD;AuBlwGC;EAAY,gBAAA;EAAgB,qBAAA;EvBswG7B;AuBrwGC;EAAY,oBAAA;EvBwwGb;AuBvwGC;EAAY,0BAAA;EvB0wGb;AuBvwGD;EACE,oBAAA;EACA,WAAA;EACA,kBAAA;ElBsKA,iDAAA;EACQ,4CAAA;KAAA,yCAAA;EAOR,oCAAA;EACQ,+BAAA;KAAA,4BAAA;EAGR,0CAAA;EACQ,qCAAA;KAAA,kCAAA;EL4lGT;AwBtyGD;EACE,uBAAA;EACA,UAAA;EACA,WAAA;EACA,kBAAA;EACA,wBAAA;EACA,uBAAA;EACA,qCAAA;EACA,oCAAA;ExBwyGD;AwBpyGD;;EAEE,oBAAA;ExBsyGD;AwBlyGD;EACE,YAAA;ExBoyGD;AwBhyGD;EACE,oBAAA;EACA,WAAA;EACA,SAAA;EACA,eAAA;EACA,eAAA;EACA,aAAA;EACA,kBAAA;EACA,gBAAA;EACA,iBAAA;EACA,kBAAA;EACA,iBAAA;EACA,kBAAA;EACA,2BAAA;EACA,2BAAA;EACA,uCAAA;EACA,oBAAA;EnBuBA,qDAAA;EACQ,6CAAA;EmBtBR,sCAAA;UAAA,8BAAA;ExBmyGD;AwB9xGC;EACE,UAAA;EACA,YAAA;ExBgyGH;AwBzzGD;ECxBE,aAAA;EACA,eAAA;EACA,kBAAA;EACA,2BAAA;EzBo1GD;AwB/zGD;EAmCI,gBAAA;EACA,mBAAA;EACA,aAAA;EACA,qBAAA;EACA,yBAAA;EACA,gBAAA;EACA,qBAAA;ExB+xGH;AwBzxGC;;EAEE,uBAAA;EACA,gBAAA;EACA,2BAAA;ExB2xGH;AwBrxGC;;;EAGE,gBAAA;EACA,uBAAA;EACA,YAAA;EACA,2BAAA;ExBuxGH;AwB9wGC;;;EAGE,gBAAA;ExBgxGH;AwB5wGC;;EAEE,uBAAA;EACA,+BAAA;EACA,wBAAA;EE1GF,qEAAA;EF4GE,qBAAA;ExB8wGH;AwBzwGD;EAGI,gBAAA;ExBywGH;AwB5wGD;EAQI,YAAA;ExBuwGH;AwB/vGD;EACE,YAAA;EACA,UAAA;ExBiwGD;AwBzvGD;EACE,SAAA;EACA,aAAA;ExB2vGD;AwBvvGD;EACE,gBAAA;EACA,mBAAA;EACA,iBAAA;EACA,yBAAA;EACA,gBAAA;EACA,qBAAA;ExByvGD;AwBrvGD;EACE,iBAAA;EACA,SAAA;EACA,UAAA;EACA,WAAA;EACA,QAAA;EACA,cAAA;ExBuvGD;AwBnvGD;EACE,UAAA;EACA,YAAA;ExBqvGD;AwB7uGD;;EAII,eAAA;EACA,0BAAA;EACA,aAAA;ExB6uGH;AwBnvGD;;EAUI,WAAA;EACA,cAAA;EACA,oBAAA;ExB6uGH;AwBxtGD;EAXE;IAnEA,YAAA;IACA,UAAA;IxB0yGC;EwBxuGD;IAzDA,SAAA;IACA,aAAA;IxBoyGC;EACF;A2Bn7GD;;EAEE,oBAAA;EACA,uBAAA;EACA,wBAAA;E3Bq7GD;A2Bz7GD;;EAMI,oBAAA;EACA,aAAA;E3Bu7GH;A2Br7GG;;;;;;;;EAIE,YAAA;E3B27GL;A2Br7GD;;;;EAKI,mBAAA;E3Bs7GH;A2Bj7GD;EACE,mBAAA;E3Bm7GD;A2Bp7GD;;EAMI,aAAA;E3Bk7GH;A2Bx7GD;;;EAWI,kBAAA;E3Bk7GH;A2B96GD;EACE,kBAAA;E3Bg7GD;A2B56GD;EACE,gBAAA;E3B86GD;A2B76GC;ECjDA,+BAAA;EACG,4BAAA;E5Bi+GJ;A2B56GD;;EC9CE,8BAAA;EACG,2BAAA;E5B89GJ;A2B36GD;EACE,aAAA;E3B66GD;A2B36GD;EACE,kBAAA;E3B66GD;A2B36GD;;EClEE,+BAAA;EACG,4BAAA;E5Bi/GJ;A2B16GD;EChEE,8BAAA;EACG,2BAAA;E5B6+GJ;A2Bz6GD;;EAEE,YAAA;E3B26GD;A2B15GD;EACE,mBAAA;EACA,oBAAA;E3B45GD;A2B15GD;EACE,oBAAA;EACA,qBAAA;E3B45GD;A2Bv5GD;EtB9CE,0DAAA;EACQ,kDAAA;ELw8GT;A2Bv5GC;EtBlDA,0BAAA;EACQ,kBAAA;EL48GT;A2Bp5GD;EACE,gBAAA;E3Bs5GD;A2Bn5GD;EACE,yBAAA;EACA,wBAAA;E3Bq5GD;A2Bl5GD;EACE,yBAAA;E3Bo5GD;A2B74GD;;;EAII,gBAAA;EACA,aAAA;EACA,aAAA;EACA,iBAAA;E3B84GH;A2Br5GD;EAcM,aAAA;E3B04GL;A2Bx5GD;;;;EAsBI,kBAAA;EACA,gBAAA;E3Bw4GH;A2Bn4GC;EACE,kBAAA;E3Bq4GH;A2Bn4GC;EACE,8BAAA;ECnKF,+BAAA;EACC,8BAAA;E5ByiHF;A2Bp4GC;EACE,gCAAA;EC/KF,4BAAA;EACC,2BAAA;E5BsjHF;A2Bp4GD;EACE,kBAAA;E3Bs4GD;A2Bp4GD;;EC9KE,+BAAA;EACC,8BAAA;E5BsjHF;A2Bn4GD;EC5LE,4BAAA;EACC,2BAAA;E5BkkHF;A2B/3GD;EACE,gBAAA;EACA,aAAA;EACA,qBAAA;EACA,2BAAA;E3Bi4GD;A2Br4GD;;EAOI,aAAA;EACA,qBAAA;EACA,WAAA;E3Bk4GH;A2B34GD;EAYI,aAAA;E3Bk4GH;A2B94GD;EAgBI,YAAA;E3Bi4GH;A2Bh3GD;;;;EAKM,oBAAA;EACA,wBAAA;EACA,sBAAA;E3Bi3GL;A6B1lHD;EACE,oBAAA;EACA,gBAAA;EACA,2BAAA;E7B4lHD;A6BzlHC;EACE,aAAA;EACA,iBAAA;EACA,kBAAA;E7B2lHH;A6BpmHD;EAeI,oBAAA;EACA,YAAA;EAKA,aAAA;EAEA,aAAA;EACA,kBAAA;E7BmlHH;A6B1kHD;;;EV8BE,cAAA;EACA,oBAAA;EACA,iBAAA;EACA,wBAAA;EACA,oBAAA;EnBijHD;AmB/iHC;;;EACE,cAAA;EACA,mBAAA;EnBmjHH;AmBhjHC;;;;;;EAEE,cAAA;EnBsjHH;A6B5lHD;;;EVyBE,cAAA;EACA,mBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;EnBwkHD;AmBtkHC;;;EACE,cAAA;EACA,mBAAA;EnB0kHH;AmBvkHC;;;;;;EAEE,cAAA;EnB6kHH;A6B1mHD;;;EAGE,qBAAA;E7B4mHD;A6B1mHC;;;EACE,kBAAA;E7B8mHH;A6B1mHD;;EAEE,WAAA;EACA,qBAAA;EACA,wBAAA;E7B4mHD;A6BvmHD;EACE,mBAAA;EACA,iBAAA;EACA,qBAAA;EACA,gBAAA;EACA,gBAAA;EACA,oBAAA;EACA,2BAAA;EACA,2BAAA;EACA,oBAAA;E7BymHD;A6BtmHC;EACE,mBAAA;EACA,iBAAA;EACA,oBAAA;E7BwmHH;A6BtmHC;EACE,oBAAA;EACA,iBAAA;EACA,oBAAA;E7BwmHH;A6B5nHD;;EA0BI,eAAA;E7BsmHH;A6BjmHD;;;;;;;EDhGE,+BAAA;EACG,4BAAA;E5B0sHJ;A6BlmHD;EACE,iBAAA;E7BomHD;A6BlmHD;;;;;;;EDpGE,8BAAA;EACG,2BAAA;E5B+sHJ;A6BnmHD;EACE,gBAAA;E7BqmHD;A6BhmHD;EACE,oBAAA;EAGA,cAAA;EACA,qBAAA;E7BgmHD;A6BrmHD;EAUI,oBAAA;E7B8lHH;A6BxmHD;EAYM,mBAAA;E7B+lHL;A6B5lHG;;;EAGE,YAAA;E7B8lHL;A6BzlHC;;EAGI,oBAAA;E7B0lHL;A6BvlHC;;EAGI,mBAAA;E7BwlHL;A8BlvHD;EACE,kBAAA;EACA,iBAAA;EACA,kBAAA;E9BovHD;A8BvvHD;EAOI,oBAAA;EACA,gBAAA;E9BmvHH;A8B3vHD;EAWM,oBAAA;EACA,gBAAA;EACA,oBAAA;E9BmvHL;A8BlvHK;;EAEE,uBAAA;EACA,2BAAA;E9BovHP;A8B/uHG;EACE,gBAAA;E9BivHL;A8B/uHK;;EAEE,gBAAA;EACA,uBAAA;EACA,+BAAA;EACA,qBAAA;E9BivHP;A8B1uHG;;;EAGE,2BAAA;EACA,uBAAA;E9B4uHL;A8BrxHD;ELHE,aAAA;EACA,eAAA;EACA,kBAAA;EACA,2BAAA;EzB2xHD;A8B3xHD;EA0DI,iBAAA;E9BouHH;A8B3tHD;EACE,kCAAA;E9B6tHD;A8B9tHD;EAGI,aAAA;EAEA,qBAAA;E9B6tHH;A8BluHD;EASM,mBAAA;EACA,yBAAA;EACA,+BAAA;EACA,4BAAA;E9B4tHL;A8B3tHK;EACE,uCAAA;E9B6tHP;A8BvtHK;;;EAGE,gBAAA;EACA,2BAAA;EACA,2BAAA;EACA,kCAAA;EACA,iBAAA;E9BytHP;A8BptHC;EAqDA,aAAA;EA8BA,kBAAA;E9BqoHD;A8BxtHC;EAwDE,aAAA;E9BmqHH;A8B3tHC;EA0DI,oBAAA;EACA,oBAAA;E9BoqHL;A8B/tHC;EAgEE,WAAA;EACA,YAAA;E9BkqHH;A8BtpHD;EAAA;IAPM,qBAAA;IACA,WAAA;I9BiqHH;E8B3pHH;IAJQ,kBAAA;I9BkqHL;EACF;A8B5uHC;EAuFE,iBAAA;EACA,oBAAA;E9BwpHH;A8BhvHC;;;EA8FE,2BAAA;E9BupHH;A8BzoHD;EAAA;IATM,kCAAA;IACA,4BAAA;I9BspHH;E8B9oHH;;;IAHM,8BAAA;I9BspHH;EACF;A8BvvHD;EAEI,aAAA;E9BwvHH;A8B1vHD;EAMM,oBAAA;E9BuvHL;A8B7vHD;EASM,kBAAA;E9BuvHL;A8BlvHK;;;EAGE,gBAAA;EACA,2BAAA;E9BovHP;A8B5uHD;EAEI,aAAA;E9B6uHH;A8B/uHD;EAIM,iBAAA;EACA,gBAAA;E9B8uHL;A8BluHD;EACE,aAAA;E9BouHD;A8BruHD;EAII,aAAA;E9BouHH;A8BxuHD;EAMM,oBAAA;EACA,oBAAA;E9BquHL;A8B5uHD;EAYI,WAAA;EACA,YAAA;E9BmuHH;A8BvtHD;EAAA;IAPM,qBAAA;IACA,WAAA;I9BkuHH;E8B5tHH;IAJQ,kBAAA;I9BmuHL;EACF;A8B3tHD;EACE,kBAAA;E9B6tHD;A8B9tHD;EAKI,iBAAA;EACA,oBAAA;E9B4tHH;A8BluHD;;;EAYI,2BAAA;E9B2tHH;A8B7sHD;EAAA;IATM,kCAAA;IACA,4BAAA;I9B0tHH;E8BltHH;;;IAHM,8BAAA;I9B0tHH;EACF;A8BjtHD;EAEI,eAAA;EACA,oBAAA;E9BktHH;A8BrtHD;EAMI,gBAAA;EACA,qBAAA;E9BktHH;A8BzsHD;EAEE,kBAAA;EF7OA,4BAAA;EACC,2BAAA;E5Bw7HF;A+Bl7HD;EACE,oBAAA;EACA,kBAAA;EACA,qBAAA;EACA,+BAAA;E/Bo7HD;A+B56HD;EAAA;IAFI,oBAAA;I/Bk7HD;EACF;A+Bn6HD;EAAA;IAFI,aAAA;I/By6HD;EACF;A+B35HD;EACE,qBAAA;EACA,qBAAA;EACA,oBAAA;EACA,mCAAA;EACA,4DAAA;UAAA,oDAAA;EAEA,mCAAA;E/B45HD;A+B15HC;EACE,kBAAA;E/B45HH;A+B/3HD;EAAA;IAzBI,aAAA;IACA,eAAA;IACA,0BAAA;YAAA,kBAAA;I/B45HD;E+B15HC;IACE,2BAAA;IACA,gCAAA;IACA,yBAAA;IACA,mBAAA;IACA,8BAAA;I/B45HH;E+Bz5HC;IACE,qBAAA;I/B25HH;E+Bt5HC;;;IAGE,iBAAA;IACA,kBAAA;I/Bw5HH;EACF;A+Bp5HD;;EAGI,mBAAA;E/Bq5HH;A+Bh5HC;EAAA;;IAFI,mBAAA;I/Bu5HH;EACF;A+B94HD;;;;EAII,qBAAA;EACA,oBAAA;E/Bg5HH;A+B14HC;EAAA;;;;IAHI,iBAAA;IACA,gBAAA;I/Bo5HH;EACF;A+Bx4HD;EACE,eAAA;EACA,uBAAA;E/B04HD;A+Br4HD;EAAA;IAFI,kBAAA;I/B24HD;EACF;A+Bv4HD;;EAEE,iBAAA;EACA,UAAA;EACA,SAAA;EACA,eAAA;E/By4HD;A+Bn4HD;EAAA;;IAFI,kBAAA;I/B04HD;EACF;A+Bx4HD;EACE,QAAA;EACA,uBAAA;E/B04HD;A+Bx4HD;EACE,WAAA;EACA,kBAAA;EACA,uBAAA;E/B04HD;A+Bp4HD;EACE,aAAA;EACA,oBAAA;EACA,iBAAA;EACA,mBAAA;EACA,cAAA;E/Bs4HD;A+Bp4HC;;EAEE,uBAAA;E/Bs4HH;A+B/4HD;EAaI,gBAAA;E/Bq4HH;A+B53HD;EALI;;IAEE,oBAAA;I/Bo4HH;EACF;A+B13HD;EACE,oBAAA;EACA,cAAA;EACA,oBAAA;EACA,mBAAA;EC/LA,iBAAA;EACA,oBAAA;EDgMA,+BAAA;EACA,wBAAA;EACA,+BAAA;EACA,oBAAA;E/B63HD;A+Bz3HC;EACE,YAAA;E/B23HH;A+Bz4HD;EAmBI,gBAAA;EACA,aAAA;EACA,aAAA;EACA,oBAAA;E/By3HH;A+B/4HD;EAyBI,iBAAA;E/By3HH;A+Bn3HD;EAAA;IAFI,eAAA;I/By3HD;EACF;A+Bh3HD;EACE,qBAAA;E/Bk3HD;A+Bn3HD;EAII,mBAAA;EACA,sBAAA;EACA,mBAAA;E/Bk3HH;A+Bt1HC;EAAA;IAtBI,kBAAA;IACA,aAAA;IACA,aAAA;IACA,eAAA;IACA,+BAAA;IACA,WAAA;IACA,0BAAA;YAAA,kBAAA;I/Bg3HH;E+Bh2HD;;IAbM,4BAAA;I/Bi3HL;E+Bp2HD;IAVM,mBAAA;I/Bi3HL;E+Bh3HK;;IAEE,wBAAA;I/Bk3HP;EACF;A+Bh2HD;EAAA;IAXI,aAAA;IACA,WAAA;I/B+2HD;E+Br2HH;IAPM,aAAA;I/B+2HH;E+Bx2HH;IALQ,mBAAA;IACA,sBAAA;I/Bg3HL;EACF;A+Br2HD;EACE,oBAAA;EACA,qBAAA;EACA,oBAAA;EACA,mCAAA;EACA,sCAAA;E1B/NA,8FAAA;EACQ,sFAAA;E2B/DR,iBAAA;EACA,oBAAA;EhCuoID;AkB9pHD;EAAA;IA9DM,uBAAA;IACA,kBAAA;IACA,wBAAA;IlBguHH;EkBpqHH;IAvDM,uBAAA;IACA,aAAA;IACA,wBAAA;IlB8tHH;EkBzqHH;IAhDM,uBAAA;IlB4tHH;EkB5qHH;IA5CM,uBAAA;IACA,wBAAA;IlB2tHH;EkBhrHH;;;IAtCQ,aAAA;IlB2tHL;EkBrrHH;IAhCM,aAAA;IlBwtHH;EkBxrHH;IA5BM,kBAAA;IACA,wBAAA;IlButHH;EkB5rHH;;IApBM,uBAAA;IACA,eAAA;IACA,kBAAA;IACA,wBAAA;IlBotHH;EkBnsHH;;IAdQ,iBAAA;IlBqtHL;EkBvsHH;;IATM,oBAAA;IACA,gBAAA;IlBotHH;EkB5sHH;IAHM,QAAA;IlBktHH;EACF;A+B94HC;EAAA;IANI,oBAAA;I/Bw5HH;E+Bt5HG;IACE,kBAAA;I/Bw5HL;EACF;A+Bv4HD;EAAA;IARI,aAAA;IACA,WAAA;IACA,gBAAA;IACA,iBAAA;IACA,gBAAA;IACA,mBAAA;I1B1PF,0BAAA;IACQ,kBAAA;IL8oIP;EACF;A+B74HD;EACE,eAAA;EHrUA,4BAAA;EACC,2BAAA;E5BqtIF;A+B74HD;EACE,kBAAA;EH1UA,8BAAA;EACC,6BAAA;EAOD,+BAAA;EACC,8BAAA;E5BotIF;A+Bz4HD;ECjVE,iBAAA;EACA,oBAAA;EhC6tID;A+B14HC;ECpVA,kBAAA;EACA,qBAAA;EhCiuID;A+B34HC;ECvVA,kBAAA;EACA,qBAAA;EhCquID;A+Br4HD;ECjWE,kBAAA;EACA,qBAAA;EhCyuID;A+Bj4HD;EAAA;IAJI,aAAA;IACA,mBAAA;IACA,oBAAA;I/By4HD;EACF;A+B52HD;EAhBE;IEzWA,wBAAA;IjCyuIC;E+B/3HD;IE7WA,yBAAA;IF+WE,qBAAA;I/Bi4HD;E+Bn4HD;IAKI,iBAAA;I/Bi4HH;EACF;A+Bx3HD;EACE,2BAAA;EACA,uBAAA;E/B03HD;A+B53HD;EAKI,gBAAA;E/B03HH;A+Bz3HG;;EAEE,gBAAA;EACA,+BAAA;E/B23HL;A+Bp4HD;EAcI,gBAAA;E/By3HH;A+Bv4HD;EAmBM,gBAAA;E/Bu3HL;A+Br3HK;;EAEE,gBAAA;EACA,+BAAA;E/Bu3HP;A+Bn3HK;;;EAGE,gBAAA;EACA,2BAAA;E/Bq3HP;A+Bj3HK;;;EAGE,gBAAA;EACA,+BAAA;E/Bm3HP;A+B35HD;EA8CI,uBAAA;E/Bg3HH;A+B/2HG;;EAEE,2BAAA;E/Bi3HL;A+Bl6HD;EAoDM,2BAAA;E/Bi3HL;A+Br6HD;;EA0DI,uBAAA;E/B+2HH;A+Bx2HK;;;EAGE,2BAAA;EACA,gBAAA;E/B02HP;A+Bz0HC;EAAA;IAzBQ,gBAAA;I/Bs2HP;E+Br2HO;;IAEE,gBAAA;IACA,+BAAA;I/Bu2HT;E+Bn2HO;;;IAGE,gBAAA;IACA,2BAAA;I/Bq2HT;E+Bj2HO;;;IAGE,gBAAA;IACA,+BAAA;I/Bm2HT;EACF;A+Br8HD;EA8GI,gBAAA;E/B01HH;A+Bz1HG;EACE,gBAAA;E/B21HL;A+B38HD;EAqHI,gBAAA;E/By1HH;A+Bx1HG;;EAEE,gBAAA;E/B01HL;A+Bt1HK;;;;EAEE,gBAAA;E/B01HP;A+Bl1HD;EACE,2BAAA;EACA,uBAAA;E/Bo1HD;A+Bt1HD;EAKI,gBAAA;E/Bo1HH;A+Bn1HG;;EAEE,gBAAA;EACA,+BAAA;E/Bq1HL;A+B91HD;EAcI,gBAAA;E/Bm1HH;A+Bj2HD;EAmBM,gBAAA;E/Bi1HL;A+B/0HK;;EAEE,gBAAA;EACA,+BAAA;E/Bi1HP;A+B70HK;;;EAGE,gBAAA;EACA,2BAAA;E/B+0HP;A+B30HK;;;EAGE,gBAAA;EACA,+BAAA;E/B60HP;A+Br3HD;EA+CI,uBAAA;E/By0HH;A+Bx0HG;;EAEE,2BAAA;E/B00HL;A+B53HD;EAqDM,2BAAA;E/B00HL;A+B/3HD;;EA2DI,uBAAA;E/Bw0HH;A+Bl0HK;;;EAGE,2BAAA;EACA,gBAAA;E/Bo0HP;A+B7xHC;EAAA;IA/BQ,uBAAA;I/Bg0HP;E+BjyHD;IA5BQ,2BAAA;I/Bg0HP;E+BpyHD;IAzBQ,gBAAA;I/Bg0HP;E+B/zHO;;IAEE,gBAAA;IACA,+BAAA;I/Bi0HT;E+B7zHO;;;IAGE,gBAAA;IACA,2BAAA;I/B+zHT;E+B3zHO;;;IAGE,gBAAA;IACA,+BAAA;I/B6zHT;EACF;A+Br6HD;EA+GI,gBAAA;E/ByzHH;A+BxzHG;EACE,gBAAA;E/B0zHL;A+B36HD;EAsHI,gBAAA;E/BwzHH;A+BvzHG;;EAEE,gBAAA;E/ByzHL;A+BrzHK;;;;EAEE,gBAAA;E/ByzHP;AkCp8ID;EACE,mBAAA;EACA,qBAAA;EACA,kBAAA;EACA,2BAAA;EACA,oBAAA;ElCs8ID;AkC38ID;EAQI,uBAAA;ElCs8IH;AkC98ID;EAWM,mBAAA;EACA,gBAAA;EACA,gBAAA;ElCs8IL;AkCn9ID;EAkBI,gBAAA;ElCo8IH;AmCx9ID;EACE,uBAAA;EACA,iBAAA;EACA,gBAAA;EACA,oBAAA;EnC09ID;AmC99ID;EAOI,iBAAA;EnC09IH;AmCj+ID;;EAUM,oBAAA;EACA,aAAA;EACA,mBAAA;EACA,yBAAA;EACA,uBAAA;EACA,gBAAA;EACA,2BAAA;EACA,2BAAA;EACA,mBAAA;EnC29IL;AmCz9IG;;EAGI,gBAAA;EPXN,gCAAA;EACG,6BAAA;E5Bs+IJ;AmCx9IG;;EPvBF,iCAAA;EACG,8BAAA;E5Bm/IJ;AmCn9IG;;;;EAEE,gBAAA;EACA,2BAAA;EACA,uBAAA;EnCu9IL;AmCj9IG;;;;;;EAGE,YAAA;EACA,gBAAA;EACA,2BAAA;EACA,uBAAA;EACA,iBAAA;EnCs9IL;AmC5gJD;;;;;;EAiEM,gBAAA;EACA,2BAAA;EACA,uBAAA;EACA,qBAAA;EnCm9IL;AmC18ID;;EC1EM,oBAAA;EACA,iBAAA;EpCwhJL;AoCthJG;;ERMF,gCAAA;EACG,6BAAA;E5BohJJ;AoCrhJG;;ERRF,iCAAA;EACG,8BAAA;E5BiiJJ;AmCp9ID;;EC/EM,mBAAA;EACA,iBAAA;EpCuiJL;AoCriJG;;ERMF,gCAAA;EACG,6BAAA;E5BmiJJ;AoCpiJG;;ERRF,iCAAA;EACG,8BAAA;E5BgjJJ;AqCnjJD;EACE,iBAAA;EACA,gBAAA;EACA,kBAAA;EACA,oBAAA;ErCqjJD;AqCzjJD;EAOI,iBAAA;ErCqjJH;AqC5jJD;;EAUM,uBAAA;EACA,mBAAA;EACA,2BAAA;EACA,2BAAA;EACA,qBAAA;ErCsjJL;AqCpkJD;;EAmBM,uBAAA;EACA,2BAAA;ErCqjJL;AqCzkJD;;EA2BM,cAAA;ErCkjJL;AqC7kJD;;EAkCM,aAAA;ErC+iJL;AqCjlJD;;;;EA2CM,gBAAA;EACA,2BAAA;EACA,qBAAA;ErC4iJL;AsC1lJD;EACE,iBAAA;EACA,yBAAA;EACA,gBAAA;EACA,mBAAA;EACA,gBAAA;EACA,gBAAA;EACA,oBAAA;EACA,qBAAA;EACA,0BAAA;EACA,sBAAA;EtC4lJD;AsCxlJG;;EAEE,gBAAA;EACA,uBAAA;EACA,iBAAA;EtC0lJL;AsCrlJC;EACE,eAAA;EtCulJH;AsCnlJC;EACE,oBAAA;EACA,WAAA;EtCqlJH;AsC9kJD;ECtCE,2BAAA;EvCunJD;AuCpnJG;;EAEE,2BAAA;EvCsnJL;AsCjlJD;EC1CE,2BAAA;EvC8nJD;AuC3nJG;;EAEE,2BAAA;EvC6nJL;AsCplJD;EC9CE,2BAAA;EvCqoJD;AuCloJG;;EAEE,2BAAA;EvCooJL;AsCvlJD;EClDE,2BAAA;EvC4oJD;AuCzoJG;;EAEE,2BAAA;EvC2oJL;AsC1lJD;ECtDE,2BAAA;EvCmpJD;AuChpJG;;EAEE,2BAAA;EvCkpJL;AsC7lJD;EC1DE,2BAAA;EvC0pJD;AuCvpJG;;EAEE,2BAAA;EvCypJL;AwC3pJD;EACE,uBAAA;EACA,iBAAA;EACA,kBAAA;EACA,iBAAA;EACA,mBAAA;EACA,gBAAA;EACA,gBAAA;EACA,0BAAA;EACA,qBAAA;EACA,oBAAA;EACA,2BAAA;EACA,qBAAA;ExC6pJD;AwC1pJC;EACE,eAAA;ExC4pJH;AwCxpJC;EACE,oBAAA;EACA,WAAA;ExC0pJH;AwCvpJC;EACE,QAAA;EACA,kBAAA;ExCypJH;AwCppJG;;EAEE,gBAAA;EACA,uBAAA;EACA,iBAAA;ExCspJL;AwCjpJC;;EAEE,gBAAA;EACA,2BAAA;ExCmpJH;AwChpJC;EACE,cAAA;ExCkpJH;AwC/oJC;EACE,mBAAA;ExCipJH;AwC9oJC;EACE,kBAAA;ExCgpJH;AyCzsJD;EACE,oBAAA;EACA,qBAAA;EACA,gBAAA;EACA,2BAAA;EzC2sJD;AyC/sJD;;EAQI,gBAAA;EzC2sJH;AyCntJD;EAYI,qBAAA;EACA,iBAAA;EACA,kBAAA;EzC0sJH;AyCxtJD;EAkBI,2BAAA;EzCysJH;AyCtsJC;;EAEE,oBAAA;EzCwsJH;AyC/tJD;EA2BI,iBAAA;EzCusJH;AyCtrJD;EAAA;IAbI,iBAAA;IzCusJD;EyCrsJC;;IAEE,oBAAA;IACA,qBAAA;IzCusJH;EyC/rJH;;IAHM,iBAAA;IzCssJH;EACF;A0C/uJD;EACE,gBAAA;EACA,cAAA;EACA,qBAAA;EACA,yBAAA;EACA,2BAAA;EACA,2BAAA;EACA,oBAAA;ErCiLA,6CAAA;EACK,wCAAA;EACG,qCAAA;ELikJT;A0C3vJD;;EAaI,mBAAA;EACA,oBAAA;E1CkvJH;A0C9uJC;;;EAGE,uBAAA;E1CgvJH;A0CrwJD;EA0BI,cAAA;EACA,gBAAA;E1C8uJH;A2CvwJD;EACE,eAAA;EACA,qBAAA;EACA,+BAAA;EACA,oBAAA;E3CywJD;A2C7wJD;EAQI,eAAA;EAEA,gBAAA;E3CuwJH;A2CjxJD;EAeI,mBAAA;E3CqwJH;A2CpxJD;;EAqBI,kBAAA;E3CmwJH;A2CxxJD;EAyBI,iBAAA;E3CkwJH;A2C1vJD;;EAEE,qBAAA;E3C4vJD;A2C9vJD;;EAMI,oBAAA;EACA,WAAA;EACA,cAAA;EACA,gBAAA;E3C4vJH;A2CpvJD;ECvDE,2BAAA;EACA,uBAAA;EACA,gBAAA;E5C8yJD;A2CzvJD;EClDI,2BAAA;E5C8yJH;A2C5vJD;EC/CI,gBAAA;E5C8yJH;A2C3vJD;EC3DE,2BAAA;EACA,uBAAA;EACA,gBAAA;E5CyzJD;A2ChwJD;ECtDI,2BAAA;E5CyzJH;A2CnwJD;ECnDI,gBAAA;E5CyzJH;A2ClwJD;EC/DE,2BAAA;EACA,uBAAA;EACA,gBAAA;E5Co0JD;A2CvwJD;EC1DI,2BAAA;E5Co0JH;A2C1wJD;ECvDI,gBAAA;E5Co0JH;A2CzwJD;ECnEE,2BAAA;EACA,uBAAA;EACA,gBAAA;E5C+0JD;A2C9wJD;EC9DI,2BAAA;E5C+0JH;A2CjxJD;EC3DI,gBAAA;E5C+0JH;A6Cj1JD;EACE;IAAQ,6BAAA;I7Co1JP;E6Cn1JD;IAAQ,0BAAA;I7Cs1JP;EACF;A6Cn1JD;EACE;IAAQ,6BAAA;I7Cs1JP;E6Cr1JD;IAAQ,0BAAA;I7Cw1JP;EACF;A6C31JD;EACE;IAAQ,6BAAA;I7Cs1JP;E6Cr1JD;IAAQ,0BAAA;I7Cw1JP;EACF;A6Cj1JD;EACE,kBAAA;EACA,cAAA;EACA,qBAAA;EACA,2BAAA;EACA,oBAAA;ExCsCA,wDAAA;EACQ,gDAAA;EL8yJT;A6Ch1JD;EACE,aAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,mBAAA;EACA,gBAAA;EACA,oBAAA;EACA,2BAAA;ExCyBA,wDAAA;EACQ,gDAAA;EAyHR,qCAAA;EACK,gCAAA;EACG,6BAAA;ELksJT;A6C70JD;;ECCI,+MAAA;EACA,0MAAA;EACA,uMAAA;EDAF,oCAAA;UAAA,4BAAA;E7Ci1JD;A6C10JD;;ExC5CE,4DAAA;EACK,uDAAA;EACG,oDAAA;EL03JT;A6Cv0JD;EErEE,2BAAA;E/C+4JD;A+C54JC;EDgDE,+MAAA;EACA,0MAAA;EACA,uMAAA;E9C+1JH;A6C30JD;EEzEE,2BAAA;E/Cu5JD;A+Cp5JC;EDgDE,+MAAA;EACA,0MAAA;EACA,uMAAA;E9Cu2JH;A6C/0JD;EE7EE,2BAAA;E/C+5JD;A+C55JC;EDgDE,+MAAA;EACA,0MAAA;EACA,uMAAA;E9C+2JH;A6Cn1JD;EEjFE,2BAAA;E/Cu6JD;A+Cp6JC;EDgDE,+MAAA;EACA,0MAAA;EACA,uMAAA;E9Cu3JH;AgD/6JD;EAEE,kBAAA;EhDg7JD;AgD96JC;EACE,eAAA;EhDg7JH;AgD56JD;;EAEE,SAAA;EACA,kBAAA;EhD86JD;AgD36JD;EACE,gBAAA;EhD66JD;AgD16JD;EACE,gBAAA;EhD46JD;AgDz6JD;;EAEE,oBAAA;EhD26JD;AgDx6JD;;EAEE,qBAAA;EhD06JD;AgDv6JD;;;EAGE,qBAAA;EACA,qBAAA;EhDy6JD;AgDt6JD;EACE,wBAAA;EhDw6JD;AgDr6JD;EACE,wBAAA;EhDu6JD;AgDn6JD;EACE,eAAA;EACA,oBAAA;EhDq6JD;AgD/5JD;EACE,iBAAA;EACA,kBAAA;EhDi6JD;AiDn9JD;EAEE,qBAAA;EACA,iBAAA;EjDo9JD;AiD58JD;EACE,oBAAA;EACA,gBAAA;EACA,oBAAA;EAEA,qBAAA;EACA,2BAAA;EACA,2BAAA;EjD68JD;AiD18JC;ErB3BA,8BAAA;EACC,6BAAA;E5Bw+JF;AiD38JC;EACE,kBAAA;ErBvBF,iCAAA;EACC,gCAAA;E5Bq+JF;AiDp8JD;EACE,gBAAA;EjDs8JD;AiDv8JD;EAII,gBAAA;EjDs8JH;AiDl8JC;;EAEE,uBAAA;EACA,gBAAA;EACA,2BAAA;EjDo8JH;AiD97JC;;;EAGE,2BAAA;EACA,gBAAA;EACA,qBAAA;EjDg8JH;AiDr8JC;;;EASI,gBAAA;EjDi8JL;AiD18JC;;;EAYI,gBAAA;EjDm8JL;AiD97JC;;;EAGE,YAAA;EACA,gBAAA;EACA,2BAAA;EACA,uBAAA;EjDg8JH;AiDt8JC;;;;;;;;;EAYI,gBAAA;EjDq8JL;AiDj9JC;;;EAeI,gBAAA;EjDu8JL;AkDniKC;EACE,gBAAA;EACA,2BAAA;ElDqiKH;AkDniKG;EACE,gBAAA;ElDqiKL;AkDtiKG;EAII,gBAAA;ElDqiKP;AkDliKK;;EAEE,gBAAA;EACA,2BAAA;ElDoiKP;AkDliKK;;;EAGE,aAAA;EACA,2BAAA;EACA,uBAAA;ElDoiKP;AkDzjKC;EACE,gBAAA;EACA,2BAAA;ElD2jKH;AkDzjKG;EACE,gBAAA;ElD2jKL;AkD5jKG;EAII,gBAAA;ElD2jKP;AkDxjKK;;EAEE,gBAAA;EACA,2BAAA;ElD0jKP;AkDxjKK;;;EAGE,aAAA;EACA,2BAAA;EACA,uBAAA;ElD0jKP;AkD/kKC;EACE,gBAAA;EACA,2BAAA;ElDilKH;AkD/kKG;EACE,gBAAA;ElDilKL;AkDllKG;EAII,gBAAA;ElDilKP;AkD9kKK;;EAEE,gBAAA;EACA,2BAAA;ElDglKP;AkD9kKK;;;EAGE,aAAA;EACA,2BAAA;EACA,uBAAA;ElDglKP;AkDrmKC;EACE,gBAAA;EACA,2BAAA;ElDumKH;AkDrmKG;EACE,gBAAA;ElDumKL;AkDxmKG;EAII,gBAAA;ElDumKP;AkDpmKK;;EAEE,gBAAA;EACA,2BAAA;ElDsmKP;AkDpmKK;;;EAGE,aAAA;EACA,2BAAA;EACA,uBAAA;ElDsmKP;AiD1gKD;EACE,eAAA;EACA,oBAAA;EjD4gKD;AiD1gKD;EACE,kBAAA;EACA,kBAAA;EjD4gKD;AmDhoKD;EACE,qBAAA;EACA,2BAAA;EACA,+BAAA;EACA,oBAAA;E9C0DA,mDAAA;EACQ,2CAAA;ELykKT;AmD/nKD;EACE,eAAA;EnDioKD;AmD5nKD;EACE,oBAAA;EACA,sCAAA;EvBpBA,8BAAA;EACC,6BAAA;E5BmpKF;AmDloKD;EAMI,gBAAA;EnD+nKH;AmD1nKD;EACE,eAAA;EACA,kBAAA;EACA,iBAAA;EACA,gBAAA;EnD4nKD;AmDhoKD;;;;;EAWI,gBAAA;EnD4nKH;AmDvnKD;EACE,oBAAA;EACA,2BAAA;EACA,+BAAA;EvBxCA,iCAAA;EACC,gCAAA;E5BkqKF;AmDjnKD;;EAGI,kBAAA;EnDknKH;AmDrnKD;;EAMM,qBAAA;EACA,kBAAA;EnDmnKL;AmD/mKG;;EAEI,eAAA;EvBvEN,8BAAA;EACC,6BAAA;E5ByrKF;AmD9mKG;;EAEI,kBAAA;EvBtEN,iCAAA;EACC,gCAAA;E5BurKF;AmD3mKD;EAEI,qBAAA;EnD4mKH;AmDzmKD;EACE,qBAAA;EnD2mKD;AmDnmKD;;;EAII,kBAAA;EnDomKH;AmDxmKD;;;EAOM,oBAAA;EACA,qBAAA;EnDsmKL;AmD9mKD;;EvBnGE,8BAAA;EACC,6BAAA;E5BqtKF;AmDnnKD;;;;EAmBQ,6BAAA;EACA,8BAAA;EnDsmKP;AmD1nKD;;;;;;;;EAwBU,6BAAA;EnD4mKT;AmDpoKD;;;;;;;;EA4BU,8BAAA;EnDknKT;AmD9oKD;;EvB3FE,iCAAA;EACC,gCAAA;E5B6uKF;AmDnpKD;;;;EAyCQ,gCAAA;EACA,iCAAA;EnDgnKP;AmD1pKD;;;;;;;;EA8CU,gCAAA;EnDsnKT;AmDpqKD;;;;;;;;EAkDU,iCAAA;EnD4nKT;AmD9qKD;;;;EA2DI,+BAAA;EnDynKH;AmDprKD;;EA+DI,eAAA;EnDynKH;AmDxrKD;;EAmEI,WAAA;EnDynKH;AmD5rKD;;;;;;;;;;;;EA0EU,gBAAA;EnDgoKT;AmD1sKD;;;;;;;;;;;;EA8EU,iBAAA;EnD0oKT;AmDxtKD;;;;;;;;EAuFU,kBAAA;EnD2oKT;AmDluKD;;;;;;;;EAgGU,kBAAA;EnD4oKT;AmD5uKD;EAsGI,WAAA;EACA,kBAAA;EnDyoKH;AmD/nKD;EACE,qBAAA;EnDioKD;AmDloKD;EAKI,kBAAA;EACA,oBAAA;EnDgoKH;AmDtoKD;EASM,iBAAA;EnDgoKL;AmDzoKD;EAcI,kBAAA;EnD8nKH;AmD5oKD;;EAkBM,+BAAA;EnD8nKL;AmDhpKD;EAuBI,eAAA;EnD4nKH;AmDnpKD;EAyBM,kCAAA;EnD6nKL;AmDtnKD;ECpPE,uBAAA;EpD62KD;AoD32KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpD62KH;AoDh3KC;EAMI,2BAAA;EpD62KL;AoDn3KC;EASI,gBAAA;EACA,2BAAA;EpD62KL;AoD12KC;EAEI,8BAAA;EpD22KL;AmDroKD;ECvPE,uBAAA;EpD+3KD;AoD73KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpD+3KH;AoDl4KC;EAMI,2BAAA;EpD+3KL;AoDr4KC;EASI,gBAAA;EACA,2BAAA;EpD+3KL;AoD53KC;EAEI,8BAAA;EpD63KL;AmDppKD;EC1PE,uBAAA;EpDi5KD;AoD/4KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpDi5KH;AoDp5KC;EAMI,2BAAA;EpDi5KL;AoDv5KC;EASI,gBAAA;EACA,2BAAA;EpDi5KL;AoD94KC;EAEI,8BAAA;EpD+4KL;AmDnqKD;EC7PE,uBAAA;EpDm6KD;AoDj6KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpDm6KH;AoDt6KC;EAMI,2BAAA;EpDm6KL;AoDz6KC;EASI,gBAAA;EACA,2BAAA;EpDm6KL;AoDh6KC;EAEI,8BAAA;EpDi6KL;AmDlrKD;EChQE,uBAAA;EpDq7KD;AoDn7KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpDq7KH;AoDx7KC;EAMI,2BAAA;EpDq7KL;AoD37KC;EASI,gBAAA;EACA,2BAAA;EpDq7KL;AoDl7KC;EAEI,8BAAA;EpDm7KL;AmDjsKD;ECnQE,uBAAA;EpDu8KD;AoDr8KC;EACE,gBAAA;EACA,2BAAA;EACA,uBAAA;EpDu8KH;AoD18KC;EAMI,2BAAA;EpDu8KL;AoD78KC;EASI,gBAAA;EACA,2BAAA;EpDu8KL;AoDp8KC;EAEI,8BAAA;EpDq8KL;AqDr9KD;EACE,oBAAA;EACA,gBAAA;EACA,WAAA;EACA,YAAA;EACA,kBAAA;ErDu9KD;AqD59KD;;;;;EAYI,oBAAA;EACA,QAAA;EACA,SAAA;EACA,WAAA;EACA,cAAA;EACA,aAAA;EACA,WAAA;ErDu9KH;AqDn9KC;EACE,wBAAA;ErDq9KH;AqDj9KC;EACE,qBAAA;ErDm9KH;AsD7+KD;EACE,kBAAA;EACA,eAAA;EACA,qBAAA;EACA,2BAAA;EACA,2BAAA;EACA,oBAAA;EjDwDA,yDAAA;EACQ,iDAAA;ELw7KT;AsDv/KD;EASI,oBAAA;EACA,mCAAA;EtDi/KH;AsD5+KD;EACE,eAAA;EACA,oBAAA;EtD8+KD;AsD5+KD;EACE,cAAA;EACA,oBAAA;EtD8+KD;AuDpgLD;EACE,cAAA;EACA,iBAAA;EACA,mBAAA;EACA,gBAAA;EACA,gBAAA;EACA,8BAAA;EjCRA,cAAA;EAGA,2BAAA;EtB6gLD;AuDrgLC;;EAEE,gBAAA;EACA,uBAAA;EACA,iBAAA;EjCfF,cAAA;EAGA,2BAAA;EtBqhLD;AuDjgLC;EACE,YAAA;EACA,iBAAA;EACA,yBAAA;EACA,WAAA;EACA,0BAAA;EvDmgLH;AwDxhLD;EACE,kBAAA;ExD0hLD;AwDthLD;EACE,eAAA;EACA,kBAAA;EACA,iBAAA;EACA,QAAA;EACA,UAAA;EACA,WAAA;EACA,SAAA;EACA,eAAA;EACA,mCAAA;EAIA,YAAA;ExDqhLD;AwDlhLC;EnD+GA,uCAAA;EACI,mCAAA;EACC,kCAAA;EACG,+BAAA;EAkER,qDAAA;EAEK,2CAAA;EACG,qCAAA;ELq2KT;AwDxhLC;EnD2GA,oCAAA;EACI,gCAAA;EACC,+BAAA;EACG,4BAAA;ELg7KT;AwD5hLD;EACE,oBAAA;EACA,kBAAA;ExD8hLD;AwD1hLD;EACE,oBAAA;EACA,aAAA;EACA,cAAA;ExD4hLD;AwDxhLD;EACE,oBAAA;EACA,2BAAA;EACA,2BAAA;EACA,sCAAA;EACA,oBAAA;EnDaA,kDAAA;EACQ,0CAAA;EmDZR,sCAAA;UAAA,8BAAA;EAEA,YAAA;ExD0hLD;AwDthLD;EACE,oBAAA;EACA,QAAA;EACA,UAAA;EACA,SAAA;EACA,2BAAA;ExDwhLD;AwDthLC;ElCnEA,YAAA;EAGA,0BAAA;EtB0lLD;AwDzhLC;ElCpEA,cAAA;EAGA,2BAAA;EtB8lLD;AwDxhLD;EACE,eAAA;EACA,kCAAA;EACA,2BAAA;ExD0hLD;AwDvhLD;EACE,kBAAA;ExDyhLD;AwDrhLD;EACE,WAAA;EACA,yBAAA;ExDuhLD;AwDlhLD;EACE,oBAAA;EACA,eAAA;ExDohLD;AwDhhLD;EACE,eAAA;EACA,mBAAA;EACA,+BAAA;ExDkhLD;AwDrhLD;EAQI,kBAAA;EACA,kBAAA;ExDghLH;AwDzhLD;EAaI,mBAAA;ExD+gLH;AwD5hLD;EAiBI,gBAAA;ExD8gLH;AwDzgLD;EACE,oBAAA;EACA,cAAA;EACA,aAAA;EACA,cAAA;EACA,kBAAA;ExD2gLD;AwDz/KD;EAZE;IACE,cAAA;IACA,mBAAA;IxDwgLD;EwDtgLD;InDrEA,mDAAA;IACQ,2CAAA;IL8kLP;EwDrgLD;IAAY,cAAA;IxDwgLX;EACF;AwDngLD;EAFE;IAAY,cAAA;IxDygLX;EACF;AyDtpLD;EACE,oBAAA;EACA,eAAA;EACA,gBAAA;EACA,qBAAA;EAEA,6DAAA;EACA,iBAAA;EACA,qBAAA;EACA,kBAAA;EnCZA,YAAA;EAGA,0BAAA;EtBkqLD;AyDtpLC;EnCfA,cAAA;EAGA,2BAAA;EtBsqLD;AyDzpLC;EAAW,kBAAA;EAAmB,gBAAA;EzD6pL/B;AyD5pLC;EAAW,kBAAA;EAAmB,gBAAA;EzDgqL/B;AyD/pLC;EAAW,iBAAA;EAAmB,gBAAA;EzDmqL/B;AyDlqLC;EAAW,mBAAA;EAAmB,gBAAA;EzDsqL/B;AyDlqLD;EACE,kBAAA;EACA,kBAAA;EACA,gBAAA;EACA,oBAAA;EACA,uBAAA;EACA,2BAAA;EACA,oBAAA;EzDoqLD;AyDhqLD;EACE,oBAAA;EACA,UAAA;EACA,WAAA;EACA,2BAAA;EACA,qBAAA;EzDkqLD;AyD9pLC;EACE,WAAA;EACA,WAAA;EACA,mBAAA;EACA,yBAAA;EACA,2BAAA;EzDgqLH;AyD9pLC;EACE,WAAA;EACA,YAAA;EACA,qBAAA;EACA,yBAAA;EACA,2BAAA;EzDgqLH;AyD9pLC;EACE,WAAA;EACA,WAAA;EACA,qBAAA;EACA,yBAAA;EACA,2BAAA;EzDgqLH;AyD9pLC;EACE,UAAA;EACA,SAAA;EACA,kBAAA;EACA,6BAAA;EACA,6BAAA;EzDgqLH;AyD9pLC;EACE,UAAA;EACA,UAAA;EACA,kBAAA;EACA,6BAAA;EACA,4BAAA;EzDgqLH;AyD9pLC;EACE,QAAA;EACA,WAAA;EACA,mBAAA;EACA,yBAAA;EACA,8BAAA;EzDgqLH;AyD9pLC;EACE,QAAA;EACA,YAAA;EACA,kBAAA;EACA,yBAAA;EACA,8BAAA;EzDgqLH;AyD9pLC;EACE,QAAA;EACA,WAAA;EACA,kBAAA;EACA,yBAAA;EACA,8BAAA;EzDgqLH;A0D/vLD;EACE,oBAAA;EACA,QAAA;EACA,SAAA;EACA,eAAA;EACA,eAAA;EACA,kBAAA;EACA,cAAA;EAEA,6DAAA;EACA,iBAAA;EACA,qBAAA;EACA,yBAAA;EACA,kBAAA;EACA,2BAAA;EACA,sCAAA;UAAA,8BAAA;EACA,2BAAA;EACA,sCAAA;EACA,oBAAA;ErD6CA,mDAAA;EACQ,2CAAA;EqD1CR,qBAAA;E1D+vLD;A0D5vLC;EAAY,mBAAA;E1D+vLb;A0D9vLC;EAAY,mBAAA;E1DiwLb;A0DhwLC;EAAY,kBAAA;E1DmwLb;A0DlwLC;EAAY,oBAAA;E1DqwLb;A0DlwLD;EACE,WAAA;EACA,mBAAA;EACA,iBAAA;EACA,2BAAA;EACA,kCAAA;EACA,4BAAA;E1DowLD;A0DjwLD;EACE,mBAAA;E1DmwLD;A0D3vLC;;EAEE,oBAAA;EACA,gBAAA;EACA,UAAA;EACA,WAAA;EACA,2BAAA;EACA,qBAAA;E1D6vLH;A0D1vLD;EACE,oBAAA;E1D4vLD;A0D1vLD;EACE,oBAAA;EACA,aAAA;E1D4vLD;A0DxvLC;EACE,WAAA;EACA,oBAAA;EACA,wBAAA;EACA,2BAAA;EACA,uCAAA;EACA,eAAA;E1D0vLH;A0DzvLG;EACE,cAAA;EACA,aAAA;EACA,oBAAA;EACA,wBAAA;EACA,2BAAA;E1D2vLL;A0DxvLC;EACE,UAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,6BAAA;EACA,yCAAA;E1D0vLH;A0DzvLG;EACE,cAAA;EACA,WAAA;EACA,eAAA;EACA,sBAAA;EACA,6BAAA;E1D2vLL;A0DxvLC;EACE,WAAA;EACA,oBAAA;EACA,qBAAA;EACA,8BAAA;EACA,0CAAA;EACA,YAAA;E1D0vLH;A0DzvLG;EACE,cAAA;EACA,UAAA;EACA,oBAAA;EACA,qBAAA;EACA,8BAAA;E1D2vLL;A0DvvLC;EACE,UAAA;EACA,cAAA;EACA,mBAAA;EACA,uBAAA;EACA,4BAAA;EACA,wCAAA;E1DyvLH;A0DxvLG;EACE,cAAA;EACA,YAAA;EACA,uBAAA;EACA,4BAAA;EACA,eAAA;E1D0vLL;A2Dv3LD;EACE,oBAAA;E3Dy3LD;A2Dt3LD;EACE,oBAAA;EACA,kBAAA;EACA,aAAA;E3Dw3LD;A2D33LD;EAMI,eAAA;EACA,oBAAA;EtD6KF,2CAAA;EACK,sCAAA;EACG,mCAAA;EL4sLT;A2Dl4LD;;EAcM,gBAAA;E3Dw3LL;A2D91LC;EAAA;ItDiKA,wDAAA;IAEK,8CAAA;IACG,wCAAA;IA7JR,qCAAA;IAEQ,6BAAA;IA+GR,2BAAA;IAEQ,mBAAA;ILivLP;E2D53LG;;ItDmHJ,4CAAA;IACQ,oCAAA;IsDjHF,SAAA;I3D+3LL;E2D73LG;;ItD8GJ,6CAAA;IACQ,qCAAA;IsD5GF,SAAA;I3Dg4LL;E2D93LG;;;ItDyGJ,yCAAA;IACQ,iCAAA;IsDtGF,SAAA;I3Di4LL;EACF;A2Dv6LD;;;EA6CI,gBAAA;E3D+3LH;A2D56LD;EAiDI,SAAA;E3D83LH;A2D/6LD;;EAsDI,oBAAA;EACA,QAAA;EACA,aAAA;E3D63LH;A2Dr7LD;EA4DI,YAAA;E3D43LH;A2Dx7LD;EA+DI,aAAA;E3D43LH;A2D37LD;;EAmEI,SAAA;E3D43LH;A2D/7LD;EAuEI,aAAA;E3D23LH;A2Dl8LD;EA0EI,YAAA;E3D23LH;A2Dn3LD;EACE,oBAAA;EACA,QAAA;EACA,SAAA;EACA,WAAA;EACA,YAAA;ErC9FA,cAAA;EAGA,2BAAA;EqC6FA,iBAAA;EACA,gBAAA;EACA,oBAAA;EACA,2CAAA;E3Ds3LD;A2Dj3LC;EblGE,oGAAA;EACA,+FAAA;EACA,sHAAA;EAAA,gGAAA;EACA,6BAAA;EACA,wHAAA;E9Cs9LH;A2Dr3LC;EACE,YAAA;EACA,UAAA;EbvGA,oGAAA;EACA,+FAAA;EACA,sHAAA;EAAA,gGAAA;EACA,6BAAA;EACA,wHAAA;E9C+9LH;A2Dv3LC;;EAEE,YAAA;EACA,gBAAA;EACA,uBAAA;ErCtHF,cAAA;EAGA,2BAAA;EtB8+LD;A2Dx5LD;;;;EAsCI,oBAAA;EACA,UAAA;EACA,YAAA;EACA,uBAAA;E3Dw3LH;A2Dj6LD;;EA6CI,WAAA;EACA,oBAAA;E3Dw3LH;A2Dt6LD;;EAkDI,YAAA;EACA,qBAAA;E3Dw3LH;A2D36LD;;EAuDI,aAAA;EACA,cAAA;EACA,mBAAA;EACA,gBAAA;EACA,oBAAA;E3Dw3LH;A2Dn3LG;EACE,kBAAA;E3Dq3LL;A2Dj3LG;EACE,kBAAA;E3Dm3LL;A2Dz2LD;EACE,oBAAA;EACA,cAAA;EACA,WAAA;EACA,aAAA;EACA,YAAA;EACA,mBAAA;EACA,iBAAA;EACA,kBAAA;EACA,oBAAA;E3D22LD;A2Dp3LD;EAYI,uBAAA;EACA,aAAA;EACA,cAAA;EACA,aAAA;EACA,qBAAA;EACA,2BAAA;EACA,qBAAA;EACA,iBAAA;EAWA,2BAAA;EACA,oCAAA;E3Di2LH;A2Dh4LD;EAkCI,WAAA;EACA,aAAA;EACA,cAAA;EACA,2BAAA;E3Di2LH;A2D11LD;EACE,oBAAA;EACA,WAAA;EACA,YAAA;EACA,cAAA;EACA,aAAA;EACA,mBAAA;EACA,sBAAA;EACA,gBAAA;EACA,oBAAA;EACA,2CAAA;E3D41LD;A2D31LC;EACE,mBAAA;E3D61LH;A2DpzLD;EAhCE;;;;IAKI,aAAA;IACA,cAAA;IACA,mBAAA;IACA,iBAAA;I3Ds1LH;E2D91LD;;IAYI,oBAAA;I3Ds1LH;E2Dl2LD;;IAgBI,qBAAA;I3Ds1LH;E2Dj1LD;IACE,WAAA;IACA,YAAA;IACA,sBAAA;I3Dm1LD;E2D/0LD;IACE,cAAA;I3Di1LD;EACF;A4D/kMC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAEE,cAAA;EACA,gBAAA;E5D6mMH;A4D3mMC;;;;;;;;;;;;;;;EACE,aAAA;E5D2nMH;AiCnoMD;E4BRE,gBAAA;EACA,mBAAA;EACA,oBAAA;E7D8oMD;AiCroMD;EACE,yBAAA;EjCuoMD;AiCroMD;EACE,wBAAA;EjCuoMD;AiC/nMD;EACE,0BAAA;EjCioMD;AiC/nMD;EACE,2BAAA;EjCioMD;AiC/nMD;EACE,oBAAA;EjCioMD;AiC/nMD;E6BzBE,aAAA;EACA,oBAAA;EACA,mBAAA;EACA,+BAAA;EACA,WAAA;E9D2pMD;AiC7nMD;EACE,0BAAA;EACA,+BAAA;EjC+nMD;AiCxnMD;EACE,iBAAA;EjC0nMD;A+D5pMD;EACE,qBAAA;E/D8pMD;A+DxpMD;;;;ECdE,0BAAA;EhE4qMD;A+DvpMD;;;;;;;;;;;;EAYE,0BAAA;E/DypMD;A+DlpMD;EAAA;IChDE,2BAAA;IhEssMC;EgErsMD;IAAU,gBAAA;IhEwsMT;EgEvsMD;IAAU,+BAAA;IhE0sMT;EgEzsMD;;IACU,gCAAA;IhE4sMT;EACF;A+D5pMD;EAAA;IAFI,2BAAA;I/DkqMD;EACF;A+D5pMD;EAAA;IAFI,4BAAA;I/DkqMD;EACF;A+D5pMD;EAAA;IAFI,kCAAA;I/DkqMD;EACF;A+D3pMD;EAAA;ICrEE,2BAAA;IhEouMC;EgEnuMD;IAAU,gBAAA;IhEsuMT;EgEruMD;IAAU,+BAAA;IhEwuMT;EgEvuMD;;IACU,gCAAA;IhE0uMT;EACF;A+DrqMD;EAAA;IAFI,2BAAA;I/D2qMD;EACF;A+DrqMD;EAAA;IAFI,4BAAA;I/D2qMD;EACF;A+DrqMD;EAAA;IAFI,kCAAA;I/D2qMD;EACF;A+DpqMD;EAAA;IC1FE,2BAAA;IhEkwMC;EgEjwMD;IAAU,gBAAA;IhEowMT;EgEnwMD;IAAU,+BAAA;IhEswMT;EgErwMD;;IACU,gCAAA;IhEwwMT;EACF;A+D9qMD;EAAA;IAFI,2BAAA;I/DorMD;EACF;A+D9qMD;EAAA;IAFI,4BAAA;I/DorMD;EACF;A+D9qMD;EAAA;IAFI,kCAAA;I/DorMD;EACF;A+D7qMD;EAAA;IC/GE,2BAAA;IhEgyMC;EgE/xMD;IAAU,gBAAA;IhEkyMT;EgEjyMD;IAAU,+BAAA;IhEoyMT;EgEnyMD;;IACU,gCAAA;IhEsyMT;EACF;A+DvrMD;EAAA;IAFI,2BAAA;I/D6rMD;EACF;A+DvrMD;EAAA;IAFI,4BAAA;I/D6rMD;EACF;A+DvrMD;EAAA;IAFI,kCAAA;I/D6rMD;EACF;A+DtrMD;EAAA;IC5HE,0BAAA;IhEszMC;EACF;A+DtrMD;EAAA;ICjIE,0BAAA;IhE2zMC;EACF;A+DtrMD;EAAA;ICtIE,0BAAA;IhEg0MC;EACF;A+DtrMD;EAAA;IC3IE,0BAAA;IhEq0MC;EACF;A+DnrMD;ECnJE,0BAAA;EhEy0MD;A+DhrMD;EAAA;ICjKE,2BAAA;IhEq1MC;EgEp1MD;IAAU,gBAAA;IhEu1MT;EgEt1MD;IAAU,+BAAA;IhEy1MT;EgEx1MD;;IACU,gCAAA;IhE21MT;EACF;A+D9rMD;EACE,0BAAA;E/DgsMD;A+D3rMD;EAAA;IAFI,2BAAA;I/DisMD;EACF;A+D/rMD;EACE,0BAAA;E/DisMD;A+D5rMD;EAAA;IAFI,4BAAA;I/DksMD;EACF;A+DhsMD;EACE,0BAAA;E/DksMD;A+D7rMD;EAAA;IAFI,kCAAA;I/DmsMD;EACF;A+D5rMD;EAAA;ICpLE,0BAAA;IhEo3MC;EACF","file":"bootstrap.css","sourcesContent":["/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\nhtml {\n font-family: sans-serif;\n -ms-text-size-adjust: 100%;\n -webkit-text-size-adjust: 100%;\n}\nbody {\n margin: 0;\n}\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmain,\nmenu,\nnav,\nsection,\nsummary {\n display: block;\n}\naudio,\ncanvas,\nprogress,\nvideo {\n display: inline-block;\n vertical-align: baseline;\n}\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n[hidden],\ntemplate {\n display: none;\n}\na {\n background-color: transparent;\n}\na:active,\na:hover {\n outline: 0;\n}\nabbr[title] {\n border-bottom: 1px dotted;\n}\nb,\nstrong {\n font-weight: bold;\n}\ndfn {\n font-style: italic;\n}\nh1 {\n font-size: 2em;\n margin: 0.67em 0;\n}\nmark {\n background: #ff0;\n color: #000;\n}\nsmall {\n font-size: 80%;\n}\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsup {\n top: -0.5em;\n}\nsub {\n bottom: -0.25em;\n}\nimg {\n border: 0;\n}\nsvg:not(:root) {\n overflow: hidden;\n}\nfigure {\n margin: 1em 40px;\n}\nhr {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n height: 0;\n}\npre {\n overflow: auto;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, monospace;\n font-size: 1em;\n}\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n color: inherit;\n font: inherit;\n margin: 0;\n}\nbutton {\n overflow: visible;\n}\nbutton,\nselect {\n text-transform: none;\n}\nbutton,\nhtml input[type=\"button\"],\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button;\n cursor: pointer;\n}\nbutton[disabled],\nhtml input[disabled] {\n cursor: default;\n}\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\ninput {\n line-height: normal;\n}\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box;\n padding: 0;\n}\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n height: auto;\n}\ninput[type=\"search\"] {\n -webkit-appearance: textfield;\n -moz-box-sizing: content-box;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n}\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\nlegend {\n border: 0;\n padding: 0;\n}\ntextarea {\n overflow: auto;\n}\noptgroup {\n font-weight: bold;\n}\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\ntd,\nth {\n padding: 0;\n}\n/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */\n@media print {\n *,\n *:before,\n *:after {\n background: transparent !important;\n color: #000 !important;\n box-shadow: none !important;\n text-shadow: none !important;\n }\n a,\n a:visited {\n text-decoration: underline;\n }\n a[href]:after {\n content: \" (\" attr(href) \")\";\n }\n abbr[title]:after {\n content: \" (\" attr(title) \")\";\n }\n a[href^=\"#\"]:after,\n a[href^=\"javascript:\"]:after {\n content: \"\";\n }\n pre,\n blockquote {\n border: 1px solid #999;\n page-break-inside: avoid;\n }\n thead {\n display: table-header-group;\n }\n tr,\n img {\n page-break-inside: avoid;\n }\n img {\n max-width: 100% !important;\n }\n p,\n h2,\n h3 {\n orphans: 3;\n widows: 3;\n }\n h2,\n h3 {\n page-break-after: avoid;\n }\n select {\n background: #fff !important;\n }\n .navbar {\n display: none;\n }\n .btn > .caret,\n .dropup > .btn > .caret {\n border-top-color: #000 !important;\n }\n .label {\n border: 1px solid #000;\n }\n .table {\n border-collapse: collapse !important;\n }\n .table td,\n .table th {\n background-color: #fff !important;\n }\n .table-bordered th,\n .table-bordered td {\n border: 1px solid #ddd !important;\n }\n}\n@font-face {\n font-family: 'Glyphicons Halflings';\n src: url('../fonts/glyphicons-halflings-regular.eot');\n src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');\n}\n.glyphicon {\n position: relative;\n top: 1px;\n display: inline-block;\n font-family: 'Glyphicons Halflings';\n font-style: normal;\n font-weight: normal;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.glyphicon-asterisk:before {\n content: \"\\2a\";\n}\n.glyphicon-plus:before {\n content: \"\\2b\";\n}\n.glyphicon-euro:before,\n.glyphicon-eur:before {\n content: \"\\20ac\";\n}\n.glyphicon-minus:before {\n content: \"\\2212\";\n}\n.glyphicon-cloud:before {\n content: \"\\2601\";\n}\n.glyphicon-envelope:before {\n content: \"\\2709\";\n}\n.glyphicon-pencil:before {\n content: \"\\270f\";\n}\n.glyphicon-glass:before {\n content: \"\\e001\";\n}\n.glyphicon-music:before {\n content: \"\\e002\";\n}\n.glyphicon-search:before {\n content: \"\\e003\";\n}\n.glyphicon-heart:before {\n content: \"\\e005\";\n}\n.glyphicon-star:before {\n content: \"\\e006\";\n}\n.glyphicon-star-empty:before {\n content: \"\\e007\";\n}\n.glyphicon-user:before {\n content: \"\\e008\";\n}\n.glyphicon-film:before {\n content: \"\\e009\";\n}\n.glyphicon-th-large:before {\n content: \"\\e010\";\n}\n.glyphicon-th:before {\n content: \"\\e011\";\n}\n.glyphicon-th-list:before {\n content: \"\\e012\";\n}\n.glyphicon-ok:before {\n content: \"\\e013\";\n}\n.glyphicon-remove:before {\n content: \"\\e014\";\n}\n.glyphicon-zoom-in:before {\n content: \"\\e015\";\n}\n.glyphicon-zoom-out:before {\n content: \"\\e016\";\n}\n.glyphicon-off:before {\n content: \"\\e017\";\n}\n.glyphicon-signal:before {\n content: \"\\e018\";\n}\n.glyphicon-cog:before {\n content: \"\\e019\";\n}\n.glyphicon-trash:before {\n content: \"\\e020\";\n}\n.glyphicon-home:before {\n content: \"\\e021\";\n}\n.glyphicon-file:before {\n content: \"\\e022\";\n}\n.glyphicon-time:before {\n content: \"\\e023\";\n}\n.glyphicon-road:before {\n content: \"\\e024\";\n}\n.glyphicon-download-alt:before {\n content: \"\\e025\";\n}\n.glyphicon-download:before {\n content: \"\\e026\";\n}\n.glyphicon-upload:before {\n content: \"\\e027\";\n}\n.glyphicon-inbox:before {\n content: \"\\e028\";\n}\n.glyphicon-play-circle:before {\n content: \"\\e029\";\n}\n.glyphicon-repeat:before {\n content: \"\\e030\";\n}\n.glyphicon-refresh:before {\n content: \"\\e031\";\n}\n.glyphicon-list-alt:before {\n content: \"\\e032\";\n}\n.glyphicon-lock:before {\n content: \"\\e033\";\n}\n.glyphicon-flag:before {\n content: \"\\e034\";\n}\n.glyphicon-headphones:before {\n content: \"\\e035\";\n}\n.glyphicon-volume-off:before {\n content: \"\\e036\";\n}\n.glyphicon-volume-down:before {\n content: \"\\e037\";\n}\n.glyphicon-volume-up:before {\n content: \"\\e038\";\n}\n.glyphicon-qrcode:before {\n content: \"\\e039\";\n}\n.glyphicon-barcode:before {\n content: \"\\e040\";\n}\n.glyphicon-tag:before {\n content: \"\\e041\";\n}\n.glyphicon-tags:before {\n content: \"\\e042\";\n}\n.glyphicon-book:before {\n content: \"\\e043\";\n}\n.glyphicon-bookmark:before {\n content: \"\\e044\";\n}\n.glyphicon-print:before {\n content: \"\\e045\";\n}\n.glyphicon-camera:before {\n content: \"\\e046\";\n}\n.glyphicon-font:before {\n content: \"\\e047\";\n}\n.glyphicon-bold:before {\n content: \"\\e048\";\n}\n.glyphicon-italic:before {\n content: \"\\e049\";\n}\n.glyphicon-text-height:before {\n content: \"\\e050\";\n}\n.glyphicon-text-width:before {\n content: \"\\e051\";\n}\n.glyphicon-align-left:before {\n content: \"\\e052\";\n}\n.glyphicon-align-center:before {\n content: \"\\e053\";\n}\n.glyphicon-align-right:before {\n content: \"\\e054\";\n}\n.glyphicon-align-justify:before {\n content: \"\\e055\";\n}\n.glyphicon-list:before {\n content: \"\\e056\";\n}\n.glyphicon-indent-left:before {\n content: \"\\e057\";\n}\n.glyphicon-indent-right:before {\n content: \"\\e058\";\n}\n.glyphicon-facetime-video:before {\n content: \"\\e059\";\n}\n.glyphicon-picture:before {\n content: \"\\e060\";\n}\n.glyphicon-map-marker:before {\n content: \"\\e062\";\n}\n.glyphicon-adjust:before {\n content: \"\\e063\";\n}\n.glyphicon-tint:before {\n content: \"\\e064\";\n}\n.glyphicon-edit:before {\n content: \"\\e065\";\n}\n.glyphicon-share:before {\n content: \"\\e066\";\n}\n.glyphicon-check:before {\n content: \"\\e067\";\n}\n.glyphicon-move:before {\n content: \"\\e068\";\n}\n.glyphicon-step-backward:before {\n content: \"\\e069\";\n}\n.glyphicon-fast-backward:before {\n content: \"\\e070\";\n}\n.glyphicon-backward:before {\n content: \"\\e071\";\n}\n.glyphicon-play:before {\n content: \"\\e072\";\n}\n.glyphicon-pause:before {\n content: \"\\e073\";\n}\n.glyphicon-stop:before {\n content: \"\\e074\";\n}\n.glyphicon-forward:before {\n content: \"\\e075\";\n}\n.glyphicon-fast-forward:before {\n content: \"\\e076\";\n}\n.glyphicon-step-forward:before {\n content: \"\\e077\";\n}\n.glyphicon-eject:before {\n content: \"\\e078\";\n}\n.glyphicon-chevron-left:before {\n content: \"\\e079\";\n}\n.glyphicon-chevron-right:before {\n content: \"\\e080\";\n}\n.glyphicon-plus-sign:before {\n content: \"\\e081\";\n}\n.glyphicon-minus-sign:before {\n content: \"\\e082\";\n}\n.glyphicon-remove-sign:before {\n content: \"\\e083\";\n}\n.glyphicon-ok-sign:before {\n content: \"\\e084\";\n}\n.glyphicon-question-sign:before {\n content: \"\\e085\";\n}\n.glyphicon-info-sign:before {\n content: \"\\e086\";\n}\n.glyphicon-screenshot:before {\n content: \"\\e087\";\n}\n.glyphicon-remove-circle:before {\n content: \"\\e088\";\n}\n.glyphicon-ok-circle:before {\n content: \"\\e089\";\n}\n.glyphicon-ban-circle:before {\n content: \"\\e090\";\n}\n.glyphicon-arrow-left:before {\n content: \"\\e091\";\n}\n.glyphicon-arrow-right:before {\n content: \"\\e092\";\n}\n.glyphicon-arrow-up:before {\n content: \"\\e093\";\n}\n.glyphicon-arrow-down:before {\n content: \"\\e094\";\n}\n.glyphicon-share-alt:before {\n content: \"\\e095\";\n}\n.glyphicon-resize-full:before {\n content: \"\\e096\";\n}\n.glyphicon-resize-small:before {\n content: \"\\e097\";\n}\n.glyphicon-exclamation-sign:before {\n content: \"\\e101\";\n}\n.glyphicon-gift:before {\n content: \"\\e102\";\n}\n.glyphicon-leaf:before {\n content: \"\\e103\";\n}\n.glyphicon-fire:before {\n content: \"\\e104\";\n}\n.glyphicon-eye-open:before {\n content: \"\\e105\";\n}\n.glyphicon-eye-close:before {\n content: \"\\e106\";\n}\n.glyphicon-warning-sign:before {\n content: \"\\e107\";\n}\n.glyphicon-plane:before {\n content: \"\\e108\";\n}\n.glyphicon-calendar:before {\n content: \"\\e109\";\n}\n.glyphicon-random:before {\n content: \"\\e110\";\n}\n.glyphicon-comment:before {\n content: \"\\e111\";\n}\n.glyphicon-magnet:before {\n content: \"\\e112\";\n}\n.glyphicon-chevron-up:before {\n content: \"\\e113\";\n}\n.glyphicon-chevron-down:before {\n content: \"\\e114\";\n}\n.glyphicon-retweet:before {\n content: \"\\e115\";\n}\n.glyphicon-shopping-cart:before {\n content: \"\\e116\";\n}\n.glyphicon-folder-close:before {\n content: \"\\e117\";\n}\n.glyphicon-folder-open:before {\n content: \"\\e118\";\n}\n.glyphicon-resize-vertical:before {\n content: \"\\e119\";\n}\n.glyphicon-resize-horizontal:before {\n content: \"\\e120\";\n}\n.glyphicon-hdd:before {\n content: \"\\e121\";\n}\n.glyphicon-bullhorn:before {\n content: \"\\e122\";\n}\n.glyphicon-bell:before {\n content: \"\\e123\";\n}\n.glyphicon-certificate:before {\n content: \"\\e124\";\n}\n.glyphicon-thumbs-up:before {\n content: \"\\e125\";\n}\n.glyphicon-thumbs-down:before {\n content: \"\\e126\";\n}\n.glyphicon-hand-right:before {\n content: \"\\e127\";\n}\n.glyphicon-hand-left:before {\n content: \"\\e128\";\n}\n.glyphicon-hand-up:before {\n content: \"\\e129\";\n}\n.glyphicon-hand-down:before {\n content: \"\\e130\";\n}\n.glyphicon-circle-arrow-right:before {\n content: \"\\e131\";\n}\n.glyphicon-circle-arrow-left:before {\n content: \"\\e132\";\n}\n.glyphicon-circle-arrow-up:before {\n content: \"\\e133\";\n}\n.glyphicon-circle-arrow-down:before {\n content: \"\\e134\";\n}\n.glyphicon-globe:before {\n content: \"\\e135\";\n}\n.glyphicon-wrench:before {\n content: \"\\e136\";\n}\n.glyphicon-tasks:before {\n content: \"\\e137\";\n}\n.glyphicon-filter:before {\n content: \"\\e138\";\n}\n.glyphicon-briefcase:before {\n content: \"\\e139\";\n}\n.glyphicon-fullscreen:before {\n content: \"\\e140\";\n}\n.glyphicon-dashboard:before {\n content: \"\\e141\";\n}\n.glyphicon-paperclip:before {\n content: \"\\e142\";\n}\n.glyphicon-heart-empty:before {\n content: \"\\e143\";\n}\n.glyphicon-link:before {\n content: \"\\e144\";\n}\n.glyphicon-phone:before {\n content: \"\\e145\";\n}\n.glyphicon-pushpin:before {\n content: \"\\e146\";\n}\n.glyphicon-usd:before {\n content: \"\\e148\";\n}\n.glyphicon-gbp:before {\n content: \"\\e149\";\n}\n.glyphicon-sort:before {\n content: \"\\e150\";\n}\n.glyphicon-sort-by-alphabet:before {\n content: \"\\e151\";\n}\n.glyphicon-sort-by-alphabet-alt:before {\n content: \"\\e152\";\n}\n.glyphicon-sort-by-order:before {\n content: \"\\e153\";\n}\n.glyphicon-sort-by-order-alt:before {\n content: \"\\e154\";\n}\n.glyphicon-sort-by-attributes:before {\n content: \"\\e155\";\n}\n.glyphicon-sort-by-attributes-alt:before {\n content: \"\\e156\";\n}\n.glyphicon-unchecked:before {\n content: \"\\e157\";\n}\n.glyphicon-expand:before {\n content: \"\\e158\";\n}\n.glyphicon-collapse-down:before {\n content: \"\\e159\";\n}\n.glyphicon-collapse-up:before {\n content: \"\\e160\";\n}\n.glyphicon-log-in:before {\n content: \"\\e161\";\n}\n.glyphicon-flash:before {\n content: \"\\e162\";\n}\n.glyphicon-log-out:before {\n content: \"\\e163\";\n}\n.glyphicon-new-window:before {\n content: \"\\e164\";\n}\n.glyphicon-record:before {\n content: \"\\e165\";\n}\n.glyphicon-save:before {\n content: \"\\e166\";\n}\n.glyphicon-open:before {\n content: \"\\e167\";\n}\n.glyphicon-saved:before {\n content: \"\\e168\";\n}\n.glyphicon-import:before {\n content: \"\\e169\";\n}\n.glyphicon-export:before {\n content: \"\\e170\";\n}\n.glyphicon-send:before {\n content: \"\\e171\";\n}\n.glyphicon-floppy-disk:before {\n content: \"\\e172\";\n}\n.glyphicon-floppy-saved:before {\n content: \"\\e173\";\n}\n.glyphicon-floppy-remove:before {\n content: \"\\e174\";\n}\n.glyphicon-floppy-save:before {\n content: \"\\e175\";\n}\n.glyphicon-floppy-open:before {\n content: \"\\e176\";\n}\n.glyphicon-credit-card:before {\n content: \"\\e177\";\n}\n.glyphicon-transfer:before {\n content: \"\\e178\";\n}\n.glyphicon-cutlery:before {\n content: \"\\e179\";\n}\n.glyphicon-header:before {\n content: \"\\e180\";\n}\n.glyphicon-compressed:before {\n content: \"\\e181\";\n}\n.glyphicon-earphone:before {\n content: \"\\e182\";\n}\n.glyphicon-phone-alt:before {\n content: \"\\e183\";\n}\n.glyphicon-tower:before {\n content: \"\\e184\";\n}\n.glyphicon-stats:before {\n content: \"\\e185\";\n}\n.glyphicon-sd-video:before {\n content: \"\\e186\";\n}\n.glyphicon-hd-video:before {\n content: \"\\e187\";\n}\n.glyphicon-subtitles:before {\n content: \"\\e188\";\n}\n.glyphicon-sound-stereo:before {\n content: \"\\e189\";\n}\n.glyphicon-sound-dolby:before {\n content: \"\\e190\";\n}\n.glyphicon-sound-5-1:before {\n content: \"\\e191\";\n}\n.glyphicon-sound-6-1:before {\n content: \"\\e192\";\n}\n.glyphicon-sound-7-1:before {\n content: \"\\e193\";\n}\n.glyphicon-copyright-mark:before {\n content: \"\\e194\";\n}\n.glyphicon-registration-mark:before {\n content: \"\\e195\";\n}\n.glyphicon-cloud-download:before {\n content: \"\\e197\";\n}\n.glyphicon-cloud-upload:before {\n content: \"\\e198\";\n}\n.glyphicon-tree-conifer:before {\n content: \"\\e199\";\n}\n.glyphicon-tree-deciduous:before {\n content: \"\\e200\";\n}\n.glyphicon-cd:before {\n content: \"\\e201\";\n}\n.glyphicon-save-file:before {\n content: \"\\e202\";\n}\n.glyphicon-open-file:before {\n content: \"\\e203\";\n}\n.glyphicon-level-up:before {\n content: \"\\e204\";\n}\n.glyphicon-copy:before {\n content: \"\\e205\";\n}\n.glyphicon-paste:before {\n content: \"\\e206\";\n}\n.glyphicon-alert:before {\n content: \"\\e209\";\n}\n.glyphicon-equalizer:before {\n content: \"\\e210\";\n}\n.glyphicon-king:before {\n content: \"\\e211\";\n}\n.glyphicon-queen:before {\n content: \"\\e212\";\n}\n.glyphicon-pawn:before {\n content: \"\\e213\";\n}\n.glyphicon-bishop:before {\n content: \"\\e214\";\n}\n.glyphicon-knight:before {\n content: \"\\e215\";\n}\n.glyphicon-baby-formula:before {\n content: \"\\e216\";\n}\n.glyphicon-tent:before {\n content: \"\\26fa\";\n}\n.glyphicon-blackboard:before {\n content: \"\\e218\";\n}\n.glyphicon-bed:before {\n content: \"\\e219\";\n}\n.glyphicon-apple:before {\n content: \"\\f8ff\";\n}\n.glyphicon-erase:before {\n content: \"\\e221\";\n}\n.glyphicon-hourglass:before {\n content: \"\\231b\";\n}\n.glyphicon-lamp:before {\n content: \"\\e223\";\n}\n.glyphicon-duplicate:before {\n content: \"\\e224\";\n}\n.glyphicon-piggy-bank:before {\n content: \"\\e225\";\n}\n.glyphicon-scissors:before {\n content: \"\\e226\";\n}\n.glyphicon-bitcoin:before {\n content: \"\\e227\";\n}\n.glyphicon-yen:before {\n content: \"\\00a5\";\n}\n.glyphicon-ruble:before {\n content: \"\\20bd\";\n}\n.glyphicon-scale:before {\n content: \"\\e230\";\n}\n.glyphicon-ice-lolly:before {\n content: \"\\e231\";\n}\n.glyphicon-ice-lolly-tasted:before {\n content: \"\\e232\";\n}\n.glyphicon-education:before {\n content: \"\\e233\";\n}\n.glyphicon-option-horizontal:before {\n content: \"\\e234\";\n}\n.glyphicon-option-vertical:before {\n content: \"\\e235\";\n}\n.glyphicon-menu-hamburger:before {\n content: \"\\e236\";\n}\n.glyphicon-modal-window:before {\n content: \"\\e237\";\n}\n.glyphicon-oil:before {\n content: \"\\e238\";\n}\n.glyphicon-grain:before {\n content: \"\\e239\";\n}\n.glyphicon-sunglasses:before {\n content: \"\\e240\";\n}\n.glyphicon-text-size:before {\n content: \"\\e241\";\n}\n.glyphicon-text-color:before {\n content: \"\\e242\";\n}\n.glyphicon-text-background:before {\n content: \"\\e243\";\n}\n.glyphicon-object-align-top:before {\n content: \"\\e244\";\n}\n.glyphicon-object-align-bottom:before {\n content: \"\\e245\";\n}\n.glyphicon-object-align-horizontal:before {\n content: \"\\e246\";\n}\n.glyphicon-object-align-left:before {\n content: \"\\e247\";\n}\n.glyphicon-object-align-vertical:before {\n content: \"\\e248\";\n}\n.glyphicon-object-align-right:before {\n content: \"\\e249\";\n}\n.glyphicon-triangle-right:before {\n content: \"\\e250\";\n}\n.glyphicon-triangle-left:before {\n content: \"\\e251\";\n}\n.glyphicon-triangle-bottom:before {\n content: \"\\e252\";\n}\n.glyphicon-triangle-top:before {\n content: \"\\e253\";\n}\n.glyphicon-console:before {\n content: \"\\e254\";\n}\n.glyphicon-superscript:before {\n content: \"\\e255\";\n}\n.glyphicon-subscript:before {\n content: \"\\e256\";\n}\n.glyphicon-menu-left:before {\n content: \"\\e257\";\n}\n.glyphicon-menu-right:before {\n content: \"\\e258\";\n}\n.glyphicon-menu-down:before {\n content: \"\\e259\";\n}\n.glyphicon-menu-up:before {\n content: \"\\e260\";\n}\n* {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n*:before,\n*:after {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\nhtml {\n font-size: 10px;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\nbody {\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 14px;\n line-height: 1.42857143;\n color: #333333;\n background-color: #ffffff;\n}\ninput,\nbutton,\nselect,\ntextarea {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n}\na {\n color: #337ab7;\n text-decoration: none;\n}\na:hover,\na:focus {\n color: #23527c;\n text-decoration: underline;\n}\na:focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\nfigure {\n margin: 0;\n}\nimg {\n vertical-align: middle;\n}\n.img-responsive,\n.thumbnail > img,\n.thumbnail a > img,\n.carousel-inner > .item > img,\n.carousel-inner > .item > a > img {\n display: block;\n max-width: 100%;\n height: auto;\n}\n.img-rounded {\n border-radius: 6px;\n}\n.img-thumbnail {\n padding: 4px;\n line-height: 1.42857143;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 4px;\n -webkit-transition: all 0.2s ease-in-out;\n -o-transition: all 0.2s ease-in-out;\n transition: all 0.2s ease-in-out;\n display: inline-block;\n max-width: 100%;\n height: auto;\n}\n.img-circle {\n border-radius: 50%;\n}\nhr {\n margin-top: 20px;\n margin-bottom: 20px;\n border: 0;\n border-top: 1px solid #eeeeee;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n border: 0;\n}\n.sr-only-focusable:active,\n.sr-only-focusable:focus {\n position: static;\n width: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n clip: auto;\n}\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n.h1,\n.h2,\n.h3,\n.h4,\n.h5,\n.h6 {\n font-family: inherit;\n font-weight: 500;\n line-height: 1.1;\n color: inherit;\n}\nh1 small,\nh2 small,\nh3 small,\nh4 small,\nh5 small,\nh6 small,\n.h1 small,\n.h2 small,\n.h3 small,\n.h4 small,\n.h5 small,\n.h6 small,\nh1 .small,\nh2 .small,\nh3 .small,\nh4 .small,\nh5 .small,\nh6 .small,\n.h1 .small,\n.h2 .small,\n.h3 .small,\n.h4 .small,\n.h5 .small,\n.h6 .small {\n font-weight: normal;\n line-height: 1;\n color: #777777;\n}\nh1,\n.h1,\nh2,\n.h2,\nh3,\n.h3 {\n margin-top: 20px;\n margin-bottom: 10px;\n}\nh1 small,\n.h1 small,\nh2 small,\n.h2 small,\nh3 small,\n.h3 small,\nh1 .small,\n.h1 .small,\nh2 .small,\n.h2 .small,\nh3 .small,\n.h3 .small {\n font-size: 65%;\n}\nh4,\n.h4,\nh5,\n.h5,\nh6,\n.h6 {\n margin-top: 10px;\n margin-bottom: 10px;\n}\nh4 small,\n.h4 small,\nh5 small,\n.h5 small,\nh6 small,\n.h6 small,\nh4 .small,\n.h4 .small,\nh5 .small,\n.h5 .small,\nh6 .small,\n.h6 .small {\n font-size: 75%;\n}\nh1,\n.h1 {\n font-size: 36px;\n}\nh2,\n.h2 {\n font-size: 30px;\n}\nh3,\n.h3 {\n font-size: 24px;\n}\nh4,\n.h4 {\n font-size: 18px;\n}\nh5,\n.h5 {\n font-size: 14px;\n}\nh6,\n.h6 {\n font-size: 12px;\n}\np {\n margin: 0 0 10px;\n}\n.lead {\n margin-bottom: 20px;\n font-size: 16px;\n font-weight: 300;\n line-height: 1.4;\n}\n@media (min-width: 768px) {\n .lead {\n font-size: 21px;\n }\n}\nsmall,\n.small {\n font-size: 85%;\n}\nmark,\n.mark {\n background-color: #fcf8e3;\n padding: .2em;\n}\n.text-left {\n text-align: left;\n}\n.text-right {\n text-align: right;\n}\n.text-center {\n text-align: center;\n}\n.text-justify {\n text-align: justify;\n}\n.text-nowrap {\n white-space: nowrap;\n}\n.text-lowercase {\n text-transform: lowercase;\n}\n.text-uppercase {\n text-transform: uppercase;\n}\n.text-capitalize {\n text-transform: capitalize;\n}\n.text-muted {\n color: #777777;\n}\n.text-primary {\n color: #337ab7;\n}\na.text-primary:hover {\n color: #286090;\n}\n.text-success {\n color: #3c763d;\n}\na.text-success:hover {\n color: #2b542c;\n}\n.text-info {\n color: #31708f;\n}\na.text-info:hover {\n color: #245269;\n}\n.text-warning {\n color: #8a6d3b;\n}\na.text-warning:hover {\n color: #66512c;\n}\n.text-danger {\n color: #a94442;\n}\na.text-danger:hover {\n color: #843534;\n}\n.bg-primary {\n color: #fff;\n background-color: #337ab7;\n}\na.bg-primary:hover {\n background-color: #286090;\n}\n.bg-success {\n background-color: #dff0d8;\n}\na.bg-success:hover {\n background-color: #c1e2b3;\n}\n.bg-info {\n background-color: #d9edf7;\n}\na.bg-info:hover {\n background-color: #afd9ee;\n}\n.bg-warning {\n background-color: #fcf8e3;\n}\na.bg-warning:hover {\n background-color: #f7ecb5;\n}\n.bg-danger {\n background-color: #f2dede;\n}\na.bg-danger:hover {\n background-color: #e4b9b9;\n}\n.page-header {\n padding-bottom: 9px;\n margin: 40px 0 20px;\n border-bottom: 1px solid #eeeeee;\n}\nul,\nol {\n margin-top: 0;\n margin-bottom: 10px;\n}\nul ul,\nol ul,\nul ol,\nol ol {\n margin-bottom: 0;\n}\n.list-unstyled {\n padding-left: 0;\n list-style: none;\n}\n.list-inline {\n padding-left: 0;\n list-style: none;\n margin-left: -5px;\n}\n.list-inline > li {\n display: inline-block;\n padding-left: 5px;\n padding-right: 5px;\n}\ndl {\n margin-top: 0;\n margin-bottom: 20px;\n}\ndt,\ndd {\n line-height: 1.42857143;\n}\ndt {\n font-weight: bold;\n}\ndd {\n margin-left: 0;\n}\n@media (min-width: 768px) {\n .dl-horizontal dt {\n float: left;\n width: 160px;\n clear: left;\n text-align: right;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .dl-horizontal dd {\n margin-left: 180px;\n }\n}\nabbr[title],\nabbr[data-original-title] {\n cursor: help;\n border-bottom: 1px dotted #777777;\n}\n.initialism {\n font-size: 90%;\n text-transform: uppercase;\n}\nblockquote {\n padding: 10px 20px;\n margin: 0 0 20px;\n font-size: 17.5px;\n border-left: 5px solid #eeeeee;\n}\nblockquote p:last-child,\nblockquote ul:last-child,\nblockquote ol:last-child {\n margin-bottom: 0;\n}\nblockquote footer,\nblockquote small,\nblockquote .small {\n display: block;\n font-size: 80%;\n line-height: 1.42857143;\n color: #777777;\n}\nblockquote footer:before,\nblockquote small:before,\nblockquote .small:before {\n content: '\\2014 \\00A0';\n}\n.blockquote-reverse,\nblockquote.pull-right {\n padding-right: 15px;\n padding-left: 0;\n border-right: 5px solid #eeeeee;\n border-left: 0;\n text-align: right;\n}\n.blockquote-reverse footer:before,\nblockquote.pull-right footer:before,\n.blockquote-reverse small:before,\nblockquote.pull-right small:before,\n.blockquote-reverse .small:before,\nblockquote.pull-right .small:before {\n content: '';\n}\n.blockquote-reverse footer:after,\nblockquote.pull-right footer:after,\n.blockquote-reverse small:after,\nblockquote.pull-right small:after,\n.blockquote-reverse .small:after,\nblockquote.pull-right .small:after {\n content: '\\00A0 \\2014';\n}\naddress {\n margin-bottom: 20px;\n font-style: normal;\n line-height: 1.42857143;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: Menlo, Monaco, Consolas, \"Courier New\", monospace;\n}\ncode {\n padding: 2px 4px;\n font-size: 90%;\n color: #c7254e;\n background-color: #f9f2f4;\n border-radius: 4px;\n}\nkbd {\n padding: 2px 4px;\n font-size: 90%;\n color: #ffffff;\n background-color: #333333;\n border-radius: 3px;\n box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);\n}\nkbd kbd {\n padding: 0;\n font-size: 100%;\n font-weight: bold;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 9.5px;\n margin: 0 0 10px;\n font-size: 13px;\n line-height: 1.42857143;\n word-break: break-all;\n word-wrap: break-word;\n color: #333333;\n background-color: #f5f5f5;\n border: 1px solid #cccccc;\n border-radius: 4px;\n}\npre code {\n padding: 0;\n font-size: inherit;\n color: inherit;\n white-space: pre-wrap;\n background-color: transparent;\n border-radius: 0;\n}\n.pre-scrollable {\n max-height: 340px;\n overflow-y: scroll;\n}\n.container {\n margin-right: auto;\n margin-left: auto;\n padding-left: 15px;\n padding-right: 15px;\n}\n@media (min-width: 768px) {\n .container {\n width: 750px;\n }\n}\n@media (min-width: 992px) {\n .container {\n width: 970px;\n }\n}\n@media (min-width: 1200px) {\n .container {\n width: 1170px;\n }\n}\n.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 15px;\n padding-right: 15px;\n}\n.row {\n margin-left: -15px;\n margin-right: -15px;\n}\n.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {\n position: relative;\n min-height: 1px;\n padding-left: 15px;\n padding-right: 15px;\n}\n.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {\n float: left;\n}\n.col-xs-12 {\n width: 100%;\n}\n.col-xs-11 {\n width: 91.66666667%;\n}\n.col-xs-10 {\n width: 83.33333333%;\n}\n.col-xs-9 {\n width: 75%;\n}\n.col-xs-8 {\n width: 66.66666667%;\n}\n.col-xs-7 {\n width: 58.33333333%;\n}\n.col-xs-6 {\n width: 50%;\n}\n.col-xs-5 {\n width: 41.66666667%;\n}\n.col-xs-4 {\n width: 33.33333333%;\n}\n.col-xs-3 {\n width: 25%;\n}\n.col-xs-2 {\n width: 16.66666667%;\n}\n.col-xs-1 {\n width: 8.33333333%;\n}\n.col-xs-pull-12 {\n right: 100%;\n}\n.col-xs-pull-11 {\n right: 91.66666667%;\n}\n.col-xs-pull-10 {\n right: 83.33333333%;\n}\n.col-xs-pull-9 {\n right: 75%;\n}\n.col-xs-pull-8 {\n right: 66.66666667%;\n}\n.col-xs-pull-7 {\n right: 58.33333333%;\n}\n.col-xs-pull-6 {\n right: 50%;\n}\n.col-xs-pull-5 {\n right: 41.66666667%;\n}\n.col-xs-pull-4 {\n right: 33.33333333%;\n}\n.col-xs-pull-3 {\n right: 25%;\n}\n.col-xs-pull-2 {\n right: 16.66666667%;\n}\n.col-xs-pull-1 {\n right: 8.33333333%;\n}\n.col-xs-pull-0 {\n right: auto;\n}\n.col-xs-push-12 {\n left: 100%;\n}\n.col-xs-push-11 {\n left: 91.66666667%;\n}\n.col-xs-push-10 {\n left: 83.33333333%;\n}\n.col-xs-push-9 {\n left: 75%;\n}\n.col-xs-push-8 {\n left: 66.66666667%;\n}\n.col-xs-push-7 {\n left: 58.33333333%;\n}\n.col-xs-push-6 {\n left: 50%;\n}\n.col-xs-push-5 {\n left: 41.66666667%;\n}\n.col-xs-push-4 {\n left: 33.33333333%;\n}\n.col-xs-push-3 {\n left: 25%;\n}\n.col-xs-push-2 {\n left: 16.66666667%;\n}\n.col-xs-push-1 {\n left: 8.33333333%;\n}\n.col-xs-push-0 {\n left: auto;\n}\n.col-xs-offset-12 {\n margin-left: 100%;\n}\n.col-xs-offset-11 {\n margin-left: 91.66666667%;\n}\n.col-xs-offset-10 {\n margin-left: 83.33333333%;\n}\n.col-xs-offset-9 {\n margin-left: 75%;\n}\n.col-xs-offset-8 {\n margin-left: 66.66666667%;\n}\n.col-xs-offset-7 {\n margin-left: 58.33333333%;\n}\n.col-xs-offset-6 {\n margin-left: 50%;\n}\n.col-xs-offset-5 {\n margin-left: 41.66666667%;\n}\n.col-xs-offset-4 {\n margin-left: 33.33333333%;\n}\n.col-xs-offset-3 {\n margin-left: 25%;\n}\n.col-xs-offset-2 {\n margin-left: 16.66666667%;\n}\n.col-xs-offset-1 {\n margin-left: 8.33333333%;\n}\n.col-xs-offset-0 {\n margin-left: 0%;\n}\n@media (min-width: 768px) {\n .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {\n float: left;\n }\n .col-sm-12 {\n width: 100%;\n }\n .col-sm-11 {\n width: 91.66666667%;\n }\n .col-sm-10 {\n width: 83.33333333%;\n }\n .col-sm-9 {\n width: 75%;\n }\n .col-sm-8 {\n width: 66.66666667%;\n }\n .col-sm-7 {\n width: 58.33333333%;\n }\n .col-sm-6 {\n width: 50%;\n }\n .col-sm-5 {\n width: 41.66666667%;\n }\n .col-sm-4 {\n width: 33.33333333%;\n }\n .col-sm-3 {\n width: 25%;\n }\n .col-sm-2 {\n width: 16.66666667%;\n }\n .col-sm-1 {\n width: 8.33333333%;\n }\n .col-sm-pull-12 {\n right: 100%;\n }\n .col-sm-pull-11 {\n right: 91.66666667%;\n }\n .col-sm-pull-10 {\n right: 83.33333333%;\n }\n .col-sm-pull-9 {\n right: 75%;\n }\n .col-sm-pull-8 {\n right: 66.66666667%;\n }\n .col-sm-pull-7 {\n right: 58.33333333%;\n }\n .col-sm-pull-6 {\n right: 50%;\n }\n .col-sm-pull-5 {\n right: 41.66666667%;\n }\n .col-sm-pull-4 {\n right: 33.33333333%;\n }\n .col-sm-pull-3 {\n right: 25%;\n }\n .col-sm-pull-2 {\n right: 16.66666667%;\n }\n .col-sm-pull-1 {\n right: 8.33333333%;\n }\n .col-sm-pull-0 {\n right: auto;\n }\n .col-sm-push-12 {\n left: 100%;\n }\n .col-sm-push-11 {\n left: 91.66666667%;\n }\n .col-sm-push-10 {\n left: 83.33333333%;\n }\n .col-sm-push-9 {\n left: 75%;\n }\n .col-sm-push-8 {\n left: 66.66666667%;\n }\n .col-sm-push-7 {\n left: 58.33333333%;\n }\n .col-sm-push-6 {\n left: 50%;\n }\n .col-sm-push-5 {\n left: 41.66666667%;\n }\n .col-sm-push-4 {\n left: 33.33333333%;\n }\n .col-sm-push-3 {\n left: 25%;\n }\n .col-sm-push-2 {\n left: 16.66666667%;\n }\n .col-sm-push-1 {\n left: 8.33333333%;\n }\n .col-sm-push-0 {\n left: auto;\n }\n .col-sm-offset-12 {\n margin-left: 100%;\n }\n .col-sm-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-sm-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-sm-offset-9 {\n margin-left: 75%;\n }\n .col-sm-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-sm-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-sm-offset-6 {\n margin-left: 50%;\n }\n .col-sm-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-sm-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-sm-offset-3 {\n margin-left: 25%;\n }\n .col-sm-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-sm-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-sm-offset-0 {\n margin-left: 0%;\n }\n}\n@media (min-width: 992px) {\n .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {\n float: left;\n }\n .col-md-12 {\n width: 100%;\n }\n .col-md-11 {\n width: 91.66666667%;\n }\n .col-md-10 {\n width: 83.33333333%;\n }\n .col-md-9 {\n width: 75%;\n }\n .col-md-8 {\n width: 66.66666667%;\n }\n .col-md-7 {\n width: 58.33333333%;\n }\n .col-md-6 {\n width: 50%;\n }\n .col-md-5 {\n width: 41.66666667%;\n }\n .col-md-4 {\n width: 33.33333333%;\n }\n .col-md-3 {\n width: 25%;\n }\n .col-md-2 {\n width: 16.66666667%;\n }\n .col-md-1 {\n width: 8.33333333%;\n }\n .col-md-pull-12 {\n right: 100%;\n }\n .col-md-pull-11 {\n right: 91.66666667%;\n }\n .col-md-pull-10 {\n right: 83.33333333%;\n }\n .col-md-pull-9 {\n right: 75%;\n }\n .col-md-pull-8 {\n right: 66.66666667%;\n }\n .col-md-pull-7 {\n right: 58.33333333%;\n }\n .col-md-pull-6 {\n right: 50%;\n }\n .col-md-pull-5 {\n right: 41.66666667%;\n }\n .col-md-pull-4 {\n right: 33.33333333%;\n }\n .col-md-pull-3 {\n right: 25%;\n }\n .col-md-pull-2 {\n right: 16.66666667%;\n }\n .col-md-pull-1 {\n right: 8.33333333%;\n }\n .col-md-pull-0 {\n right: auto;\n }\n .col-md-push-12 {\n left: 100%;\n }\n .col-md-push-11 {\n left: 91.66666667%;\n }\n .col-md-push-10 {\n left: 83.33333333%;\n }\n .col-md-push-9 {\n left: 75%;\n }\n .col-md-push-8 {\n left: 66.66666667%;\n }\n .col-md-push-7 {\n left: 58.33333333%;\n }\n .col-md-push-6 {\n left: 50%;\n }\n .col-md-push-5 {\n left: 41.66666667%;\n }\n .col-md-push-4 {\n left: 33.33333333%;\n }\n .col-md-push-3 {\n left: 25%;\n }\n .col-md-push-2 {\n left: 16.66666667%;\n }\n .col-md-push-1 {\n left: 8.33333333%;\n }\n .col-md-push-0 {\n left: auto;\n }\n .col-md-offset-12 {\n margin-left: 100%;\n }\n .col-md-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-md-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-md-offset-9 {\n margin-left: 75%;\n }\n .col-md-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-md-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-md-offset-6 {\n margin-left: 50%;\n }\n .col-md-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-md-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-md-offset-3 {\n margin-left: 25%;\n }\n .col-md-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-md-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-md-offset-0 {\n margin-left: 0%;\n }\n}\n@media (min-width: 1200px) {\n .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {\n float: left;\n }\n .col-lg-12 {\n width: 100%;\n }\n .col-lg-11 {\n width: 91.66666667%;\n }\n .col-lg-10 {\n width: 83.33333333%;\n }\n .col-lg-9 {\n width: 75%;\n }\n .col-lg-8 {\n width: 66.66666667%;\n }\n .col-lg-7 {\n width: 58.33333333%;\n }\n .col-lg-6 {\n width: 50%;\n }\n .col-lg-5 {\n width: 41.66666667%;\n }\n .col-lg-4 {\n width: 33.33333333%;\n }\n .col-lg-3 {\n width: 25%;\n }\n .col-lg-2 {\n width: 16.66666667%;\n }\n .col-lg-1 {\n width: 8.33333333%;\n }\n .col-lg-pull-12 {\n right: 100%;\n }\n .col-lg-pull-11 {\n right: 91.66666667%;\n }\n .col-lg-pull-10 {\n right: 83.33333333%;\n }\n .col-lg-pull-9 {\n right: 75%;\n }\n .col-lg-pull-8 {\n right: 66.66666667%;\n }\n .col-lg-pull-7 {\n right: 58.33333333%;\n }\n .col-lg-pull-6 {\n right: 50%;\n }\n .col-lg-pull-5 {\n right: 41.66666667%;\n }\n .col-lg-pull-4 {\n right: 33.33333333%;\n }\n .col-lg-pull-3 {\n right: 25%;\n }\n .col-lg-pull-2 {\n right: 16.66666667%;\n }\n .col-lg-pull-1 {\n right: 8.33333333%;\n }\n .col-lg-pull-0 {\n right: auto;\n }\n .col-lg-push-12 {\n left: 100%;\n }\n .col-lg-push-11 {\n left: 91.66666667%;\n }\n .col-lg-push-10 {\n left: 83.33333333%;\n }\n .col-lg-push-9 {\n left: 75%;\n }\n .col-lg-push-8 {\n left: 66.66666667%;\n }\n .col-lg-push-7 {\n left: 58.33333333%;\n }\n .col-lg-push-6 {\n left: 50%;\n }\n .col-lg-push-5 {\n left: 41.66666667%;\n }\n .col-lg-push-4 {\n left: 33.33333333%;\n }\n .col-lg-push-3 {\n left: 25%;\n }\n .col-lg-push-2 {\n left: 16.66666667%;\n }\n .col-lg-push-1 {\n left: 8.33333333%;\n }\n .col-lg-push-0 {\n left: auto;\n }\n .col-lg-offset-12 {\n margin-left: 100%;\n }\n .col-lg-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-lg-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-lg-offset-9 {\n margin-left: 75%;\n }\n .col-lg-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-lg-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-lg-offset-6 {\n margin-left: 50%;\n }\n .col-lg-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-lg-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-lg-offset-3 {\n margin-left: 25%;\n }\n .col-lg-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-lg-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-lg-offset-0 {\n margin-left: 0%;\n }\n}\ntable {\n background-color: transparent;\n}\ncaption {\n padding-top: 8px;\n padding-bottom: 8px;\n color: #777777;\n text-align: left;\n}\nth {\n text-align: left;\n}\n.table {\n width: 100%;\n max-width: 100%;\n margin-bottom: 20px;\n}\n.table > thead > tr > th,\n.table > tbody > tr > th,\n.table > tfoot > tr > th,\n.table > thead > tr > td,\n.table > tbody > tr > td,\n.table > tfoot > tr > td {\n padding: 8px;\n line-height: 1.42857143;\n vertical-align: top;\n border-top: 1px solid #dddddd;\n}\n.table > thead > tr > th {\n vertical-align: bottom;\n border-bottom: 2px solid #dddddd;\n}\n.table > caption + thead > tr:first-child > th,\n.table > colgroup + thead > tr:first-child > th,\n.table > thead:first-child > tr:first-child > th,\n.table > caption + thead > tr:first-child > td,\n.table > colgroup + thead > tr:first-child > td,\n.table > thead:first-child > tr:first-child > td {\n border-top: 0;\n}\n.table > tbody + tbody {\n border-top: 2px solid #dddddd;\n}\n.table .table {\n background-color: #ffffff;\n}\n.table-condensed > thead > tr > th,\n.table-condensed > tbody > tr > th,\n.table-condensed > tfoot > tr > th,\n.table-condensed > thead > tr > td,\n.table-condensed > tbody > tr > td,\n.table-condensed > tfoot > tr > td {\n padding: 5px;\n}\n.table-bordered {\n border: 1px solid #dddddd;\n}\n.table-bordered > thead > tr > th,\n.table-bordered > tbody > tr > th,\n.table-bordered > tfoot > tr > th,\n.table-bordered > thead > tr > td,\n.table-bordered > tbody > tr > td,\n.table-bordered > tfoot > tr > td {\n border: 1px solid #dddddd;\n}\n.table-bordered > thead > tr > th,\n.table-bordered > thead > tr > td {\n border-bottom-width: 2px;\n}\n.table-striped > tbody > tr:nth-of-type(odd) {\n background-color: #f9f9f9;\n}\n.table-hover > tbody > tr:hover {\n background-color: #f5f5f5;\n}\ntable col[class*=\"col-\"] {\n position: static;\n float: none;\n display: table-column;\n}\ntable td[class*=\"col-\"],\ntable th[class*=\"col-\"] {\n position: static;\n float: none;\n display: table-cell;\n}\n.table > thead > tr > td.active,\n.table > tbody > tr > td.active,\n.table > tfoot > tr > td.active,\n.table > thead > tr > th.active,\n.table > tbody > tr > th.active,\n.table > tfoot > tr > th.active,\n.table > thead > tr.active > td,\n.table > tbody > tr.active > td,\n.table > tfoot > tr.active > td,\n.table > thead > tr.active > th,\n.table > tbody > tr.active > th,\n.table > tfoot > tr.active > th {\n background-color: #f5f5f5;\n}\n.table-hover > tbody > tr > td.active:hover,\n.table-hover > tbody > tr > th.active:hover,\n.table-hover > tbody > tr.active:hover > td,\n.table-hover > tbody > tr:hover > .active,\n.table-hover > tbody > tr.active:hover > th {\n background-color: #e8e8e8;\n}\n.table > thead > tr > td.success,\n.table > tbody > tr > td.success,\n.table > tfoot > tr > td.success,\n.table > thead > tr > th.success,\n.table > tbody > tr > th.success,\n.table > tfoot > tr > th.success,\n.table > thead > tr.success > td,\n.table > tbody > tr.success > td,\n.table > tfoot > tr.success > td,\n.table > thead > tr.success > th,\n.table > tbody > tr.success > th,\n.table > tfoot > tr.success > th {\n background-color: #dff0d8;\n}\n.table-hover > tbody > tr > td.success:hover,\n.table-hover > tbody > tr > th.success:hover,\n.table-hover > tbody > tr.success:hover > td,\n.table-hover > tbody > tr:hover > .success,\n.table-hover > tbody > tr.success:hover > th {\n background-color: #d0e9c6;\n}\n.table > thead > tr > td.info,\n.table > tbody > tr > td.info,\n.table > tfoot > tr > td.info,\n.table > thead > tr > th.info,\n.table > tbody > tr > th.info,\n.table > tfoot > tr > th.info,\n.table > thead > tr.info > td,\n.table > tbody > tr.info > td,\n.table > tfoot > tr.info > td,\n.table > thead > tr.info > th,\n.table > tbody > tr.info > th,\n.table > tfoot > tr.info > th {\n background-color: #d9edf7;\n}\n.table-hover > tbody > tr > td.info:hover,\n.table-hover > tbody > tr > th.info:hover,\n.table-hover > tbody > tr.info:hover > td,\n.table-hover > tbody > tr:hover > .info,\n.table-hover > tbody > tr.info:hover > th {\n background-color: #c4e3f3;\n}\n.table > thead > tr > td.warning,\n.table > tbody > tr > td.warning,\n.table > tfoot > tr > td.warning,\n.table > thead > tr > th.warning,\n.table > tbody > tr > th.warning,\n.table > tfoot > tr > th.warning,\n.table > thead > tr.warning > td,\n.table > tbody > tr.warning > td,\n.table > tfoot > tr.warning > td,\n.table > thead > tr.warning > th,\n.table > tbody > tr.warning > th,\n.table > tfoot > tr.warning > th {\n background-color: #fcf8e3;\n}\n.table-hover > tbody > tr > td.warning:hover,\n.table-hover > tbody > tr > th.warning:hover,\n.table-hover > tbody > tr.warning:hover > td,\n.table-hover > tbody > tr:hover > .warning,\n.table-hover > tbody > tr.warning:hover > th {\n background-color: #faf2cc;\n}\n.table > thead > tr > td.danger,\n.table > tbody > tr > td.danger,\n.table > tfoot > tr > td.danger,\n.table > thead > tr > th.danger,\n.table > tbody > tr > th.danger,\n.table > tfoot > tr > th.danger,\n.table > thead > tr.danger > td,\n.table > tbody > tr.danger > td,\n.table > tfoot > tr.danger > td,\n.table > thead > tr.danger > th,\n.table > tbody > tr.danger > th,\n.table > tfoot > tr.danger > th {\n background-color: #f2dede;\n}\n.table-hover > tbody > tr > td.danger:hover,\n.table-hover > tbody > tr > th.danger:hover,\n.table-hover > tbody > tr.danger:hover > td,\n.table-hover > tbody > tr:hover > .danger,\n.table-hover > tbody > tr.danger:hover > th {\n background-color: #ebcccc;\n}\n.table-responsive {\n overflow-x: auto;\n min-height: 0.01%;\n}\n@media screen and (max-width: 767px) {\n .table-responsive {\n width: 100%;\n margin-bottom: 15px;\n overflow-y: hidden;\n -ms-overflow-style: -ms-autohiding-scrollbar;\n border: 1px solid #dddddd;\n }\n .table-responsive > .table {\n margin-bottom: 0;\n }\n .table-responsive > .table > thead > tr > th,\n .table-responsive > .table > tbody > tr > th,\n .table-responsive > .table > tfoot > tr > th,\n .table-responsive > .table > thead > tr > td,\n .table-responsive > .table > tbody > tr > td,\n .table-responsive > .table > tfoot > tr > td {\n white-space: nowrap;\n }\n .table-responsive > .table-bordered {\n border: 0;\n }\n .table-responsive > .table-bordered > thead > tr > th:first-child,\n .table-responsive > .table-bordered > tbody > tr > th:first-child,\n .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n .table-responsive > .table-bordered > thead > tr > td:first-child,\n .table-responsive > .table-bordered > tbody > tr > td:first-child,\n .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n border-left: 0;\n }\n .table-responsive > .table-bordered > thead > tr > th:last-child,\n .table-responsive > .table-bordered > tbody > tr > th:last-child,\n .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n .table-responsive > .table-bordered > thead > tr > td:last-child,\n .table-responsive > .table-bordered > tbody > tr > td:last-child,\n .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n border-right: 0;\n }\n .table-responsive > .table-bordered > tbody > tr:last-child > th,\n .table-responsive > .table-bordered > tfoot > tr:last-child > th,\n .table-responsive > .table-bordered > tbody > tr:last-child > td,\n .table-responsive > .table-bordered > tfoot > tr:last-child > td {\n border-bottom: 0;\n }\n}\nfieldset {\n padding: 0;\n margin: 0;\n border: 0;\n min-width: 0;\n}\nlegend {\n display: block;\n width: 100%;\n padding: 0;\n margin-bottom: 20px;\n font-size: 21px;\n line-height: inherit;\n color: #333333;\n border: 0;\n border-bottom: 1px solid #e5e5e5;\n}\nlabel {\n display: inline-block;\n max-width: 100%;\n margin-bottom: 5px;\n font-weight: bold;\n}\ninput[type=\"search\"] {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 4px 0 0;\n margin-top: 1px \\9;\n line-height: normal;\n}\ninput[type=\"file\"] {\n display: block;\n}\ninput[type=\"range\"] {\n display: block;\n width: 100%;\n}\nselect[multiple],\nselect[size] {\n height: auto;\n}\ninput[type=\"file\"]:focus,\ninput[type=\"radio\"]:focus,\ninput[type=\"checkbox\"]:focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\noutput {\n display: block;\n padding-top: 7px;\n font-size: 14px;\n line-height: 1.42857143;\n color: #555555;\n}\n.form-control {\n display: block;\n width: 100%;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n line-height: 1.42857143;\n color: #555555;\n background-color: #ffffff;\n background-image: none;\n border: 1px solid #cccccc;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n}\n.form-control:focus {\n border-color: #66afe9;\n outline: 0;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);\n box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);\n}\n.form-control::-moz-placeholder {\n color: #999999;\n opacity: 1;\n}\n.form-control:-ms-input-placeholder {\n color: #999999;\n}\n.form-control::-webkit-input-placeholder {\n color: #999999;\n}\n.form-control[disabled],\n.form-control[readonly],\nfieldset[disabled] .form-control {\n cursor: not-allowed;\n background-color: #eeeeee;\n opacity: 1;\n}\ntextarea.form-control {\n height: auto;\n}\ninput[type=\"search\"] {\n -webkit-appearance: none;\n}\n@media screen and (-webkit-min-device-pixel-ratio: 0) {\n input[type=\"date\"],\n input[type=\"time\"],\n input[type=\"datetime-local\"],\n input[type=\"month\"] {\n line-height: 34px;\n }\n input[type=\"date\"].input-sm,\n input[type=\"time\"].input-sm,\n input[type=\"datetime-local\"].input-sm,\n input[type=\"month\"].input-sm,\n .input-group-sm input[type=\"date\"],\n .input-group-sm input[type=\"time\"],\n .input-group-sm input[type=\"datetime-local\"],\n .input-group-sm input[type=\"month\"] {\n line-height: 30px;\n }\n input[type=\"date\"].input-lg,\n input[type=\"time\"].input-lg,\n input[type=\"datetime-local\"].input-lg,\n input[type=\"month\"].input-lg,\n .input-group-lg input[type=\"date\"],\n .input-group-lg input[type=\"time\"],\n .input-group-lg input[type=\"datetime-local\"],\n .input-group-lg input[type=\"month\"] {\n line-height: 46px;\n }\n}\n.form-group {\n margin-bottom: 15px;\n}\n.radio,\n.checkbox {\n position: relative;\n display: block;\n margin-top: 10px;\n margin-bottom: 10px;\n}\n.radio label,\n.checkbox label {\n min-height: 20px;\n padding-left: 20px;\n margin-bottom: 0;\n font-weight: normal;\n cursor: pointer;\n}\n.radio input[type=\"radio\"],\n.radio-inline input[type=\"radio\"],\n.checkbox input[type=\"checkbox\"],\n.checkbox-inline input[type=\"checkbox\"] {\n position: absolute;\n margin-left: -20px;\n margin-top: 4px \\9;\n}\n.radio + .radio,\n.checkbox + .checkbox {\n margin-top: -5px;\n}\n.radio-inline,\n.checkbox-inline {\n display: inline-block;\n padding-left: 20px;\n margin-bottom: 0;\n vertical-align: middle;\n font-weight: normal;\n cursor: pointer;\n}\n.radio-inline + .radio-inline,\n.checkbox-inline + .checkbox-inline {\n margin-top: 0;\n margin-left: 10px;\n}\ninput[type=\"radio\"][disabled],\ninput[type=\"checkbox\"][disabled],\ninput[type=\"radio\"].disabled,\ninput[type=\"checkbox\"].disabled,\nfieldset[disabled] input[type=\"radio\"],\nfieldset[disabled] input[type=\"checkbox\"] {\n cursor: not-allowed;\n}\n.radio-inline.disabled,\n.checkbox-inline.disabled,\nfieldset[disabled] .radio-inline,\nfieldset[disabled] .checkbox-inline {\n cursor: not-allowed;\n}\n.radio.disabled label,\n.checkbox.disabled label,\nfieldset[disabled] .radio label,\nfieldset[disabled] .checkbox label {\n cursor: not-allowed;\n}\n.form-control-static {\n padding-top: 7px;\n padding-bottom: 7px;\n margin-bottom: 0;\n}\n.form-control-static.input-lg,\n.form-control-static.input-sm {\n padding-left: 0;\n padding-right: 0;\n}\n.input-sm {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.input-sm {\n height: 30px;\n line-height: 30px;\n}\ntextarea.input-sm,\nselect[multiple].input-sm {\n height: auto;\n}\n.form-group-sm .form-control {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.form-group-sm .form-control {\n height: 30px;\n line-height: 30px;\n}\ntextarea.form-group-sm .form-control,\nselect[multiple].form-group-sm .form-control {\n height: auto;\n}\n.form-group-sm .form-control-static {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n}\n.input-lg {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.input-lg {\n height: 46px;\n line-height: 46px;\n}\ntextarea.input-lg,\nselect[multiple].input-lg {\n height: auto;\n}\n.form-group-lg .form-control {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.form-group-lg .form-control {\n height: 46px;\n line-height: 46px;\n}\ntextarea.form-group-lg .form-control,\nselect[multiple].form-group-lg .form-control {\n height: auto;\n}\n.form-group-lg .form-control-static {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n}\n.has-feedback {\n position: relative;\n}\n.has-feedback .form-control {\n padding-right: 42.5px;\n}\n.form-control-feedback {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 2;\n display: block;\n width: 34px;\n height: 34px;\n line-height: 34px;\n text-align: center;\n pointer-events: none;\n}\n.input-lg + .form-control-feedback {\n width: 46px;\n height: 46px;\n line-height: 46px;\n}\n.input-sm + .form-control-feedback {\n width: 30px;\n height: 30px;\n line-height: 30px;\n}\n.has-success .help-block,\n.has-success .control-label,\n.has-success .radio,\n.has-success .checkbox,\n.has-success .radio-inline,\n.has-success .checkbox-inline,\n.has-success.radio label,\n.has-success.checkbox label,\n.has-success.radio-inline label,\n.has-success.checkbox-inline label {\n color: #3c763d;\n}\n.has-success .form-control {\n border-color: #3c763d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-success .form-control:focus {\n border-color: #2b542c;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n}\n.has-success .input-group-addon {\n color: #3c763d;\n border-color: #3c763d;\n background-color: #dff0d8;\n}\n.has-success .form-control-feedback {\n color: #3c763d;\n}\n.has-warning .help-block,\n.has-warning .control-label,\n.has-warning .radio,\n.has-warning .checkbox,\n.has-warning .radio-inline,\n.has-warning .checkbox-inline,\n.has-warning.radio label,\n.has-warning.checkbox label,\n.has-warning.radio-inline label,\n.has-warning.checkbox-inline label {\n color: #8a6d3b;\n}\n.has-warning .form-control {\n border-color: #8a6d3b;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-warning .form-control:focus {\n border-color: #66512c;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n}\n.has-warning .input-group-addon {\n color: #8a6d3b;\n border-color: #8a6d3b;\n background-color: #fcf8e3;\n}\n.has-warning .form-control-feedback {\n color: #8a6d3b;\n}\n.has-error .help-block,\n.has-error .control-label,\n.has-error .radio,\n.has-error .checkbox,\n.has-error .radio-inline,\n.has-error .checkbox-inline,\n.has-error.radio label,\n.has-error.checkbox label,\n.has-error.radio-inline label,\n.has-error.checkbox-inline label {\n color: #a94442;\n}\n.has-error .form-control {\n border-color: #a94442;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-error .form-control:focus {\n border-color: #843534;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n}\n.has-error .input-group-addon {\n color: #a94442;\n border-color: #a94442;\n background-color: #f2dede;\n}\n.has-error .form-control-feedback {\n color: #a94442;\n}\n.has-feedback label ~ .form-control-feedback {\n top: 25px;\n}\n.has-feedback label.sr-only ~ .form-control-feedback {\n top: 0;\n}\n.help-block {\n display: block;\n margin-top: 5px;\n margin-bottom: 10px;\n color: #737373;\n}\n@media (min-width: 768px) {\n .form-inline .form-group {\n display: inline-block;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .form-control {\n display: inline-block;\n width: auto;\n vertical-align: middle;\n }\n .form-inline .form-control-static {\n display: inline-block;\n }\n .form-inline .input-group {\n display: inline-table;\n vertical-align: middle;\n }\n .form-inline .input-group .input-group-addon,\n .form-inline .input-group .input-group-btn,\n .form-inline .input-group .form-control {\n width: auto;\n }\n .form-inline .input-group > .form-control {\n width: 100%;\n }\n .form-inline .control-label {\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .radio,\n .form-inline .checkbox {\n display: inline-block;\n margin-top: 0;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .radio label,\n .form-inline .checkbox label {\n padding-left: 0;\n }\n .form-inline .radio input[type=\"radio\"],\n .form-inline .checkbox input[type=\"checkbox\"] {\n position: relative;\n margin-left: 0;\n }\n .form-inline .has-feedback .form-control-feedback {\n top: 0;\n }\n}\n.form-horizontal .radio,\n.form-horizontal .checkbox,\n.form-horizontal .radio-inline,\n.form-horizontal .checkbox-inline {\n margin-top: 0;\n margin-bottom: 0;\n padding-top: 7px;\n}\n.form-horizontal .radio,\n.form-horizontal .checkbox {\n min-height: 27px;\n}\n.form-horizontal .form-group {\n margin-left: -15px;\n margin-right: -15px;\n}\n@media (min-width: 768px) {\n .form-horizontal .control-label {\n text-align: right;\n margin-bottom: 0;\n padding-top: 7px;\n }\n}\n.form-horizontal .has-feedback .form-control-feedback {\n right: 15px;\n}\n@media (min-width: 768px) {\n .form-horizontal .form-group-lg .control-label {\n padding-top: 14.333333px;\n }\n}\n@media (min-width: 768px) {\n .form-horizontal .form-group-sm .control-label {\n padding-top: 6px;\n }\n}\n.btn {\n display: inline-block;\n margin-bottom: 0;\n font-weight: normal;\n text-align: center;\n vertical-align: middle;\n touch-action: manipulation;\n cursor: pointer;\n background-image: none;\n border: 1px solid transparent;\n white-space: nowrap;\n padding: 6px 12px;\n font-size: 14px;\n line-height: 1.42857143;\n border-radius: 4px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.btn:focus,\n.btn:active:focus,\n.btn.active:focus,\n.btn.focus,\n.btn:active.focus,\n.btn.active.focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\n.btn:hover,\n.btn:focus,\n.btn.focus {\n color: #333333;\n text-decoration: none;\n}\n.btn:active,\n.btn.active {\n outline: 0;\n background-image: none;\n -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n.btn.disabled,\n.btn[disabled],\nfieldset[disabled] .btn {\n cursor: not-allowed;\n pointer-events: none;\n opacity: 0.65;\n filter: alpha(opacity=65);\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn-default {\n color: #333333;\n background-color: #ffffff;\n border-color: #cccccc;\n}\n.btn-default:hover,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.open > .dropdown-toggle.btn-default {\n color: #333333;\n background-color: #e6e6e6;\n border-color: #adadad;\n}\n.btn-default:active,\n.btn-default.active,\n.open > .dropdown-toggle.btn-default {\n background-image: none;\n}\n.btn-default.disabled,\n.btn-default[disabled],\nfieldset[disabled] .btn-default,\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus,\n.btn-default.disabled:active,\n.btn-default[disabled]:active,\nfieldset[disabled] .btn-default:active,\n.btn-default.disabled.active,\n.btn-default[disabled].active,\nfieldset[disabled] .btn-default.active {\n background-color: #ffffff;\n border-color: #cccccc;\n}\n.btn-default .badge {\n color: #ffffff;\n background-color: #333333;\n}\n.btn-primary {\n color: #ffffff;\n background-color: #337ab7;\n border-color: #2e6da4;\n}\n.btn-primary:hover,\n.btn-primary:focus,\n.btn-primary.focus,\n.btn-primary:active,\n.btn-primary.active,\n.open > .dropdown-toggle.btn-primary {\n color: #ffffff;\n background-color: #286090;\n border-color: #204d74;\n}\n.btn-primary:active,\n.btn-primary.active,\n.open > .dropdown-toggle.btn-primary {\n background-image: none;\n}\n.btn-primary.disabled,\n.btn-primary[disabled],\nfieldset[disabled] .btn-primary,\n.btn-primary.disabled:hover,\n.btn-primary[disabled]:hover,\nfieldset[disabled] .btn-primary:hover,\n.btn-primary.disabled:focus,\n.btn-primary[disabled]:focus,\nfieldset[disabled] .btn-primary:focus,\n.btn-primary.disabled.focus,\n.btn-primary[disabled].focus,\nfieldset[disabled] .btn-primary.focus,\n.btn-primary.disabled:active,\n.btn-primary[disabled]:active,\nfieldset[disabled] .btn-primary:active,\n.btn-primary.disabled.active,\n.btn-primary[disabled].active,\nfieldset[disabled] .btn-primary.active {\n background-color: #337ab7;\n border-color: #2e6da4;\n}\n.btn-primary .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.btn-success {\n color: #ffffff;\n background-color: #5cb85c;\n border-color: #4cae4c;\n}\n.btn-success:hover,\n.btn-success:focus,\n.btn-success.focus,\n.btn-success:active,\n.btn-success.active,\n.open > .dropdown-toggle.btn-success {\n color: #ffffff;\n background-color: #449d44;\n border-color: #398439;\n}\n.btn-success:active,\n.btn-success.active,\n.open > .dropdown-toggle.btn-success {\n background-image: none;\n}\n.btn-success.disabled,\n.btn-success[disabled],\nfieldset[disabled] .btn-success,\n.btn-success.disabled:hover,\n.btn-success[disabled]:hover,\nfieldset[disabled] .btn-success:hover,\n.btn-success.disabled:focus,\n.btn-success[disabled]:focus,\nfieldset[disabled] .btn-success:focus,\n.btn-success.disabled.focus,\n.btn-success[disabled].focus,\nfieldset[disabled] .btn-success.focus,\n.btn-success.disabled:active,\n.btn-success[disabled]:active,\nfieldset[disabled] .btn-success:active,\n.btn-success.disabled.active,\n.btn-success[disabled].active,\nfieldset[disabled] .btn-success.active {\n background-color: #5cb85c;\n border-color: #4cae4c;\n}\n.btn-success .badge {\n color: #5cb85c;\n background-color: #ffffff;\n}\n.btn-info {\n color: #ffffff;\n background-color: #5bc0de;\n border-color: #46b8da;\n}\n.btn-info:hover,\n.btn-info:focus,\n.btn-info.focus,\n.btn-info:active,\n.btn-info.active,\n.open > .dropdown-toggle.btn-info {\n color: #ffffff;\n background-color: #31b0d5;\n border-color: #269abc;\n}\n.btn-info:active,\n.btn-info.active,\n.open > .dropdown-toggle.btn-info {\n background-image: none;\n}\n.btn-info.disabled,\n.btn-info[disabled],\nfieldset[disabled] .btn-info,\n.btn-info.disabled:hover,\n.btn-info[disabled]:hover,\nfieldset[disabled] .btn-info:hover,\n.btn-info.disabled:focus,\n.btn-info[disabled]:focus,\nfieldset[disabled] .btn-info:focus,\n.btn-info.disabled.focus,\n.btn-info[disabled].focus,\nfieldset[disabled] .btn-info.focus,\n.btn-info.disabled:active,\n.btn-info[disabled]:active,\nfieldset[disabled] .btn-info:active,\n.btn-info.disabled.active,\n.btn-info[disabled].active,\nfieldset[disabled] .btn-info.active {\n background-color: #5bc0de;\n border-color: #46b8da;\n}\n.btn-info .badge {\n color: #5bc0de;\n background-color: #ffffff;\n}\n.btn-warning {\n color: #ffffff;\n background-color: #f0ad4e;\n border-color: #eea236;\n}\n.btn-warning:hover,\n.btn-warning:focus,\n.btn-warning.focus,\n.btn-warning:active,\n.btn-warning.active,\n.open > .dropdown-toggle.btn-warning {\n color: #ffffff;\n background-color: #ec971f;\n border-color: #d58512;\n}\n.btn-warning:active,\n.btn-warning.active,\n.open > .dropdown-toggle.btn-warning {\n background-image: none;\n}\n.btn-warning.disabled,\n.btn-warning[disabled],\nfieldset[disabled] .btn-warning,\n.btn-warning.disabled:hover,\n.btn-warning[disabled]:hover,\nfieldset[disabled] .btn-warning:hover,\n.btn-warning.disabled:focus,\n.btn-warning[disabled]:focus,\nfieldset[disabled] .btn-warning:focus,\n.btn-warning.disabled.focus,\n.btn-warning[disabled].focus,\nfieldset[disabled] .btn-warning.focus,\n.btn-warning.disabled:active,\n.btn-warning[disabled]:active,\nfieldset[disabled] .btn-warning:active,\n.btn-warning.disabled.active,\n.btn-warning[disabled].active,\nfieldset[disabled] .btn-warning.active {\n background-color: #f0ad4e;\n border-color: #eea236;\n}\n.btn-warning .badge {\n color: #f0ad4e;\n background-color: #ffffff;\n}\n.btn-danger {\n color: #ffffff;\n background-color: #d9534f;\n border-color: #d43f3a;\n}\n.btn-danger:hover,\n.btn-danger:focus,\n.btn-danger.focus,\n.btn-danger:active,\n.btn-danger.active,\n.open > .dropdown-toggle.btn-danger {\n color: #ffffff;\n background-color: #c9302c;\n border-color: #ac2925;\n}\n.btn-danger:active,\n.btn-danger.active,\n.open > .dropdown-toggle.btn-danger {\n background-image: none;\n}\n.btn-danger.disabled,\n.btn-danger[disabled],\nfieldset[disabled] .btn-danger,\n.btn-danger.disabled:hover,\n.btn-danger[disabled]:hover,\nfieldset[disabled] .btn-danger:hover,\n.btn-danger.disabled:focus,\n.btn-danger[disabled]:focus,\nfieldset[disabled] .btn-danger:focus,\n.btn-danger.disabled.focus,\n.btn-danger[disabled].focus,\nfieldset[disabled] .btn-danger.focus,\n.btn-danger.disabled:active,\n.btn-danger[disabled]:active,\nfieldset[disabled] .btn-danger:active,\n.btn-danger.disabled.active,\n.btn-danger[disabled].active,\nfieldset[disabled] .btn-danger.active {\n background-color: #d9534f;\n border-color: #d43f3a;\n}\n.btn-danger .badge {\n color: #d9534f;\n background-color: #ffffff;\n}\n.btn-link {\n color: #337ab7;\n font-weight: normal;\n border-radius: 0;\n}\n.btn-link,\n.btn-link:active,\n.btn-link.active,\n.btn-link[disabled],\nfieldset[disabled] .btn-link {\n background-color: transparent;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn-link,\n.btn-link:hover,\n.btn-link:focus,\n.btn-link:active {\n border-color: transparent;\n}\n.btn-link:hover,\n.btn-link:focus {\n color: #23527c;\n text-decoration: underline;\n background-color: transparent;\n}\n.btn-link[disabled]:hover,\nfieldset[disabled] .btn-link:hover,\n.btn-link[disabled]:focus,\nfieldset[disabled] .btn-link:focus {\n color: #777777;\n text-decoration: none;\n}\n.btn-lg,\n.btn-group-lg > .btn {\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\n.btn-sm,\n.btn-group-sm > .btn {\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n padding: 1px 5px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\n.btn-block {\n display: block;\n width: 100%;\n}\n.btn-block + .btn-block {\n margin-top: 5px;\n}\ninput[type=\"submit\"].btn-block,\ninput[type=\"reset\"].btn-block,\ninput[type=\"button\"].btn-block {\n width: 100%;\n}\n.fade {\n opacity: 0;\n -webkit-transition: opacity 0.15s linear;\n -o-transition: opacity 0.15s linear;\n transition: opacity 0.15s linear;\n}\n.fade.in {\n opacity: 1;\n}\n.collapse {\n display: none;\n visibility: hidden;\n}\n.collapse.in {\n display: block;\n visibility: visible;\n}\ntr.collapse.in {\n display: table-row;\n}\ntbody.collapse.in {\n display: table-row-group;\n}\n.collapsing {\n position: relative;\n height: 0;\n overflow: hidden;\n -webkit-transition-property: height, visibility;\n transition-property: height, visibility;\n -webkit-transition-duration: 0.35s;\n transition-duration: 0.35s;\n -webkit-transition-timing-function: ease;\n transition-timing-function: ease;\n}\n.caret {\n display: inline-block;\n width: 0;\n height: 0;\n margin-left: 2px;\n vertical-align: middle;\n border-top: 4px solid;\n border-right: 4px solid transparent;\n border-left: 4px solid transparent;\n}\n.dropup,\n.dropdown {\n position: relative;\n}\n.dropdown-toggle:focus {\n outline: 0;\n}\n.dropdown-menu {\n position: absolute;\n top: 100%;\n left: 0;\n z-index: 1000;\n display: none;\n float: left;\n min-width: 160px;\n padding: 5px 0;\n margin: 2px 0 0;\n list-style: none;\n font-size: 14px;\n text-align: left;\n background-color: #ffffff;\n border: 1px solid #cccccc;\n border: 1px solid rgba(0, 0, 0, 0.15);\n border-radius: 4px;\n -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n background-clip: padding-box;\n}\n.dropdown-menu.pull-right {\n right: 0;\n left: auto;\n}\n.dropdown-menu .divider {\n height: 1px;\n margin: 9px 0;\n overflow: hidden;\n background-color: #e5e5e5;\n}\n.dropdown-menu > li > a {\n display: block;\n padding: 3px 20px;\n clear: both;\n font-weight: normal;\n line-height: 1.42857143;\n color: #333333;\n white-space: nowrap;\n}\n.dropdown-menu > li > a:hover,\n.dropdown-menu > li > a:focus {\n text-decoration: none;\n color: #262626;\n background-color: #f5f5f5;\n}\n.dropdown-menu > .active > a,\n.dropdown-menu > .active > a:hover,\n.dropdown-menu > .active > a:focus {\n color: #ffffff;\n text-decoration: none;\n outline: 0;\n background-color: #337ab7;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n color: #777777;\n}\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n text-decoration: none;\n background-color: transparent;\n background-image: none;\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n cursor: not-allowed;\n}\n.open > .dropdown-menu {\n display: block;\n}\n.open > a {\n outline: 0;\n}\n.dropdown-menu-right {\n left: auto;\n right: 0;\n}\n.dropdown-menu-left {\n left: 0;\n right: auto;\n}\n.dropdown-header {\n display: block;\n padding: 3px 20px;\n font-size: 12px;\n line-height: 1.42857143;\n color: #777777;\n white-space: nowrap;\n}\n.dropdown-backdrop {\n position: fixed;\n left: 0;\n right: 0;\n bottom: 0;\n top: 0;\n z-index: 990;\n}\n.pull-right > .dropdown-menu {\n right: 0;\n left: auto;\n}\n.dropup .caret,\n.navbar-fixed-bottom .dropdown .caret {\n border-top: 0;\n border-bottom: 4px solid;\n content: \"\";\n}\n.dropup .dropdown-menu,\n.navbar-fixed-bottom .dropdown .dropdown-menu {\n top: auto;\n bottom: 100%;\n margin-bottom: 2px;\n}\n@media (min-width: 768px) {\n .navbar-right .dropdown-menu {\n left: auto;\n right: 0;\n }\n .navbar-right .dropdown-menu-left {\n left: 0;\n right: auto;\n }\n}\n.btn-group,\n.btn-group-vertical {\n position: relative;\n display: inline-block;\n vertical-align: middle;\n}\n.btn-group > .btn,\n.btn-group-vertical > .btn {\n position: relative;\n float: left;\n}\n.btn-group > .btn:hover,\n.btn-group-vertical > .btn:hover,\n.btn-group > .btn:focus,\n.btn-group-vertical > .btn:focus,\n.btn-group > .btn:active,\n.btn-group-vertical > .btn:active,\n.btn-group > .btn.active,\n.btn-group-vertical > .btn.active {\n z-index: 2;\n}\n.btn-group .btn + .btn,\n.btn-group .btn + .btn-group,\n.btn-group .btn-group + .btn,\n.btn-group .btn-group + .btn-group {\n margin-left: -1px;\n}\n.btn-toolbar {\n margin-left: -5px;\n}\n.btn-toolbar .btn-group,\n.btn-toolbar .input-group {\n float: left;\n}\n.btn-toolbar > .btn,\n.btn-toolbar > .btn-group,\n.btn-toolbar > .input-group {\n margin-left: 5px;\n}\n.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {\n border-radius: 0;\n}\n.btn-group > .btn:first-child {\n margin-left: 0;\n}\n.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.btn-group > .btn:last-child:not(:first-child),\n.btn-group > .dropdown-toggle:not(:first-child) {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group > .btn-group {\n float: left;\n}\n.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,\n.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group .dropdown-toggle:active,\n.btn-group.open .dropdown-toggle {\n outline: 0;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n}\n.btn-group > .btn-lg + .dropdown-toggle {\n padding-left: 12px;\n padding-right: 12px;\n}\n.btn-group.open .dropdown-toggle {\n -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n.btn-group.open .dropdown-toggle.btn-link {\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn .caret {\n margin-left: 0;\n}\n.btn-lg .caret {\n border-width: 5px 5px 0;\n border-bottom-width: 0;\n}\n.dropup .btn-lg .caret {\n border-width: 0 5px 5px;\n}\n.btn-group-vertical > .btn,\n.btn-group-vertical > .btn-group,\n.btn-group-vertical > .btn-group > .btn {\n display: block;\n float: none;\n width: 100%;\n max-width: 100%;\n}\n.btn-group-vertical > .btn-group > .btn {\n float: none;\n}\n.btn-group-vertical > .btn + .btn,\n.btn-group-vertical > .btn + .btn-group,\n.btn-group-vertical > .btn-group + .btn,\n.btn-group-vertical > .btn-group + .btn-group {\n margin-top: -1px;\n margin-left: 0;\n}\n.btn-group-vertical > .btn:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.btn-group-vertical > .btn:first-child:not(:last-child) {\n border-top-right-radius: 4px;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.btn-group-vertical > .btn:last-child:not(:first-child) {\n border-bottom-left-radius: 4px;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,\n.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group-justified {\n display: table;\n width: 100%;\n table-layout: fixed;\n border-collapse: separate;\n}\n.btn-group-justified > .btn,\n.btn-group-justified > .btn-group {\n float: none;\n display: table-cell;\n width: 1%;\n}\n.btn-group-justified > .btn-group .btn {\n width: 100%;\n}\n.btn-group-justified > .btn-group .dropdown-menu {\n left: auto;\n}\n[data-toggle=\"buttons\"] > .btn input[type=\"radio\"],\n[data-toggle=\"buttons\"] > .btn-group > .btn input[type=\"radio\"],\n[data-toggle=\"buttons\"] > .btn input[type=\"checkbox\"],\n[data-toggle=\"buttons\"] > .btn-group > .btn input[type=\"checkbox\"] {\n position: absolute;\n clip: rect(0, 0, 0, 0);\n pointer-events: none;\n}\n.input-group {\n position: relative;\n display: table;\n border-collapse: separate;\n}\n.input-group[class*=\"col-\"] {\n float: none;\n padding-left: 0;\n padding-right: 0;\n}\n.input-group .form-control {\n position: relative;\n z-index: 2;\n float: left;\n width: 100%;\n margin-bottom: 0;\n}\n.input-group-lg > .form-control,\n.input-group-lg > .input-group-addon,\n.input-group-lg > .input-group-btn > .btn {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.input-group-lg > .form-control,\nselect.input-group-lg > .input-group-addon,\nselect.input-group-lg > .input-group-btn > .btn {\n height: 46px;\n line-height: 46px;\n}\ntextarea.input-group-lg > .form-control,\ntextarea.input-group-lg > .input-group-addon,\ntextarea.input-group-lg > .input-group-btn > .btn,\nselect[multiple].input-group-lg > .form-control,\nselect[multiple].input-group-lg > .input-group-addon,\nselect[multiple].input-group-lg > .input-group-btn > .btn {\n height: auto;\n}\n.input-group-sm > .form-control,\n.input-group-sm > .input-group-addon,\n.input-group-sm > .input-group-btn > .btn {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.input-group-sm > .form-control,\nselect.input-group-sm > .input-group-addon,\nselect.input-group-sm > .input-group-btn > .btn {\n height: 30px;\n line-height: 30px;\n}\ntextarea.input-group-sm > .form-control,\ntextarea.input-group-sm > .input-group-addon,\ntextarea.input-group-sm > .input-group-btn > .btn,\nselect[multiple].input-group-sm > .form-control,\nselect[multiple].input-group-sm > .input-group-addon,\nselect[multiple].input-group-sm > .input-group-btn > .btn {\n height: auto;\n}\n.input-group-addon,\n.input-group-btn,\n.input-group .form-control {\n display: table-cell;\n}\n.input-group-addon:not(:first-child):not(:last-child),\n.input-group-btn:not(:first-child):not(:last-child),\n.input-group .form-control:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.input-group-addon,\n.input-group-btn {\n width: 1%;\n white-space: nowrap;\n vertical-align: middle;\n}\n.input-group-addon {\n padding: 6px 12px;\n font-size: 14px;\n font-weight: normal;\n line-height: 1;\n color: #555555;\n text-align: center;\n background-color: #eeeeee;\n border: 1px solid #cccccc;\n border-radius: 4px;\n}\n.input-group-addon.input-sm {\n padding: 5px 10px;\n font-size: 12px;\n border-radius: 3px;\n}\n.input-group-addon.input-lg {\n padding: 10px 16px;\n font-size: 18px;\n border-radius: 6px;\n}\n.input-group-addon input[type=\"radio\"],\n.input-group-addon input[type=\"checkbox\"] {\n margin-top: 0;\n}\n.input-group .form-control:first-child,\n.input-group-addon:first-child,\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group > .btn,\n.input-group-btn:first-child > .dropdown-toggle,\n.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),\n.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.input-group-addon:first-child {\n border-right: 0;\n}\n.input-group .form-control:last-child,\n.input-group-addon:last-child,\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .btn-group > .btn,\n.input-group-btn:last-child > .dropdown-toggle,\n.input-group-btn:first-child > .btn:not(:first-child),\n.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.input-group-addon:last-child {\n border-left: 0;\n}\n.input-group-btn {\n position: relative;\n font-size: 0;\n white-space: nowrap;\n}\n.input-group-btn > .btn {\n position: relative;\n}\n.input-group-btn > .btn + .btn {\n margin-left: -1px;\n}\n.input-group-btn > .btn:hover,\n.input-group-btn > .btn:focus,\n.input-group-btn > .btn:active {\n z-index: 2;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n margin-right: -1px;\n}\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .btn-group {\n margin-left: -1px;\n}\n.nav {\n margin-bottom: 0;\n padding-left: 0;\n list-style: none;\n}\n.nav > li {\n position: relative;\n display: block;\n}\n.nav > li > a {\n position: relative;\n display: block;\n padding: 10px 15px;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: #eeeeee;\n}\n.nav > li.disabled > a {\n color: #777777;\n}\n.nav > li.disabled > a:hover,\n.nav > li.disabled > a:focus {\n color: #777777;\n text-decoration: none;\n background-color: transparent;\n cursor: not-allowed;\n}\n.nav .open > a,\n.nav .open > a:hover,\n.nav .open > a:focus {\n background-color: #eeeeee;\n border-color: #337ab7;\n}\n.nav .nav-divider {\n height: 1px;\n margin: 9px 0;\n overflow: hidden;\n background-color: #e5e5e5;\n}\n.nav > li > a > img {\n max-width: none;\n}\n.nav-tabs {\n border-bottom: 1px solid #dddddd;\n}\n.nav-tabs > li {\n float: left;\n margin-bottom: -1px;\n}\n.nav-tabs > li > a {\n margin-right: 2px;\n line-height: 1.42857143;\n border: 1px solid transparent;\n border-radius: 4px 4px 0 0;\n}\n.nav-tabs > li > a:hover {\n border-color: #eeeeee #eeeeee #dddddd;\n}\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #555555;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav-tabs.nav-justified {\n width: 100%;\n border-bottom: 0;\n}\n.nav-tabs.nav-justified > li {\n float: none;\n}\n.nav-tabs.nav-justified > li > a {\n text-align: center;\n margin-bottom: 5px;\n}\n.nav-tabs.nav-justified > .dropdown .dropdown-menu {\n top: auto;\n left: auto;\n}\n@media (min-width: 768px) {\n .nav-tabs.nav-justified > li {\n display: table-cell;\n width: 1%;\n }\n .nav-tabs.nav-justified > li > a {\n margin-bottom: 0;\n }\n}\n.nav-tabs.nav-justified > li > a {\n margin-right: 0;\n border-radius: 4px;\n}\n.nav-tabs.nav-justified > .active > a,\n.nav-tabs.nav-justified > .active > a:hover,\n.nav-tabs.nav-justified > .active > a:focus {\n border: 1px solid #dddddd;\n}\n@media (min-width: 768px) {\n .nav-tabs.nav-justified > li > a {\n border-bottom: 1px solid #dddddd;\n border-radius: 4px 4px 0 0;\n }\n .nav-tabs.nav-justified > .active > a,\n .nav-tabs.nav-justified > .active > a:hover,\n .nav-tabs.nav-justified > .active > a:focus {\n border-bottom-color: #ffffff;\n }\n}\n.nav-pills > li {\n float: left;\n}\n.nav-pills > li > a {\n border-radius: 4px;\n}\n.nav-pills > li + li {\n margin-left: 2px;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #337ab7;\n}\n.nav-stacked > li {\n float: none;\n}\n.nav-stacked > li + li {\n margin-top: 2px;\n margin-left: 0;\n}\n.nav-justified {\n width: 100%;\n}\n.nav-justified > li {\n float: none;\n}\n.nav-justified > li > a {\n text-align: center;\n margin-bottom: 5px;\n}\n.nav-justified > .dropdown .dropdown-menu {\n top: auto;\n left: auto;\n}\n@media (min-width: 768px) {\n .nav-justified > li {\n display: table-cell;\n width: 1%;\n }\n .nav-justified > li > a {\n margin-bottom: 0;\n }\n}\n.nav-tabs-justified {\n border-bottom: 0;\n}\n.nav-tabs-justified > li > a {\n margin-right: 0;\n border-radius: 4px;\n}\n.nav-tabs-justified > .active > a,\n.nav-tabs-justified > .active > a:hover,\n.nav-tabs-justified > .active > a:focus {\n border: 1px solid #dddddd;\n}\n@media (min-width: 768px) {\n .nav-tabs-justified > li > a {\n border-bottom: 1px solid #dddddd;\n border-radius: 4px 4px 0 0;\n }\n .nav-tabs-justified > .active > a,\n .nav-tabs-justified > .active > a:hover,\n .nav-tabs-justified > .active > a:focus {\n border-bottom-color: #ffffff;\n }\n}\n.tab-content > .tab-pane {\n display: none;\n visibility: hidden;\n}\n.tab-content > .active {\n display: block;\n visibility: visible;\n}\n.nav-tabs .dropdown-menu {\n margin-top: -1px;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.navbar {\n position: relative;\n min-height: 50px;\n margin-bottom: 20px;\n border: 1px solid transparent;\n}\n@media (min-width: 768px) {\n .navbar {\n border-radius: 4px;\n }\n}\n@media (min-width: 768px) {\n .navbar-header {\n float: left;\n }\n}\n.navbar-collapse {\n overflow-x: visible;\n padding-right: 15px;\n padding-left: 15px;\n border-top: 1px solid transparent;\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);\n -webkit-overflow-scrolling: touch;\n}\n.navbar-collapse.in {\n overflow-y: auto;\n}\n@media (min-width: 768px) {\n .navbar-collapse {\n width: auto;\n border-top: 0;\n box-shadow: none;\n }\n .navbar-collapse.collapse {\n display: block !important;\n visibility: visible !important;\n height: auto !important;\n padding-bottom: 0;\n overflow: visible !important;\n }\n .navbar-collapse.in {\n overflow-y: visible;\n }\n .navbar-fixed-top .navbar-collapse,\n .navbar-static-top .navbar-collapse,\n .navbar-fixed-bottom .navbar-collapse {\n padding-left: 0;\n padding-right: 0;\n }\n}\n.navbar-fixed-top .navbar-collapse,\n.navbar-fixed-bottom .navbar-collapse {\n max-height: 340px;\n}\n@media (max-device-width: 480px) and (orientation: landscape) {\n .navbar-fixed-top .navbar-collapse,\n .navbar-fixed-bottom .navbar-collapse {\n max-height: 200px;\n }\n}\n.container > .navbar-header,\n.container-fluid > .navbar-header,\n.container > .navbar-collapse,\n.container-fluid > .navbar-collapse {\n margin-right: -15px;\n margin-left: -15px;\n}\n@media (min-width: 768px) {\n .container > .navbar-header,\n .container-fluid > .navbar-header,\n .container > .navbar-collapse,\n .container-fluid > .navbar-collapse {\n margin-right: 0;\n margin-left: 0;\n }\n}\n.navbar-static-top {\n z-index: 1000;\n border-width: 0 0 1px;\n}\n@media (min-width: 768px) {\n .navbar-static-top {\n border-radius: 0;\n }\n}\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n position: fixed;\n right: 0;\n left: 0;\n z-index: 1030;\n}\n@media (min-width: 768px) {\n .navbar-fixed-top,\n .navbar-fixed-bottom {\n border-radius: 0;\n }\n}\n.navbar-fixed-top {\n top: 0;\n border-width: 0 0 1px;\n}\n.navbar-fixed-bottom {\n bottom: 0;\n margin-bottom: 0;\n border-width: 1px 0 0;\n}\n.navbar-brand {\n float: left;\n padding: 15px 15px;\n font-size: 18px;\n line-height: 20px;\n height: 50px;\n}\n.navbar-brand:hover,\n.navbar-brand:focus {\n text-decoration: none;\n}\n.navbar-brand > img {\n display: block;\n}\n@media (min-width: 768px) {\n .navbar > .container .navbar-brand,\n .navbar > .container-fluid .navbar-brand {\n margin-left: -15px;\n }\n}\n.navbar-toggle {\n position: relative;\n float: right;\n margin-right: 15px;\n padding: 9px 10px;\n margin-top: 8px;\n margin-bottom: 8px;\n background-color: transparent;\n background-image: none;\n border: 1px solid transparent;\n border-radius: 4px;\n}\n.navbar-toggle:focus {\n outline: 0;\n}\n.navbar-toggle .icon-bar {\n display: block;\n width: 22px;\n height: 2px;\n border-radius: 1px;\n}\n.navbar-toggle .icon-bar + .icon-bar {\n margin-top: 4px;\n}\n@media (min-width: 768px) {\n .navbar-toggle {\n display: none;\n }\n}\n.navbar-nav {\n margin: 7.5px -15px;\n}\n.navbar-nav > li > a {\n padding-top: 10px;\n padding-bottom: 10px;\n line-height: 20px;\n}\n@media (max-width: 767px) {\n .navbar-nav .open .dropdown-menu {\n position: static;\n float: none;\n width: auto;\n margin-top: 0;\n background-color: transparent;\n border: 0;\n box-shadow: none;\n }\n .navbar-nav .open .dropdown-menu > li > a,\n .navbar-nav .open .dropdown-menu .dropdown-header {\n padding: 5px 15px 5px 25px;\n }\n .navbar-nav .open .dropdown-menu > li > a {\n line-height: 20px;\n }\n .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-nav .open .dropdown-menu > li > a:focus {\n background-image: none;\n }\n}\n@media (min-width: 768px) {\n .navbar-nav {\n float: left;\n margin: 0;\n }\n .navbar-nav > li {\n float: left;\n }\n .navbar-nav > li > a {\n padding-top: 15px;\n padding-bottom: 15px;\n }\n}\n.navbar-form {\n margin-left: -15px;\n margin-right: -15px;\n padding: 10px 15px;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n margin-top: 8px;\n margin-bottom: 8px;\n}\n@media (min-width: 768px) {\n .navbar-form .form-group {\n display: inline-block;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .form-control {\n display: inline-block;\n width: auto;\n vertical-align: middle;\n }\n .navbar-form .form-control-static {\n display: inline-block;\n }\n .navbar-form .input-group {\n display: inline-table;\n vertical-align: middle;\n }\n .navbar-form .input-group .input-group-addon,\n .navbar-form .input-group .input-group-btn,\n .navbar-form .input-group .form-control {\n width: auto;\n }\n .navbar-form .input-group > .form-control {\n width: 100%;\n }\n .navbar-form .control-label {\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .radio,\n .navbar-form .checkbox {\n display: inline-block;\n margin-top: 0;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .radio label,\n .navbar-form .checkbox label {\n padding-left: 0;\n }\n .navbar-form .radio input[type=\"radio\"],\n .navbar-form .checkbox input[type=\"checkbox\"] {\n position: relative;\n margin-left: 0;\n }\n .navbar-form .has-feedback .form-control-feedback {\n top: 0;\n }\n}\n@media (max-width: 767px) {\n .navbar-form .form-group {\n margin-bottom: 5px;\n }\n .navbar-form .form-group:last-child {\n margin-bottom: 0;\n }\n}\n@media (min-width: 768px) {\n .navbar-form {\n width: auto;\n border: 0;\n margin-left: 0;\n margin-right: 0;\n padding-top: 0;\n padding-bottom: 0;\n -webkit-box-shadow: none;\n box-shadow: none;\n }\n}\n.navbar-nav > li > .dropdown-menu {\n margin-top: 0;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {\n margin-bottom: 0;\n border-top-right-radius: 4px;\n border-top-left-radius: 4px;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.navbar-btn {\n margin-top: 8px;\n margin-bottom: 8px;\n}\n.navbar-btn.btn-sm {\n margin-top: 10px;\n margin-bottom: 10px;\n}\n.navbar-btn.btn-xs {\n margin-top: 14px;\n margin-bottom: 14px;\n}\n.navbar-text {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n@media (min-width: 768px) {\n .navbar-text {\n float: left;\n margin-left: 15px;\n margin-right: 15px;\n }\n}\n@media (min-width: 768px) {\n .navbar-left {\n float: left !important;\n }\n .navbar-right {\n float: right !important;\n margin-right: -15px;\n }\n .navbar-right ~ .navbar-right {\n margin-right: 0;\n }\n}\n.navbar-default {\n background-color: #f8f8f8;\n border-color: #e7e7e7;\n}\n.navbar-default .navbar-brand {\n color: #777777;\n}\n.navbar-default .navbar-brand:hover,\n.navbar-default .navbar-brand:focus {\n color: #5e5e5e;\n background-color: transparent;\n}\n.navbar-default .navbar-text {\n color: #777777;\n}\n.navbar-default .navbar-nav > li > a {\n color: #777777;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #333333;\n background-color: transparent;\n}\n.navbar-default .navbar-nav > .active > a,\n.navbar-default .navbar-nav > .active > a:hover,\n.navbar-default .navbar-nav > .active > a:focus {\n color: #555555;\n background-color: #e7e7e7;\n}\n.navbar-default .navbar-nav > .disabled > a,\n.navbar-default .navbar-nav > .disabled > a:hover,\n.navbar-default .navbar-nav > .disabled > a:focus {\n color: #cccccc;\n background-color: transparent;\n}\n.navbar-default .navbar-toggle {\n border-color: #dddddd;\n}\n.navbar-default .navbar-toggle:hover,\n.navbar-default .navbar-toggle:focus {\n background-color: #dddddd;\n}\n.navbar-default .navbar-toggle .icon-bar {\n background-color: #888888;\n}\n.navbar-default .navbar-collapse,\n.navbar-default .navbar-form {\n border-color: #e7e7e7;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n background-color: #e7e7e7;\n color: #555555;\n}\n@media (max-width: 767px) {\n .navbar-default .navbar-nav .open .dropdown-menu > li > a {\n color: #777777;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {\n color: #333333;\n background-color: transparent;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a,\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {\n color: #555555;\n background-color: #e7e7e7;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n color: #cccccc;\n background-color: transparent;\n }\n}\n.navbar-default .navbar-link {\n color: #777777;\n}\n.navbar-default .navbar-link:hover {\n color: #333333;\n}\n.navbar-default .btn-link {\n color: #777777;\n}\n.navbar-default .btn-link:hover,\n.navbar-default .btn-link:focus {\n color: #333333;\n}\n.navbar-default .btn-link[disabled]:hover,\nfieldset[disabled] .navbar-default .btn-link:hover,\n.navbar-default .btn-link[disabled]:focus,\nfieldset[disabled] .navbar-default .btn-link:focus {\n color: #cccccc;\n}\n.navbar-inverse {\n background-color: #222222;\n border-color: #080808;\n}\n.navbar-inverse .navbar-brand {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-brand:hover,\n.navbar-inverse .navbar-brand:focus {\n color: #ffffff;\n background-color: transparent;\n}\n.navbar-inverse .navbar-text {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-nav > li > a {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-nav > li > a:hover,\n.navbar-inverse .navbar-nav > li > a:focus {\n color: #ffffff;\n background-color: transparent;\n}\n.navbar-inverse .navbar-nav > .active > a,\n.navbar-inverse .navbar-nav > .active > a:hover,\n.navbar-inverse .navbar-nav > .active > a:focus {\n color: #ffffff;\n background-color: #080808;\n}\n.navbar-inverse .navbar-nav > .disabled > a,\n.navbar-inverse .navbar-nav > .disabled > a:hover,\n.navbar-inverse .navbar-nav > .disabled > a:focus {\n color: #444444;\n background-color: transparent;\n}\n.navbar-inverse .navbar-toggle {\n border-color: #333333;\n}\n.navbar-inverse .navbar-toggle:hover,\n.navbar-inverse .navbar-toggle:focus {\n background-color: #333333;\n}\n.navbar-inverse .navbar-toggle .icon-bar {\n background-color: #ffffff;\n}\n.navbar-inverse .navbar-collapse,\n.navbar-inverse .navbar-form {\n border-color: #101010;\n}\n.navbar-inverse .navbar-nav > .open > a,\n.navbar-inverse .navbar-nav > .open > a:hover,\n.navbar-inverse .navbar-nav > .open > a:focus {\n background-color: #080808;\n color: #ffffff;\n}\n@media (max-width: 767px) {\n .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {\n border-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu .divider {\n background-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {\n color: #9d9d9d;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {\n color: #ffffff;\n background-color: transparent;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {\n color: #ffffff;\n background-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n color: #444444;\n background-color: transparent;\n }\n}\n.navbar-inverse .navbar-link {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-link:hover {\n color: #ffffff;\n}\n.navbar-inverse .btn-link {\n color: #9d9d9d;\n}\n.navbar-inverse .btn-link:hover,\n.navbar-inverse .btn-link:focus {\n color: #ffffff;\n}\n.navbar-inverse .btn-link[disabled]:hover,\nfieldset[disabled] .navbar-inverse .btn-link:hover,\n.navbar-inverse .btn-link[disabled]:focus,\nfieldset[disabled] .navbar-inverse .btn-link:focus {\n color: #444444;\n}\n.breadcrumb {\n padding: 8px 15px;\n margin-bottom: 20px;\n list-style: none;\n background-color: #f5f5f5;\n border-radius: 4px;\n}\n.breadcrumb > li {\n display: inline-block;\n}\n.breadcrumb > li + li:before {\n content: \"/\\00a0\";\n padding: 0 5px;\n color: #cccccc;\n}\n.breadcrumb > .active {\n color: #777777;\n}\n.pagination {\n display: inline-block;\n padding-left: 0;\n margin: 20px 0;\n border-radius: 4px;\n}\n.pagination > li {\n display: inline;\n}\n.pagination > li > a,\n.pagination > li > span {\n position: relative;\n float: left;\n padding: 6px 12px;\n line-height: 1.42857143;\n text-decoration: none;\n color: #337ab7;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n margin-left: -1px;\n}\n.pagination > li:first-child > a,\n.pagination > li:first-child > span {\n margin-left: 0;\n border-bottom-left-radius: 4px;\n border-top-left-radius: 4px;\n}\n.pagination > li:last-child > a,\n.pagination > li:last-child > span {\n border-bottom-right-radius: 4px;\n border-top-right-radius: 4px;\n}\n.pagination > li > a:hover,\n.pagination > li > span:hover,\n.pagination > li > a:focus,\n.pagination > li > span:focus {\n color: #23527c;\n background-color: #eeeeee;\n border-color: #dddddd;\n}\n.pagination > .active > a,\n.pagination > .active > span,\n.pagination > .active > a:hover,\n.pagination > .active > span:hover,\n.pagination > .active > a:focus,\n.pagination > .active > span:focus {\n z-index: 2;\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n cursor: default;\n}\n.pagination > .disabled > span,\n.pagination > .disabled > span:hover,\n.pagination > .disabled > span:focus,\n.pagination > .disabled > a,\n.pagination > .disabled > a:hover,\n.pagination > .disabled > a:focus {\n color: #777777;\n background-color: #ffffff;\n border-color: #dddddd;\n cursor: not-allowed;\n}\n.pagination-lg > li > a,\n.pagination-lg > li > span {\n padding: 10px 16px;\n font-size: 18px;\n}\n.pagination-lg > li:first-child > a,\n.pagination-lg > li:first-child > span {\n border-bottom-left-radius: 6px;\n border-top-left-radius: 6px;\n}\n.pagination-lg > li:last-child > a,\n.pagination-lg > li:last-child > span {\n border-bottom-right-radius: 6px;\n border-top-right-radius: 6px;\n}\n.pagination-sm > li > a,\n.pagination-sm > li > span {\n padding: 5px 10px;\n font-size: 12px;\n}\n.pagination-sm > li:first-child > a,\n.pagination-sm > li:first-child > span {\n border-bottom-left-radius: 3px;\n border-top-left-radius: 3px;\n}\n.pagination-sm > li:last-child > a,\n.pagination-sm > li:last-child > span {\n border-bottom-right-radius: 3px;\n border-top-right-radius: 3px;\n}\n.pager {\n padding-left: 0;\n margin: 20px 0;\n list-style: none;\n text-align: center;\n}\n.pager li {\n display: inline;\n}\n.pager li > a,\n.pager li > span {\n display: inline-block;\n padding: 5px 14px;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 15px;\n}\n.pager li > a:hover,\n.pager li > a:focus {\n text-decoration: none;\n background-color: #eeeeee;\n}\n.pager .next > a,\n.pager .next > span {\n float: right;\n}\n.pager .previous > a,\n.pager .previous > span {\n float: left;\n}\n.pager .disabled > a,\n.pager .disabled > a:hover,\n.pager .disabled > a:focus,\n.pager .disabled > span {\n color: #777777;\n background-color: #ffffff;\n cursor: not-allowed;\n}\n.label {\n display: inline;\n padding: .2em .6em .3em;\n font-size: 75%;\n font-weight: bold;\n line-height: 1;\n color: #ffffff;\n text-align: center;\n white-space: nowrap;\n vertical-align: baseline;\n border-radius: .25em;\n}\na.label:hover,\na.label:focus {\n color: #ffffff;\n text-decoration: none;\n cursor: pointer;\n}\n.label:empty {\n display: none;\n}\n.btn .label {\n position: relative;\n top: -1px;\n}\n.label-default {\n background-color: #777777;\n}\n.label-default[href]:hover,\n.label-default[href]:focus {\n background-color: #5e5e5e;\n}\n.label-primary {\n background-color: #337ab7;\n}\n.label-primary[href]:hover,\n.label-primary[href]:focus {\n background-color: #286090;\n}\n.label-success {\n background-color: #5cb85c;\n}\n.label-success[href]:hover,\n.label-success[href]:focus {\n background-color: #449d44;\n}\n.label-info {\n background-color: #5bc0de;\n}\n.label-info[href]:hover,\n.label-info[href]:focus {\n background-color: #31b0d5;\n}\n.label-warning {\n background-color: #f0ad4e;\n}\n.label-warning[href]:hover,\n.label-warning[href]:focus {\n background-color: #ec971f;\n}\n.label-danger {\n background-color: #d9534f;\n}\n.label-danger[href]:hover,\n.label-danger[href]:focus {\n background-color: #c9302c;\n}\n.badge {\n display: inline-block;\n min-width: 10px;\n padding: 3px 7px;\n font-size: 12px;\n font-weight: bold;\n color: #ffffff;\n line-height: 1;\n vertical-align: baseline;\n white-space: nowrap;\n text-align: center;\n background-color: #777777;\n border-radius: 10px;\n}\n.badge:empty {\n display: none;\n}\n.btn .badge {\n position: relative;\n top: -1px;\n}\n.btn-xs .badge {\n top: 0;\n padding: 1px 5px;\n}\na.badge:hover,\na.badge:focus {\n color: #ffffff;\n text-decoration: none;\n cursor: pointer;\n}\n.list-group-item.active > .badge,\n.nav-pills > .active > a > .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.list-group-item > .badge {\n float: right;\n}\n.list-group-item > .badge + .badge {\n margin-right: 5px;\n}\n.nav-pills > li > a > .badge {\n margin-left: 3px;\n}\n.jumbotron {\n padding: 30px 15px;\n margin-bottom: 30px;\n color: inherit;\n background-color: #eeeeee;\n}\n.jumbotron h1,\n.jumbotron .h1 {\n color: inherit;\n}\n.jumbotron p {\n margin-bottom: 15px;\n font-size: 21px;\n font-weight: 200;\n}\n.jumbotron > hr {\n border-top-color: #d5d5d5;\n}\n.container .jumbotron,\n.container-fluid .jumbotron {\n border-radius: 6px;\n}\n.jumbotron .container {\n max-width: 100%;\n}\n@media screen and (min-width: 768px) {\n .jumbotron {\n padding: 48px 0;\n }\n .container .jumbotron,\n .container-fluid .jumbotron {\n padding-left: 60px;\n padding-right: 60px;\n }\n .jumbotron h1,\n .jumbotron .h1 {\n font-size: 63px;\n }\n}\n.thumbnail {\n display: block;\n padding: 4px;\n margin-bottom: 20px;\n line-height: 1.42857143;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 4px;\n -webkit-transition: border 0.2s ease-in-out;\n -o-transition: border 0.2s ease-in-out;\n transition: border 0.2s ease-in-out;\n}\n.thumbnail > img,\n.thumbnail a > img {\n margin-left: auto;\n margin-right: auto;\n}\na.thumbnail:hover,\na.thumbnail:focus,\na.thumbnail.active {\n border-color: #337ab7;\n}\n.thumbnail .caption {\n padding: 9px;\n color: #333333;\n}\n.alert {\n padding: 15px;\n margin-bottom: 20px;\n border: 1px solid transparent;\n border-radius: 4px;\n}\n.alert h4 {\n margin-top: 0;\n color: inherit;\n}\n.alert .alert-link {\n font-weight: bold;\n}\n.alert > p,\n.alert > ul {\n margin-bottom: 0;\n}\n.alert > p + p {\n margin-top: 5px;\n}\n.alert-dismissable,\n.alert-dismissible {\n padding-right: 35px;\n}\n.alert-dismissable .close,\n.alert-dismissible .close {\n position: relative;\n top: -2px;\n right: -21px;\n color: inherit;\n}\n.alert-success {\n background-color: #dff0d8;\n border-color: #d6e9c6;\n color: #3c763d;\n}\n.alert-success hr {\n border-top-color: #c9e2b3;\n}\n.alert-success .alert-link {\n color: #2b542c;\n}\n.alert-info {\n background-color: #d9edf7;\n border-color: #bce8f1;\n color: #31708f;\n}\n.alert-info hr {\n border-top-color: #a6e1ec;\n}\n.alert-info .alert-link {\n color: #245269;\n}\n.alert-warning {\n background-color: #fcf8e3;\n border-color: #faebcc;\n color: #8a6d3b;\n}\n.alert-warning hr {\n border-top-color: #f7e1b5;\n}\n.alert-warning .alert-link {\n color: #66512c;\n}\n.alert-danger {\n background-color: #f2dede;\n border-color: #ebccd1;\n color: #a94442;\n}\n.alert-danger hr {\n border-top-color: #e4b9c0;\n}\n.alert-danger .alert-link {\n color: #843534;\n}\n@-webkit-keyframes progress-bar-stripes {\n from {\n background-position: 40px 0;\n }\n to {\n background-position: 0 0;\n }\n}\n@keyframes progress-bar-stripes {\n from {\n background-position: 40px 0;\n }\n to {\n background-position: 0 0;\n }\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 20px;\n background-color: #f5f5f5;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n.progress-bar {\n float: left;\n width: 0%;\n height: 100%;\n font-size: 12px;\n line-height: 20px;\n color: #ffffff;\n text-align: center;\n background-color: #337ab7;\n -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n -webkit-transition: width 0.6s ease;\n -o-transition: width 0.6s ease;\n transition: width 0.6s ease;\n}\n.progress-striped .progress-bar,\n.progress-bar-striped {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-size: 40px 40px;\n}\n.progress.active .progress-bar,\n.progress-bar.active {\n -webkit-animation: progress-bar-stripes 2s linear infinite;\n -o-animation: progress-bar-stripes 2s linear infinite;\n animation: progress-bar-stripes 2s linear infinite;\n}\n.progress-bar-success {\n background-color: #5cb85c;\n}\n.progress-striped .progress-bar-success {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-info {\n background-color: #5bc0de;\n}\n.progress-striped .progress-bar-info {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-warning {\n background-color: #f0ad4e;\n}\n.progress-striped .progress-bar-warning {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-danger {\n background-color: #d9534f;\n}\n.progress-striped .progress-bar-danger {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.media {\n margin-top: 15px;\n}\n.media:first-child {\n margin-top: 0;\n}\n.media,\n.media-body {\n zoom: 1;\n overflow: hidden;\n}\n.media-body {\n width: 10000px;\n}\n.media-object {\n display: block;\n}\n.media-right,\n.media > .pull-right {\n padding-left: 10px;\n}\n.media-left,\n.media > .pull-left {\n padding-right: 10px;\n}\n.media-left,\n.media-right,\n.media-body {\n display: table-cell;\n vertical-align: top;\n}\n.media-middle {\n vertical-align: middle;\n}\n.media-bottom {\n vertical-align: bottom;\n}\n.media-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.media-list {\n padding-left: 0;\n list-style: none;\n}\n.list-group {\n margin-bottom: 20px;\n padding-left: 0;\n}\n.list-group-item {\n position: relative;\n display: block;\n padding: 10px 15px;\n margin-bottom: -1px;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n}\n.list-group-item:first-child {\n border-top-right-radius: 4px;\n border-top-left-radius: 4px;\n}\n.list-group-item:last-child {\n margin-bottom: 0;\n border-bottom-right-radius: 4px;\n border-bottom-left-radius: 4px;\n}\na.list-group-item {\n color: #555555;\n}\na.list-group-item .list-group-item-heading {\n color: #333333;\n}\na.list-group-item:hover,\na.list-group-item:focus {\n text-decoration: none;\n color: #555555;\n background-color: #f5f5f5;\n}\n.list-group-item.disabled,\n.list-group-item.disabled:hover,\n.list-group-item.disabled:focus {\n background-color: #eeeeee;\n color: #777777;\n cursor: not-allowed;\n}\n.list-group-item.disabled .list-group-item-heading,\n.list-group-item.disabled:hover .list-group-item-heading,\n.list-group-item.disabled:focus .list-group-item-heading {\n color: inherit;\n}\n.list-group-item.disabled .list-group-item-text,\n.list-group-item.disabled:hover .list-group-item-text,\n.list-group-item.disabled:focus .list-group-item-text {\n color: #777777;\n}\n.list-group-item.active,\n.list-group-item.active:hover,\n.list-group-item.active:focus {\n z-index: 2;\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n}\n.list-group-item.active .list-group-item-heading,\n.list-group-item.active:hover .list-group-item-heading,\n.list-group-item.active:focus .list-group-item-heading,\n.list-group-item.active .list-group-item-heading > small,\n.list-group-item.active:hover .list-group-item-heading > small,\n.list-group-item.active:focus .list-group-item-heading > small,\n.list-group-item.active .list-group-item-heading > .small,\n.list-group-item.active:hover .list-group-item-heading > .small,\n.list-group-item.active:focus .list-group-item-heading > .small {\n color: inherit;\n}\n.list-group-item.active .list-group-item-text,\n.list-group-item.active:hover .list-group-item-text,\n.list-group-item.active:focus .list-group-item-text {\n color: #c7ddef;\n}\n.list-group-item-success {\n color: #3c763d;\n background-color: #dff0d8;\n}\na.list-group-item-success {\n color: #3c763d;\n}\na.list-group-item-success .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-success:hover,\na.list-group-item-success:focus {\n color: #3c763d;\n background-color: #d0e9c6;\n}\na.list-group-item-success.active,\na.list-group-item-success.active:hover,\na.list-group-item-success.active:focus {\n color: #fff;\n background-color: #3c763d;\n border-color: #3c763d;\n}\n.list-group-item-info {\n color: #31708f;\n background-color: #d9edf7;\n}\na.list-group-item-info {\n color: #31708f;\n}\na.list-group-item-info .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-info:hover,\na.list-group-item-info:focus {\n color: #31708f;\n background-color: #c4e3f3;\n}\na.list-group-item-info.active,\na.list-group-item-info.active:hover,\na.list-group-item-info.active:focus {\n color: #fff;\n background-color: #31708f;\n border-color: #31708f;\n}\n.list-group-item-warning {\n color: #8a6d3b;\n background-color: #fcf8e3;\n}\na.list-group-item-warning {\n color: #8a6d3b;\n}\na.list-group-item-warning .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-warning:hover,\na.list-group-item-warning:focus {\n color: #8a6d3b;\n background-color: #faf2cc;\n}\na.list-group-item-warning.active,\na.list-group-item-warning.active:hover,\na.list-group-item-warning.active:focus {\n color: #fff;\n background-color: #8a6d3b;\n border-color: #8a6d3b;\n}\n.list-group-item-danger {\n color: #a94442;\n background-color: #f2dede;\n}\na.list-group-item-danger {\n color: #a94442;\n}\na.list-group-item-danger .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-danger:hover,\na.list-group-item-danger:focus {\n color: #a94442;\n background-color: #ebcccc;\n}\na.list-group-item-danger.active,\na.list-group-item-danger.active:hover,\na.list-group-item-danger.active:focus {\n color: #fff;\n background-color: #a94442;\n border-color: #a94442;\n}\n.list-group-item-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.list-group-item-text {\n margin-bottom: 0;\n line-height: 1.3;\n}\n.panel {\n margin-bottom: 20px;\n background-color: #ffffff;\n border: 1px solid transparent;\n border-radius: 4px;\n -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n.panel-body {\n padding: 15px;\n}\n.panel-heading {\n padding: 10px 15px;\n border-bottom: 1px solid transparent;\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel-heading > .dropdown .dropdown-toggle {\n color: inherit;\n}\n.panel-title {\n margin-top: 0;\n margin-bottom: 0;\n font-size: 16px;\n color: inherit;\n}\n.panel-title > a,\n.panel-title > small,\n.panel-title > .small,\n.panel-title > small > a,\n.panel-title > .small > a {\n color: inherit;\n}\n.panel-footer {\n padding: 10px 15px;\n background-color: #f5f5f5;\n border-top: 1px solid #dddddd;\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel > .list-group,\n.panel > .panel-collapse > .list-group {\n margin-bottom: 0;\n}\n.panel > .list-group .list-group-item,\n.panel > .panel-collapse > .list-group .list-group-item {\n border-width: 1px 0;\n border-radius: 0;\n}\n.panel > .list-group:first-child .list-group-item:first-child,\n.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {\n border-top: 0;\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel > .list-group:last-child .list-group-item:last-child,\n.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {\n border-bottom: 0;\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel-heading + .list-group .list-group-item:first-child {\n border-top-width: 0;\n}\n.list-group + .panel-footer {\n border-top-width: 0;\n}\n.panel > .table,\n.panel > .table-responsive > .table,\n.panel > .panel-collapse > .table {\n margin-bottom: 0;\n}\n.panel > .table caption,\n.panel > .table-responsive > .table caption,\n.panel > .panel-collapse > .table caption {\n padding-left: 15px;\n padding-right: 15px;\n}\n.panel > .table:first-child,\n.panel > .table-responsive:first-child > .table:first-child {\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {\n border-top-left-radius: 3px;\n border-top-right-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,\n.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {\n border-top-left-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,\n.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {\n border-top-right-radius: 3px;\n}\n.panel > .table:last-child,\n.panel > .table-responsive:last-child > .table:last-child {\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {\n border-bottom-left-radius: 3px;\n border-bottom-right-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,\n.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {\n border-bottom-left-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,\n.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {\n border-bottom-right-radius: 3px;\n}\n.panel > .panel-body + .table,\n.panel > .panel-body + .table-responsive,\n.panel > .table + .panel-body,\n.panel > .table-responsive + .panel-body {\n border-top: 1px solid #dddddd;\n}\n.panel > .table > tbody:first-child > tr:first-child th,\n.panel > .table > tbody:first-child > tr:first-child td {\n border-top: 0;\n}\n.panel > .table-bordered,\n.panel > .table-responsive > .table-bordered {\n border: 0;\n}\n.panel > .table-bordered > thead > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,\n.panel > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-bordered > thead > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,\n.panel > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-bordered > tfoot > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n border-left: 0;\n}\n.panel > .table-bordered > thead > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,\n.panel > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-bordered > thead > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,\n.panel > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-bordered > tfoot > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n border-right: 0;\n}\n.panel > .table-bordered > thead > tr:first-child > td,\n.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,\n.panel > .table-bordered > tbody > tr:first-child > td,\n.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,\n.panel > .table-bordered > thead > tr:first-child > th,\n.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,\n.panel > .table-bordered > tbody > tr:first-child > th,\n.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {\n border-bottom: 0;\n}\n.panel > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-bordered > tfoot > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,\n.panel > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-bordered > tfoot > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {\n border-bottom: 0;\n}\n.panel > .table-responsive {\n border: 0;\n margin-bottom: 0;\n}\n.panel-group {\n margin-bottom: 20px;\n}\n.panel-group .panel {\n margin-bottom: 0;\n border-radius: 4px;\n}\n.panel-group .panel + .panel {\n margin-top: 5px;\n}\n.panel-group .panel-heading {\n border-bottom: 0;\n}\n.panel-group .panel-heading + .panel-collapse > .panel-body,\n.panel-group .panel-heading + .panel-collapse > .list-group {\n border-top: 1px solid #dddddd;\n}\n.panel-group .panel-footer {\n border-top: 0;\n}\n.panel-group .panel-footer + .panel-collapse .panel-body {\n border-bottom: 1px solid #dddddd;\n}\n.panel-default {\n border-color: #dddddd;\n}\n.panel-default > .panel-heading {\n color: #333333;\n background-color: #f5f5f5;\n border-color: #dddddd;\n}\n.panel-default > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #dddddd;\n}\n.panel-default > .panel-heading .badge {\n color: #f5f5f5;\n background-color: #333333;\n}\n.panel-default > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #dddddd;\n}\n.panel-primary {\n border-color: #337ab7;\n}\n.panel-primary > .panel-heading {\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n}\n.panel-primary > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #337ab7;\n}\n.panel-primary > .panel-heading .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.panel-primary > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #337ab7;\n}\n.panel-success {\n border-color: #d6e9c6;\n}\n.panel-success > .panel-heading {\n color: #3c763d;\n background-color: #dff0d8;\n border-color: #d6e9c6;\n}\n.panel-success > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #d6e9c6;\n}\n.panel-success > .panel-heading .badge {\n color: #dff0d8;\n background-color: #3c763d;\n}\n.panel-success > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #d6e9c6;\n}\n.panel-info {\n border-color: #bce8f1;\n}\n.panel-info > .panel-heading {\n color: #31708f;\n background-color: #d9edf7;\n border-color: #bce8f1;\n}\n.panel-info > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #bce8f1;\n}\n.panel-info > .panel-heading .badge {\n color: #d9edf7;\n background-color: #31708f;\n}\n.panel-info > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #bce8f1;\n}\n.panel-warning {\n border-color: #faebcc;\n}\n.panel-warning > .panel-heading {\n color: #8a6d3b;\n background-color: #fcf8e3;\n border-color: #faebcc;\n}\n.panel-warning > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #faebcc;\n}\n.panel-warning > .panel-heading .badge {\n color: #fcf8e3;\n background-color: #8a6d3b;\n}\n.panel-warning > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #faebcc;\n}\n.panel-danger {\n border-color: #ebccd1;\n}\n.panel-danger > .panel-heading {\n color: #a94442;\n background-color: #f2dede;\n border-color: #ebccd1;\n}\n.panel-danger > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #ebccd1;\n}\n.panel-danger > .panel-heading .badge {\n color: #f2dede;\n background-color: #a94442;\n}\n.panel-danger > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #ebccd1;\n}\n.embed-responsive {\n position: relative;\n display: block;\n height: 0;\n padding: 0;\n overflow: hidden;\n}\n.embed-responsive .embed-responsive-item,\n.embed-responsive iframe,\n.embed-responsive embed,\n.embed-responsive object,\n.embed-responsive video {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n height: 100%;\n width: 100%;\n border: 0;\n}\n.embed-responsive.embed-responsive-16by9 {\n padding-bottom: 56.25%;\n}\n.embed-responsive.embed-responsive-4by3 {\n padding-bottom: 75%;\n}\n.well {\n min-height: 20px;\n padding: 19px;\n margin-bottom: 20px;\n background-color: #f5f5f5;\n border: 1px solid #e3e3e3;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n.well blockquote {\n border-color: #ddd;\n border-color: rgba(0, 0, 0, 0.15);\n}\n.well-lg {\n padding: 24px;\n border-radius: 6px;\n}\n.well-sm {\n padding: 9px;\n border-radius: 3px;\n}\n.close {\n float: right;\n font-size: 21px;\n font-weight: bold;\n line-height: 1;\n color: #000000;\n text-shadow: 0 1px 0 #ffffff;\n opacity: 0.2;\n filter: alpha(opacity=20);\n}\n.close:hover,\n.close:focus {\n color: #000000;\n text-decoration: none;\n cursor: pointer;\n opacity: 0.5;\n filter: alpha(opacity=50);\n}\nbutton.close {\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: 0;\n -webkit-appearance: none;\n}\n.modal-open {\n overflow: hidden;\n}\n.modal {\n display: none;\n overflow: hidden;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1040;\n -webkit-overflow-scrolling: touch;\n outline: 0;\n}\n.modal.fade .modal-dialog {\n -webkit-transform: translate(0, -25%);\n -ms-transform: translate(0, -25%);\n -o-transform: translate(0, -25%);\n transform: translate(0, -25%);\n -webkit-transition: -webkit-transform 0.3s ease-out;\n -moz-transition: -moz-transform 0.3s ease-out;\n -o-transition: -o-transform 0.3s ease-out;\n transition: transform 0.3s ease-out;\n}\n.modal.in .modal-dialog {\n -webkit-transform: translate(0, 0);\n -ms-transform: translate(0, 0);\n -o-transform: translate(0, 0);\n transform: translate(0, 0);\n}\n.modal-open .modal {\n overflow-x: hidden;\n overflow-y: auto;\n}\n.modal-dialog {\n position: relative;\n width: auto;\n margin: 10px;\n}\n.modal-content {\n position: relative;\n background-color: #ffffff;\n border: 1px solid #999999;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 6px;\n -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n background-clip: padding-box;\n outline: 0;\n}\n.modal-backdrop {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n background-color: #000000;\n}\n.modal-backdrop.fade {\n opacity: 0;\n filter: alpha(opacity=0);\n}\n.modal-backdrop.in {\n opacity: 0.5;\n filter: alpha(opacity=50);\n}\n.modal-header {\n padding: 15px;\n border-bottom: 1px solid #e5e5e5;\n min-height: 16.42857143px;\n}\n.modal-header .close {\n margin-top: -2px;\n}\n.modal-title {\n margin: 0;\n line-height: 1.42857143;\n}\n.modal-body {\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 15px;\n text-align: right;\n border-top: 1px solid #e5e5e5;\n}\n.modal-footer .btn + .btn {\n margin-left: 5px;\n margin-bottom: 0;\n}\n.modal-footer .btn-group .btn + .btn {\n margin-left: -1px;\n}\n.modal-footer .btn-block + .btn-block {\n margin-left: 0;\n}\n.modal-scrollbar-measure {\n position: absolute;\n top: -9999px;\n width: 50px;\n height: 50px;\n overflow: scroll;\n}\n@media (min-width: 768px) {\n .modal-dialog {\n width: 600px;\n margin: 30px auto;\n }\n .modal-content {\n -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n }\n .modal-sm {\n width: 300px;\n }\n}\n@media (min-width: 992px) {\n .modal-lg {\n width: 900px;\n }\n}\n.tooltip {\n position: absolute;\n z-index: 1070;\n display: block;\n visibility: visible;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 12px;\n font-weight: normal;\n line-height: 1.4;\n opacity: 0;\n filter: alpha(opacity=0);\n}\n.tooltip.in {\n opacity: 0.9;\n filter: alpha(opacity=90);\n}\n.tooltip.top {\n margin-top: -3px;\n padding: 5px 0;\n}\n.tooltip.right {\n margin-left: 3px;\n padding: 0 5px;\n}\n.tooltip.bottom {\n margin-top: 3px;\n padding: 5px 0;\n}\n.tooltip.left {\n margin-left: -3px;\n padding: 0 5px;\n}\n.tooltip-inner {\n max-width: 200px;\n padding: 3px 8px;\n color: #ffffff;\n text-align: center;\n text-decoration: none;\n background-color: #000000;\n border-radius: 4px;\n}\n.tooltip-arrow {\n position: absolute;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n.tooltip.top .tooltip-arrow {\n bottom: 0;\n left: 50%;\n margin-left: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.top-left .tooltip-arrow {\n bottom: 0;\n right: 5px;\n margin-bottom: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.top-right .tooltip-arrow {\n bottom: 0;\n left: 5px;\n margin-bottom: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.right .tooltip-arrow {\n top: 50%;\n left: 0;\n margin-top: -5px;\n border-width: 5px 5px 5px 0;\n border-right-color: #000000;\n}\n.tooltip.left .tooltip-arrow {\n top: 50%;\n right: 0;\n margin-top: -5px;\n border-width: 5px 0 5px 5px;\n border-left-color: #000000;\n}\n.tooltip.bottom .tooltip-arrow {\n top: 0;\n left: 50%;\n margin-left: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.tooltip.bottom-left .tooltip-arrow {\n top: 0;\n right: 5px;\n margin-top: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.tooltip.bottom-right .tooltip-arrow {\n top: 0;\n left: 5px;\n margin-top: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.popover {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1060;\n display: none;\n max-width: 276px;\n padding: 1px;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 14px;\n font-weight: normal;\n line-height: 1.42857143;\n text-align: left;\n background-color: #ffffff;\n background-clip: padding-box;\n border: 1px solid #cccccc;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 6px;\n -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n white-space: normal;\n}\n.popover.top {\n margin-top: -10px;\n}\n.popover.right {\n margin-left: 10px;\n}\n.popover.bottom {\n margin-top: 10px;\n}\n.popover.left {\n margin-left: -10px;\n}\n.popover-title {\n margin: 0;\n padding: 8px 14px;\n font-size: 14px;\n background-color: #f7f7f7;\n border-bottom: 1px solid #ebebeb;\n border-radius: 5px 5px 0 0;\n}\n.popover-content {\n padding: 9px 14px;\n}\n.popover > .arrow,\n.popover > .arrow:after {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n.popover > .arrow {\n border-width: 11px;\n}\n.popover > .arrow:after {\n border-width: 10px;\n content: \"\";\n}\n.popover.top > .arrow {\n left: 50%;\n margin-left: -11px;\n border-bottom-width: 0;\n border-top-color: #999999;\n border-top-color: rgba(0, 0, 0, 0.25);\n bottom: -11px;\n}\n.popover.top > .arrow:after {\n content: \" \";\n bottom: 1px;\n margin-left: -10px;\n border-bottom-width: 0;\n border-top-color: #ffffff;\n}\n.popover.right > .arrow {\n top: 50%;\n left: -11px;\n margin-top: -11px;\n border-left-width: 0;\n border-right-color: #999999;\n border-right-color: rgba(0, 0, 0, 0.25);\n}\n.popover.right > .arrow:after {\n content: \" \";\n left: 1px;\n bottom: -10px;\n border-left-width: 0;\n border-right-color: #ffffff;\n}\n.popover.bottom > .arrow {\n left: 50%;\n margin-left: -11px;\n border-top-width: 0;\n border-bottom-color: #999999;\n border-bottom-color: rgba(0, 0, 0, 0.25);\n top: -11px;\n}\n.popover.bottom > .arrow:after {\n content: \" \";\n top: 1px;\n margin-left: -10px;\n border-top-width: 0;\n border-bottom-color: #ffffff;\n}\n.popover.left > .arrow {\n top: 50%;\n right: -11px;\n margin-top: -11px;\n border-right-width: 0;\n border-left-color: #999999;\n border-left-color: rgba(0, 0, 0, 0.25);\n}\n.popover.left > .arrow:after {\n content: \" \";\n right: 1px;\n border-right-width: 0;\n border-left-color: #ffffff;\n bottom: -10px;\n}\n.carousel {\n position: relative;\n}\n.carousel-inner {\n position: relative;\n overflow: hidden;\n width: 100%;\n}\n.carousel-inner > .item {\n display: none;\n position: relative;\n -webkit-transition: 0.6s ease-in-out left;\n -o-transition: 0.6s ease-in-out left;\n transition: 0.6s ease-in-out left;\n}\n.carousel-inner > .item > img,\n.carousel-inner > .item > a > img {\n line-height: 1;\n}\n@media all and (transform-3d), (-webkit-transform-3d) {\n .carousel-inner > .item {\n -webkit-transition: -webkit-transform 0.6s ease-in-out;\n -moz-transition: -moz-transform 0.6s ease-in-out;\n -o-transition: -o-transform 0.6s ease-in-out;\n transition: transform 0.6s ease-in-out;\n -webkit-backface-visibility: hidden;\n -moz-backface-visibility: hidden;\n backface-visibility: hidden;\n -webkit-perspective: 1000;\n -moz-perspective: 1000;\n perspective: 1000;\n }\n .carousel-inner > .item.next,\n .carousel-inner > .item.active.right {\n -webkit-transform: translate3d(100%, 0, 0);\n transform: translate3d(100%, 0, 0);\n left: 0;\n }\n .carousel-inner > .item.prev,\n .carousel-inner > .item.active.left {\n -webkit-transform: translate3d(-100%, 0, 0);\n transform: translate3d(-100%, 0, 0);\n left: 0;\n }\n .carousel-inner > .item.next.left,\n .carousel-inner > .item.prev.right,\n .carousel-inner > .item.active {\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n left: 0;\n }\n}\n.carousel-inner > .active,\n.carousel-inner > .next,\n.carousel-inner > .prev {\n display: block;\n}\n.carousel-inner > .active {\n left: 0;\n}\n.carousel-inner > .next,\n.carousel-inner > .prev {\n position: absolute;\n top: 0;\n width: 100%;\n}\n.carousel-inner > .next {\n left: 100%;\n}\n.carousel-inner > .prev {\n left: -100%;\n}\n.carousel-inner > .next.left,\n.carousel-inner > .prev.right {\n left: 0;\n}\n.carousel-inner > .active.left {\n left: -100%;\n}\n.carousel-inner > .active.right {\n left: 100%;\n}\n.carousel-control {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n width: 15%;\n opacity: 0.5;\n filter: alpha(opacity=50);\n font-size: 20px;\n color: #ffffff;\n text-align: center;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n}\n.carousel-control.left {\n background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);\n}\n.carousel-control.right {\n left: auto;\n right: 0;\n background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);\n}\n.carousel-control:hover,\n.carousel-control:focus {\n outline: 0;\n color: #ffffff;\n text-decoration: none;\n opacity: 0.9;\n filter: alpha(opacity=90);\n}\n.carousel-control .icon-prev,\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-left,\n.carousel-control .glyphicon-chevron-right {\n position: absolute;\n top: 50%;\n z-index: 5;\n display: inline-block;\n}\n.carousel-control .icon-prev,\n.carousel-control .glyphicon-chevron-left {\n left: 50%;\n margin-left: -10px;\n}\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-right {\n right: 50%;\n margin-right: -10px;\n}\n.carousel-control .icon-prev,\n.carousel-control .icon-next {\n width: 20px;\n height: 20px;\n margin-top: -10px;\n line-height: 1;\n font-family: serif;\n}\n.carousel-control .icon-prev:before {\n content: '\\2039';\n}\n.carousel-control .icon-next:before {\n content: '\\203a';\n}\n.carousel-indicators {\n position: absolute;\n bottom: 10px;\n left: 50%;\n z-index: 15;\n width: 60%;\n margin-left: -30%;\n padding-left: 0;\n list-style: none;\n text-align: center;\n}\n.carousel-indicators li {\n display: inline-block;\n width: 10px;\n height: 10px;\n margin: 1px;\n text-indent: -999px;\n border: 1px solid #ffffff;\n border-radius: 10px;\n cursor: pointer;\n background-color: #000 \\9;\n background-color: rgba(0, 0, 0, 0);\n}\n.carousel-indicators .active {\n margin: 0;\n width: 12px;\n height: 12px;\n background-color: #ffffff;\n}\n.carousel-caption {\n position: absolute;\n left: 15%;\n right: 15%;\n bottom: 20px;\n z-index: 10;\n padding-top: 20px;\n padding-bottom: 20px;\n color: #ffffff;\n text-align: center;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n}\n.carousel-caption .btn {\n text-shadow: none;\n}\n@media screen and (min-width: 768px) {\n .carousel-control .glyphicon-chevron-left,\n .carousel-control .glyphicon-chevron-right,\n .carousel-control .icon-prev,\n .carousel-control .icon-next {\n width: 30px;\n height: 30px;\n margin-top: -15px;\n font-size: 30px;\n }\n .carousel-control .glyphicon-chevron-left,\n .carousel-control .icon-prev {\n margin-left: -15px;\n }\n .carousel-control .glyphicon-chevron-right,\n .carousel-control .icon-next {\n margin-right: -15px;\n }\n .carousel-caption {\n left: 20%;\n right: 20%;\n padding-bottom: 30px;\n }\n .carousel-indicators {\n bottom: 20px;\n }\n}\n.clearfix:before,\n.clearfix:after,\n.dl-horizontal dd:before,\n.dl-horizontal dd:after,\n.container:before,\n.container:after,\n.container-fluid:before,\n.container-fluid:after,\n.row:before,\n.row:after,\n.form-horizontal .form-group:before,\n.form-horizontal .form-group:after,\n.btn-toolbar:before,\n.btn-toolbar:after,\n.btn-group-vertical > .btn-group:before,\n.btn-group-vertical > .btn-group:after,\n.nav:before,\n.nav:after,\n.navbar:before,\n.navbar:after,\n.navbar-header:before,\n.navbar-header:after,\n.navbar-collapse:before,\n.navbar-collapse:after,\n.pager:before,\n.pager:after,\n.panel-body:before,\n.panel-body:after,\n.modal-footer:before,\n.modal-footer:after {\n content: \" \";\n display: table;\n}\n.clearfix:after,\n.dl-horizontal dd:after,\n.container:after,\n.container-fluid:after,\n.row:after,\n.form-horizontal .form-group:after,\n.btn-toolbar:after,\n.btn-group-vertical > .btn-group:after,\n.nav:after,\n.navbar:after,\n.navbar-header:after,\n.navbar-collapse:after,\n.pager:after,\n.panel-body:after,\n.modal-footer:after {\n clear: both;\n}\n.center-block {\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n.pull-right {\n float: right !important;\n}\n.pull-left {\n float: left !important;\n}\n.hide {\n display: none !important;\n}\n.show {\n display: block !important;\n}\n.invisible {\n visibility: hidden;\n}\n.text-hide {\n font: 0/0 a;\n color: transparent;\n text-shadow: none;\n background-color: transparent;\n border: 0;\n}\n.hidden {\n display: none !important;\n visibility: hidden !important;\n}\n.affix {\n position: fixed;\n}\n@-ms-viewport {\n width: device-width;\n}\n.visible-xs,\n.visible-sm,\n.visible-md,\n.visible-lg {\n display: none !important;\n}\n.visible-xs-block,\n.visible-xs-inline,\n.visible-xs-inline-block,\n.visible-sm-block,\n.visible-sm-inline,\n.visible-sm-inline-block,\n.visible-md-block,\n.visible-md-inline,\n.visible-md-inline-block,\n.visible-lg-block,\n.visible-lg-inline,\n.visible-lg-inline-block {\n display: none !important;\n}\n@media (max-width: 767px) {\n .visible-xs {\n display: block !important;\n }\n table.visible-xs {\n display: table;\n }\n tr.visible-xs {\n display: table-row !important;\n }\n th.visible-xs,\n td.visible-xs {\n display: table-cell !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-block {\n display: block !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-inline {\n display: inline !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm {\n display: block !important;\n }\n table.visible-sm {\n display: table;\n }\n tr.visible-sm {\n display: table-row !important;\n }\n th.visible-sm,\n td.visible-sm {\n display: table-cell !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-block {\n display: block !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-inline {\n display: inline !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md {\n display: block !important;\n }\n table.visible-md {\n display: table;\n }\n tr.visible-md {\n display: table-row !important;\n }\n th.visible-md,\n td.visible-md {\n display: table-cell !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-block {\n display: block !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-inline {\n display: inline !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg {\n display: block !important;\n }\n table.visible-lg {\n display: table;\n }\n tr.visible-lg {\n display: table-row !important;\n }\n th.visible-lg,\n td.visible-lg {\n display: table-cell !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-block {\n display: block !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-inline {\n display: inline !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-inline-block {\n display: inline-block !important;\n }\n}\n@media (max-width: 767px) {\n .hidden-xs {\n display: none !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .hidden-sm {\n display: none !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .hidden-md {\n display: none !important;\n }\n}\n@media (min-width: 1200px) {\n .hidden-lg {\n display: none !important;\n }\n}\n.visible-print {\n display: none !important;\n}\n@media print {\n .visible-print {\n display: block !important;\n }\n table.visible-print {\n display: table;\n }\n tr.visible-print {\n display: table-row !important;\n }\n th.visible-print,\n td.visible-print {\n display: table-cell !important;\n }\n}\n.visible-print-block {\n display: none !important;\n}\n@media print {\n .visible-print-block {\n display: block !important;\n }\n}\n.visible-print-inline {\n display: none !important;\n}\n@media print {\n .visible-print-inline {\n display: inline !important;\n }\n}\n.visible-print-inline-block {\n display: none !important;\n}\n@media print {\n .visible-print-inline-block {\n display: inline-block !important;\n }\n}\n@media print {\n .hidden-print {\n display: none !important;\n }\n}\n/*# sourceMappingURL=bootstrap.css.map */","/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\n\n//\n// 1. Set default font family to sans-serif.\n// 2. Prevent iOS text size adjust after orientation change, without disabling\n// user zoom.\n//\n\nhtml {\n font-family: sans-serif; // 1\n -ms-text-size-adjust: 100%; // 2\n -webkit-text-size-adjust: 100%; // 2\n}\n\n//\n// Remove default margin.\n//\n\nbody {\n margin: 0;\n}\n\n// HTML5 display definitions\n// ==========================================================================\n\n//\n// Correct `block` display not defined for any HTML5 element in IE 8/9.\n// Correct `block` display not defined for `details` or `summary` in IE 10/11\n// and Firefox.\n// Correct `block` display not defined for `main` in IE 11.\n//\n\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmain,\nmenu,\nnav,\nsection,\nsummary {\n display: block;\n}\n\n//\n// 1. Correct `inline-block` display not defined in IE 8/9.\n// 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.\n//\n\naudio,\ncanvas,\nprogress,\nvideo {\n display: inline-block; // 1\n vertical-align: baseline; // 2\n}\n\n//\n// Prevent modern browsers from displaying `audio` without controls.\n// Remove excess height in iOS 5 devices.\n//\n\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n\n//\n// Address `[hidden]` styling not present in IE 8/9/10.\n// Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.\n//\n\n[hidden],\ntemplate {\n display: none;\n}\n\n// Links\n// ==========================================================================\n\n//\n// Remove the gray background color from active links in IE 10.\n//\n\na {\n background-color: transparent;\n}\n\n//\n// Improve readability when focused and also mouse hovered in all browsers.\n//\n\na:active,\na:hover {\n outline: 0;\n}\n\n// Text-level semantics\n// ==========================================================================\n\n//\n// Address styling not present in IE 8/9/10/11, Safari, and Chrome.\n//\n\nabbr[title] {\n border-bottom: 1px dotted;\n}\n\n//\n// Address style set to `bolder` in Firefox 4+, Safari, and Chrome.\n//\n\nb,\nstrong {\n font-weight: bold;\n}\n\n//\n// Address styling not present in Safari and Chrome.\n//\n\ndfn {\n font-style: italic;\n}\n\n//\n// Address variable `h1` font-size and margin within `section` and `article`\n// contexts in Firefox 4+, Safari, and Chrome.\n//\n\nh1 {\n font-size: 2em;\n margin: 0.67em 0;\n}\n\n//\n// Address styling not present in IE 8/9.\n//\n\nmark {\n background: #ff0;\n color: #000;\n}\n\n//\n// Address inconsistent and variable font size in all browsers.\n//\n\nsmall {\n font-size: 80%;\n}\n\n//\n// Prevent `sub` and `sup` affecting `line-height` in all browsers.\n//\n\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\n\nsup {\n top: -0.5em;\n}\n\nsub {\n bottom: -0.25em;\n}\n\n// Embedded content\n// ==========================================================================\n\n//\n// Remove border when inside `a` element in IE 8/9/10.\n//\n\nimg {\n border: 0;\n}\n\n//\n// Correct overflow not hidden in IE 9/10/11.\n//\n\nsvg:not(:root) {\n overflow: hidden;\n}\n\n// Grouping content\n// ==========================================================================\n\n//\n// Address margin not present in IE 8/9 and Safari.\n//\n\nfigure {\n margin: 1em 40px;\n}\n\n//\n// Address differences between Firefox and other browsers.\n//\n\nhr {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n height: 0;\n}\n\n//\n// Contain overflow in all browsers.\n//\n\npre {\n overflow: auto;\n}\n\n//\n// Address odd `em`-unit font size rendering in all browsers.\n//\n\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, monospace;\n font-size: 1em;\n}\n\n// Forms\n// ==========================================================================\n\n//\n// Known limitation: by default, Chrome and Safari on OS X allow very limited\n// styling of `select`, unless a `border` property is set.\n//\n\n//\n// 1. Correct color not being inherited.\n// Known issue: affects color of disabled elements.\n// 2. Correct font properties not being inherited.\n// 3. Address margins set differently in Firefox 4+, Safari, and Chrome.\n//\n\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n color: inherit; // 1\n font: inherit; // 2\n margin: 0; // 3\n}\n\n//\n// Address `overflow` set to `hidden` in IE 8/9/10/11.\n//\n\nbutton {\n overflow: visible;\n}\n\n//\n// Address inconsistent `text-transform` inheritance for `button` and `select`.\n// All other form control elements do not inherit `text-transform` values.\n// Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.\n// Correct `select` style inheritance in Firefox.\n//\n\nbutton,\nselect {\n text-transform: none;\n}\n\n//\n// 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`\n// and `video` controls.\n// 2. Correct inability to style clickable `input` types in iOS.\n// 3. Improve usability and consistency of cursor style between image-type\n// `input` and others.\n//\n\nbutton,\nhtml input[type=\"button\"], // 1\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button; // 2\n cursor: pointer; // 3\n}\n\n//\n// Re-set default cursor for disabled elements.\n//\n\nbutton[disabled],\nhtml input[disabled] {\n cursor: default;\n}\n\n//\n// Remove inner padding and border in Firefox 4+.\n//\n\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\n\n//\n// Address Firefox 4+ setting `line-height` on `input` using `!important` in\n// the UA stylesheet.\n//\n\ninput {\n line-height: normal;\n}\n\n//\n// It's recommended that you don't attempt to style these elements.\n// Firefox's implementation doesn't respect box-sizing, padding, or width.\n//\n// 1. Address box sizing set to `content-box` in IE 8/9/10.\n// 2. Remove excess padding in IE 8/9/10.\n//\n\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box; // 1\n padding: 0; // 2\n}\n\n//\n// Fix the cursor style for Chrome's increment/decrement buttons. For certain\n// `font-size` values of the `input`, it causes the cursor style of the\n// decrement button to change from `default` to `text`.\n//\n\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n height: auto;\n}\n\n//\n// 1. Address `appearance` set to `searchfield` in Safari and Chrome.\n// 2. Address `box-sizing` set to `border-box` in Safari and Chrome\n// (include `-moz` to future-proof).\n//\n\ninput[type=\"search\"] {\n -webkit-appearance: textfield; // 1\n -moz-box-sizing: content-box;\n -webkit-box-sizing: content-box; // 2\n box-sizing: content-box;\n}\n\n//\n// Remove inner padding and search cancel button in Safari and Chrome on OS X.\n// Safari (but not Chrome) clips the cancel button when the search input has\n// padding (and `textfield` appearance).\n//\n\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n\n//\n// Define consistent border, margin, and padding.\n//\n\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\n\n//\n// 1. Correct `color` not being inherited in IE 8/9/10/11.\n// 2. Remove padding so people aren't caught out if they zero out fieldsets.\n//\n\nlegend {\n border: 0; // 1\n padding: 0; // 2\n}\n\n//\n// Remove default vertical scrollbar in IE 8/9/10/11.\n//\n\ntextarea {\n overflow: auto;\n}\n\n//\n// Don't inherit the `font-weight` (applied by a rule above).\n// NOTE: the default cannot safely be changed in Chrome and Safari on OS X.\n//\n\noptgroup {\n font-weight: bold;\n}\n\n// Tables\n// ==========================================================================\n\n//\n// Remove most spacing between table cells.\n//\n\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\n\ntd,\nth {\n padding: 0;\n}\n","/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */\n\n// ==========================================================================\n// Print styles.\n// Inlined to avoid the additional HTTP request: h5bp.com/r\n// ==========================================================================\n\n@media print {\n *,\n *:before,\n *:after {\n background: transparent !important;\n color: #000 !important; // Black prints faster: h5bp.com/s\n box-shadow: none !important;\n text-shadow: none !important;\n }\n\n a,\n a:visited {\n text-decoration: underline;\n }\n\n a[href]:after {\n content: \" (\" attr(href) \")\";\n }\n\n abbr[title]:after {\n content: \" (\" attr(title) \")\";\n }\n\n // Don't show links that are fragment identifiers,\n // or use the `javascript:` pseudo protocol\n a[href^=\"#\"]:after,\n a[href^=\"javascript:\"]:after {\n content: \"\";\n }\n\n pre,\n blockquote {\n border: 1px solid #999;\n page-break-inside: avoid;\n }\n\n thead {\n display: table-header-group; // h5bp.com/t\n }\n\n tr,\n img {\n page-break-inside: avoid;\n }\n\n img {\n max-width: 100% !important;\n }\n\n p,\n h2,\n h3 {\n orphans: 3;\n widows: 3;\n }\n\n h2,\n h3 {\n page-break-after: avoid;\n }\n\n // Bootstrap specific changes start\n //\n // Chrome (OSX) fix for https://github.com/twbs/bootstrap/issues/11245\n // Once fixed, we can just straight up remove this.\n select {\n background: #fff !important;\n }\n\n // Bootstrap components\n .navbar {\n display: none;\n }\n .btn,\n .dropup > .btn {\n > .caret {\n border-top-color: #000 !important;\n }\n }\n .label {\n border: 1px solid #000;\n }\n\n .table {\n border-collapse: collapse !important;\n\n td,\n th {\n background-color: #fff !important;\n }\n }\n .table-bordered {\n th,\n td {\n border: 1px solid #ddd !important;\n }\n }\n\n // Bootstrap specific changes end\n}\n","//\n// Glyphicons for Bootstrap\n//\n// Since icons are fonts, they can be placed anywhere text is placed and are\n// thus automatically sized to match the surrounding child. To use, create an\n// inline element with the appropriate classes, like so:\n//\n// Star\n\n// Import the fonts\n@font-face {\n font-family: 'Glyphicons Halflings';\n src: url('@{icon-font-path}@{icon-font-name}.eot');\n src: url('@{icon-font-path}@{icon-font-name}.eot?#iefix') format('embedded-opentype'),\n url('@{icon-font-path}@{icon-font-name}.woff2') format('woff2'),\n url('@{icon-font-path}@{icon-font-name}.woff') format('woff'),\n url('@{icon-font-path}@{icon-font-name}.ttf') format('truetype'),\n url('@{icon-font-path}@{icon-font-name}.svg#@{icon-font-svg-id}') format('svg');\n}\n\n// Catchall baseclass\n.glyphicon {\n position: relative;\n top: 1px;\n display: inline-block;\n font-family: 'Glyphicons Halflings';\n font-style: normal;\n font-weight: normal;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n// Individual icons\n.glyphicon-asterisk { &:before { content: \"\\2a\"; } }\n.glyphicon-plus { &:before { content: \"\\2b\"; } }\n.glyphicon-euro,\n.glyphicon-eur { &:before { content: \"\\20ac\"; } }\n.glyphicon-minus { &:before { content: \"\\2212\"; } }\n.glyphicon-cloud { &:before { content: \"\\2601\"; } }\n.glyphicon-envelope { &:before { content: \"\\2709\"; } }\n.glyphicon-pencil { &:before { content: \"\\270f\"; } }\n.glyphicon-glass { &:before { content: \"\\e001\"; } }\n.glyphicon-music { &:before { content: \"\\e002\"; } }\n.glyphicon-search { &:before { content: \"\\e003\"; } }\n.glyphicon-heart { &:before { content: \"\\e005\"; } }\n.glyphicon-star { &:before { content: \"\\e006\"; } }\n.glyphicon-star-empty { &:before { content: \"\\e007\"; } }\n.glyphicon-user { &:before { content: \"\\e008\"; } }\n.glyphicon-film { &:before { content: \"\\e009\"; } }\n.glyphicon-th-large { &:before { content: \"\\e010\"; } }\n.glyphicon-th { &:before { content: \"\\e011\"; } }\n.glyphicon-th-list { &:before { content: \"\\e012\"; } }\n.glyphicon-ok { &:before { content: \"\\e013\"; } }\n.glyphicon-remove { &:before { content: \"\\e014\"; } }\n.glyphicon-zoom-in { &:before { content: \"\\e015\"; } }\n.glyphicon-zoom-out { &:before { content: \"\\e016\"; } }\n.glyphicon-off { &:before { content: \"\\e017\"; } }\n.glyphicon-signal { &:before { content: \"\\e018\"; } }\n.glyphicon-cog { &:before { content: \"\\e019\"; } }\n.glyphicon-trash { &:before { content: \"\\e020\"; } }\n.glyphicon-home { &:before { content: \"\\e021\"; } }\n.glyphicon-file { &:before { content: \"\\e022\"; } }\n.glyphicon-time { &:before { content: \"\\e023\"; } }\n.glyphicon-road { &:before { content: \"\\e024\"; } }\n.glyphicon-download-alt { &:before { content: \"\\e025\"; } }\n.glyphicon-download { &:before { content: \"\\e026\"; } }\n.glyphicon-upload { &:before { content: \"\\e027\"; } }\n.glyphicon-inbox { &:before { content: \"\\e028\"; } }\n.glyphicon-play-circle { &:before { content: \"\\e029\"; } }\n.glyphicon-repeat { &:before { content: \"\\e030\"; } }\n.glyphicon-refresh { &:before { content: \"\\e031\"; } }\n.glyphicon-list-alt { &:before { content: \"\\e032\"; } }\n.glyphicon-lock { &:before { content: \"\\e033\"; } }\n.glyphicon-flag { &:before { content: \"\\e034\"; } }\n.glyphicon-headphones { &:before { content: \"\\e035\"; } }\n.glyphicon-volume-off { &:before { content: \"\\e036\"; } }\n.glyphicon-volume-down { &:before { content: \"\\e037\"; } }\n.glyphicon-volume-up { &:before { content: \"\\e038\"; } }\n.glyphicon-qrcode { &:before { content: \"\\e039\"; } }\n.glyphicon-barcode { &:before { content: \"\\e040\"; } }\n.glyphicon-tag { &:before { content: \"\\e041\"; } }\n.glyphicon-tags { &:before { content: \"\\e042\"; } }\n.glyphicon-book { &:before { content: \"\\e043\"; } }\n.glyphicon-bookmark { &:before { content: \"\\e044\"; } }\n.glyphicon-print { &:before { content: \"\\e045\"; } }\n.glyphicon-camera { &:before { content: \"\\e046\"; } }\n.glyphicon-font { &:before { content: \"\\e047\"; } }\n.glyphicon-bold { &:before { content: \"\\e048\"; } }\n.glyphicon-italic { &:before { content: \"\\e049\"; } }\n.glyphicon-text-height { &:before { content: \"\\e050\"; } }\n.glyphicon-text-width { &:before { content: \"\\e051\"; } }\n.glyphicon-align-left { &:before { content: \"\\e052\"; } }\n.glyphicon-align-center { &:before { content: \"\\e053\"; } }\n.glyphicon-align-right { &:before { content: \"\\e054\"; } }\n.glyphicon-align-justify { &:before { content: \"\\e055\"; } }\n.glyphicon-list { &:before { content: \"\\e056\"; } }\n.glyphicon-indent-left { &:before { content: \"\\e057\"; } }\n.glyphicon-indent-right { &:before { content: \"\\e058\"; } }\n.glyphicon-facetime-video { &:before { content: \"\\e059\"; } }\n.glyphicon-picture { &:before { content: \"\\e060\"; } }\n.glyphicon-map-marker { &:before { content: \"\\e062\"; } }\n.glyphicon-adjust { &:before { content: \"\\e063\"; } }\n.glyphicon-tint { &:before { content: \"\\e064\"; } }\n.glyphicon-edit { &:before { content: \"\\e065\"; } }\n.glyphicon-share { &:before { content: \"\\e066\"; } }\n.glyphicon-check { &:before { content: \"\\e067\"; } }\n.glyphicon-move { &:before { content: \"\\e068\"; } }\n.glyphicon-step-backward { &:before { content: \"\\e069\"; } }\n.glyphicon-fast-backward { &:before { content: \"\\e070\"; } }\n.glyphicon-backward { &:before { content: \"\\e071\"; } }\n.glyphicon-play { &:before { content: \"\\e072\"; } }\n.glyphicon-pause { &:before { content: \"\\e073\"; } }\n.glyphicon-stop { &:before { content: \"\\e074\"; } }\n.glyphicon-forward { &:before { content: \"\\e075\"; } }\n.glyphicon-fast-forward { &:before { content: \"\\e076\"; } }\n.glyphicon-step-forward { &:before { content: \"\\e077\"; } }\n.glyphicon-eject { &:before { content: \"\\e078\"; } }\n.glyphicon-chevron-left { &:before { content: \"\\e079\"; } }\n.glyphicon-chevron-right { &:before { content: \"\\e080\"; } }\n.glyphicon-plus-sign { &:before { content: \"\\e081\"; } }\n.glyphicon-minus-sign { &:before { content: \"\\e082\"; } }\n.glyphicon-remove-sign { &:before { content: \"\\e083\"; } }\n.glyphicon-ok-sign { &:before { content: \"\\e084\"; } }\n.glyphicon-question-sign { &:before { content: \"\\e085\"; } }\n.glyphicon-info-sign { &:before { content: \"\\e086\"; } }\n.glyphicon-screenshot { &:before { content: \"\\e087\"; } }\n.glyphicon-remove-circle { &:before { content: \"\\e088\"; } }\n.glyphicon-ok-circle { &:before { content: \"\\e089\"; } }\n.glyphicon-ban-circle { &:before { content: \"\\e090\"; } }\n.glyphicon-arrow-left { &:before { content: \"\\e091\"; } }\n.glyphicon-arrow-right { &:before { content: \"\\e092\"; } }\n.glyphicon-arrow-up { &:before { content: \"\\e093\"; } }\n.glyphicon-arrow-down { &:before { content: \"\\e094\"; } }\n.glyphicon-share-alt { &:before { content: \"\\e095\"; } }\n.glyphicon-resize-full { &:before { content: \"\\e096\"; } }\n.glyphicon-resize-small { &:before { content: \"\\e097\"; } }\n.glyphicon-exclamation-sign { &:before { content: \"\\e101\"; } }\n.glyphicon-gift { &:before { content: \"\\e102\"; } }\n.glyphicon-leaf { &:before { content: \"\\e103\"; } }\n.glyphicon-fire { &:before { content: \"\\e104\"; } }\n.glyphicon-eye-open { &:before { content: \"\\e105\"; } }\n.glyphicon-eye-close { &:before { content: \"\\e106\"; } }\n.glyphicon-warning-sign { &:before { content: \"\\e107\"; } }\n.glyphicon-plane { &:before { content: \"\\e108\"; } }\n.glyphicon-calendar { &:before { content: \"\\e109\"; } }\n.glyphicon-random { &:before { content: \"\\e110\"; } }\n.glyphicon-comment { &:before { content: \"\\e111\"; } }\n.glyphicon-magnet { &:before { content: \"\\e112\"; } }\n.glyphicon-chevron-up { &:before { content: \"\\e113\"; } }\n.glyphicon-chevron-down { &:before { content: \"\\e114\"; } }\n.glyphicon-retweet { &:before { content: \"\\e115\"; } }\n.glyphicon-shopping-cart { &:before { content: \"\\e116\"; } }\n.glyphicon-folder-close { &:before { content: \"\\e117\"; } }\n.glyphicon-folder-open { &:before { content: \"\\e118\"; } }\n.glyphicon-resize-vertical { &:before { content: \"\\e119\"; } }\n.glyphicon-resize-horizontal { &:before { content: \"\\e120\"; } }\n.glyphicon-hdd { &:before { content: \"\\e121\"; } }\n.glyphicon-bullhorn { &:before { content: \"\\e122\"; } }\n.glyphicon-bell { &:before { content: \"\\e123\"; } }\n.glyphicon-certificate { &:before { content: \"\\e124\"; } }\n.glyphicon-thumbs-up { &:before { content: \"\\e125\"; } }\n.glyphicon-thumbs-down { &:before { content: \"\\e126\"; } }\n.glyphicon-hand-right { &:before { content: \"\\e127\"; } }\n.glyphicon-hand-left { &:before { content: \"\\e128\"; } }\n.glyphicon-hand-up { &:before { content: \"\\e129\"; } }\n.glyphicon-hand-down { &:before { content: \"\\e130\"; } }\n.glyphicon-circle-arrow-right { &:before { content: \"\\e131\"; } }\n.glyphicon-circle-arrow-left { &:before { content: \"\\e132\"; } }\n.glyphicon-circle-arrow-up { &:before { content: \"\\e133\"; } }\n.glyphicon-circle-arrow-down { &:before { content: \"\\e134\"; } }\n.glyphicon-globe { &:before { content: \"\\e135\"; } }\n.glyphicon-wrench { &:before { content: \"\\e136\"; } }\n.glyphicon-tasks { &:before { content: \"\\e137\"; } }\n.glyphicon-filter { &:before { content: \"\\e138\"; } }\n.glyphicon-briefcase { &:before { content: \"\\e139\"; } }\n.glyphicon-fullscreen { &:before { content: \"\\e140\"; } }\n.glyphicon-dashboard { &:before { content: \"\\e141\"; } }\n.glyphicon-paperclip { &:before { content: \"\\e142\"; } }\n.glyphicon-heart-empty { &:before { content: \"\\e143\"; } }\n.glyphicon-link { &:before { content: \"\\e144\"; } }\n.glyphicon-phone { &:before { content: \"\\e145\"; } }\n.glyphicon-pushpin { &:before { content: \"\\e146\"; } }\n.glyphicon-usd { &:before { content: \"\\e148\"; } }\n.glyphicon-gbp { &:before { content: \"\\e149\"; } }\n.glyphicon-sort { &:before { content: \"\\e150\"; } }\n.glyphicon-sort-by-alphabet { &:before { content: \"\\e151\"; } }\n.glyphicon-sort-by-alphabet-alt { &:before { content: \"\\e152\"; } }\n.glyphicon-sort-by-order { &:before { content: \"\\e153\"; } }\n.glyphicon-sort-by-order-alt { &:before { content: \"\\e154\"; } }\n.glyphicon-sort-by-attributes { &:before { content: \"\\e155\"; } }\n.glyphicon-sort-by-attributes-alt { &:before { content: \"\\e156\"; } }\n.glyphicon-unchecked { &:before { content: \"\\e157\"; } }\n.glyphicon-expand { &:before { content: \"\\e158\"; } }\n.glyphicon-collapse-down { &:before { content: \"\\e159\"; } }\n.glyphicon-collapse-up { &:before { content: \"\\e160\"; } }\n.glyphicon-log-in { &:before { content: \"\\e161\"; } }\n.glyphicon-flash { &:before { content: \"\\e162\"; } }\n.glyphicon-log-out { &:before { content: \"\\e163\"; } }\n.glyphicon-new-window { &:before { content: \"\\e164\"; } }\n.glyphicon-record { &:before { content: \"\\e165\"; } }\n.glyphicon-save { &:before { content: \"\\e166\"; } }\n.glyphicon-open { &:before { content: \"\\e167\"; } }\n.glyphicon-saved { &:before { content: \"\\e168\"; } }\n.glyphicon-import { &:before { content: \"\\e169\"; } }\n.glyphicon-export { &:before { content: \"\\e170\"; } }\n.glyphicon-send { &:before { content: \"\\e171\"; } }\n.glyphicon-floppy-disk { &:before { content: \"\\e172\"; } }\n.glyphicon-floppy-saved { &:before { content: \"\\e173\"; } }\n.glyphicon-floppy-remove { &:before { content: \"\\e174\"; } }\n.glyphicon-floppy-save { &:before { content: \"\\e175\"; } }\n.glyphicon-floppy-open { &:before { content: \"\\e176\"; } }\n.glyphicon-credit-card { &:before { content: \"\\e177\"; } }\n.glyphicon-transfer { &:before { content: \"\\e178\"; } }\n.glyphicon-cutlery { &:before { content: \"\\e179\"; } }\n.glyphicon-header { &:before { content: \"\\e180\"; } }\n.glyphicon-compressed { &:before { content: \"\\e181\"; } }\n.glyphicon-earphone { &:before { content: \"\\e182\"; } }\n.glyphicon-phone-alt { &:before { content: \"\\e183\"; } }\n.glyphicon-tower { &:before { content: \"\\e184\"; } }\n.glyphicon-stats { &:before { content: \"\\e185\"; } }\n.glyphicon-sd-video { &:before { content: \"\\e186\"; } }\n.glyphicon-hd-video { &:before { content: \"\\e187\"; } }\n.glyphicon-subtitles { &:before { content: \"\\e188\"; } }\n.glyphicon-sound-stereo { &:before { content: \"\\e189\"; } }\n.glyphicon-sound-dolby { &:before { content: \"\\e190\"; } }\n.glyphicon-sound-5-1 { &:before { content: \"\\e191\"; } }\n.glyphicon-sound-6-1 { &:before { content: \"\\e192\"; } }\n.glyphicon-sound-7-1 { &:before { content: \"\\e193\"; } }\n.glyphicon-copyright-mark { &:before { content: \"\\e194\"; } }\n.glyphicon-registration-mark { &:before { content: \"\\e195\"; } }\n.glyphicon-cloud-download { &:before { content: \"\\e197\"; } }\n.glyphicon-cloud-upload { &:before { content: \"\\e198\"; } }\n.glyphicon-tree-conifer { &:before { content: \"\\e199\"; } }\n.glyphicon-tree-deciduous { &:before { content: \"\\e200\"; } }\n.glyphicon-cd { &:before { content: \"\\e201\"; } }\n.glyphicon-save-file { &:before { content: \"\\e202\"; } }\n.glyphicon-open-file { &:before { content: \"\\e203\"; } }\n.glyphicon-level-up { &:before { content: \"\\e204\"; } }\n.glyphicon-copy { &:before { content: \"\\e205\"; } }\n.glyphicon-paste { &:before { content: \"\\e206\"; } }\n// The following 2 Glyphicons are omitted for the time being because\n// they currently use Unicode codepoints that are outside the\n// Basic Multilingual Plane (BMP). Older buggy versions of WebKit can't handle\n// non-BMP codepoints in CSS string escapes, and thus can't display these two icons.\n// Notably, the bug affects some older versions of the Android Browser.\n// More info: https://github.com/twbs/bootstrap/issues/10106\n// .glyphicon-door { &:before { content: \"\\1f6aa\"; } }\n// .glyphicon-key { &:before { content: \"\\1f511\"; } }\n.glyphicon-alert { &:before { content: \"\\e209\"; } }\n.glyphicon-equalizer { &:before { content: \"\\e210\"; } }\n.glyphicon-king { &:before { content: \"\\e211\"; } }\n.glyphicon-queen { &:before { content: \"\\e212\"; } }\n.glyphicon-pawn { &:before { content: \"\\e213\"; } }\n.glyphicon-bishop { &:before { content: \"\\e214\"; } }\n.glyphicon-knight { &:before { content: \"\\e215\"; } }\n.glyphicon-baby-formula { &:before { content: \"\\e216\"; } }\n.glyphicon-tent { &:before { content: \"\\26fa\"; } }\n.glyphicon-blackboard { &:before { content: \"\\e218\"; } }\n.glyphicon-bed { &:before { content: \"\\e219\"; } }\n.glyphicon-apple { &:before { content: \"\\f8ff\"; } }\n.glyphicon-erase { &:before { content: \"\\e221\"; } }\n.glyphicon-hourglass { &:before { content: \"\\231b\"; } }\n.glyphicon-lamp { &:before { content: \"\\e223\"; } }\n.glyphicon-duplicate { &:before { content: \"\\e224\"; } }\n.glyphicon-piggy-bank { &:before { content: \"\\e225\"; } }\n.glyphicon-scissors { &:before { content: \"\\e226\"; } }\n.glyphicon-bitcoin { &:before { content: \"\\e227\"; } }\n.glyphicon-yen { &:before { content: \"\\00a5\"; } }\n.glyphicon-ruble { &:before { content: \"\\20bd\"; } }\n.glyphicon-scale { &:before { content: \"\\e230\"; } }\n.glyphicon-ice-lolly { &:before { content: \"\\e231\"; } }\n.glyphicon-ice-lolly-tasted { &:before { content: \"\\e232\"; } }\n.glyphicon-education { &:before { content: \"\\e233\"; } }\n.glyphicon-option-horizontal { &:before { content: \"\\e234\"; } }\n.glyphicon-option-vertical { &:before { content: \"\\e235\"; } }\n.glyphicon-menu-hamburger { &:before { content: \"\\e236\"; } }\n.glyphicon-modal-window { &:before { content: \"\\e237\"; } }\n.glyphicon-oil { &:before { content: \"\\e238\"; } }\n.glyphicon-grain { &:before { content: \"\\e239\"; } }\n.glyphicon-sunglasses { &:before { content: \"\\e240\"; } }\n.glyphicon-text-size { &:before { content: \"\\e241\"; } }\n.glyphicon-text-color { &:before { content: \"\\e242\"; } }\n.glyphicon-text-background { &:before { content: \"\\e243\"; } }\n.glyphicon-object-align-top { &:before { content: \"\\e244\"; } }\n.glyphicon-object-align-bottom { &:before { content: \"\\e245\"; } }\n.glyphicon-object-align-horizontal{ &:before { content: \"\\e246\"; } }\n.glyphicon-object-align-left { &:before { content: \"\\e247\"; } }\n.glyphicon-object-align-vertical { &:before { content: \"\\e248\"; } }\n.glyphicon-object-align-right { &:before { content: \"\\e249\"; } }\n.glyphicon-triangle-right { &:before { content: \"\\e250\"; } }\n.glyphicon-triangle-left { &:before { content: \"\\e251\"; } }\n.glyphicon-triangle-bottom { &:before { content: \"\\e252\"; } }\n.glyphicon-triangle-top { &:before { content: \"\\e253\"; } }\n.glyphicon-console { &:before { content: \"\\e254\"; } }\n.glyphicon-superscript { &:before { content: \"\\e255\"; } }\n.glyphicon-subscript { &:before { content: \"\\e256\"; } }\n.glyphicon-menu-left { &:before { content: \"\\e257\"; } }\n.glyphicon-menu-right { &:before { content: \"\\e258\"; } }\n.glyphicon-menu-down { &:before { content: \"\\e259\"; } }\n.glyphicon-menu-up { &:before { content: \"\\e260\"; } }\n","//\n// Scaffolding\n// --------------------------------------------------\n\n\n// Reset the box-sizing\n//\n// Heads up! This reset may cause conflicts with some third-party widgets.\n// For recommendations on resolving such conflicts, see\n// http://getbootstrap.com/getting-started/#third-box-sizing\n* {\n .box-sizing(border-box);\n}\n*:before,\n*:after {\n .box-sizing(border-box);\n}\n\n\n// Body reset\n\nhtml {\n font-size: 10px;\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n}\n\nbody {\n font-family: @font-family-base;\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @text-color;\n background-color: @body-bg;\n}\n\n// Reset fonts for relevant elements\ninput,\nbutton,\nselect,\ntextarea {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n}\n\n\n// Links\n\na {\n color: @link-color;\n text-decoration: none;\n\n &:hover,\n &:focus {\n color: @link-hover-color;\n text-decoration: @link-hover-decoration;\n }\n\n &:focus {\n .tab-focus();\n }\n}\n\n\n// Figures\n//\n// We reset this here because previously Normalize had no `figure` margins. This\n// ensures we don't break anyone's use of the element.\n\nfigure {\n margin: 0;\n}\n\n\n// Images\n\nimg {\n vertical-align: middle;\n}\n\n// Responsive images (ensure images don't scale beyond their parents)\n.img-responsive {\n .img-responsive();\n}\n\n// Rounded corners\n.img-rounded {\n border-radius: @border-radius-large;\n}\n\n// Image thumbnails\n//\n// Heads up! This is mixin-ed into thumbnails.less for `.thumbnail`.\n.img-thumbnail {\n padding: @thumbnail-padding;\n line-height: @line-height-base;\n background-color: @thumbnail-bg;\n border: 1px solid @thumbnail-border;\n border-radius: @thumbnail-border-radius;\n .transition(all .2s ease-in-out);\n\n // Keep them at most 100% wide\n .img-responsive(inline-block);\n}\n\n// Perfect circle\n.img-circle {\n border-radius: 50%; // set radius in percents\n}\n\n\n// Horizontal rules\n\nhr {\n margin-top: @line-height-computed;\n margin-bottom: @line-height-computed;\n border: 0;\n border-top: 1px solid @hr-border;\n}\n\n\n// Only display content to screen readers\n//\n// See: http://a11yproject.com/posts/how-to-hide-content/\n\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0,0,0,0);\n border: 0;\n}\n\n// Use in conjunction with .sr-only to only display content when it's focused.\n// Useful for \"Skip to main content\" links; see http://www.w3.org/TR/2013/NOTE-WCAG20-TECHS-20130905/G1\n// Credit: HTML5 Boilerplate\n\n.sr-only-focusable {\n &:active,\n &:focus {\n position: static;\n width: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n clip: auto;\n }\n}\n","// Vendor Prefixes\n//\n// All vendor mixins are deprecated as of v3.2.0 due to the introduction of\n// Autoprefixer in our Gruntfile. They will be removed in v4.\n\n// - Animations\n// - Backface visibility\n// - Box shadow\n// - Box sizing\n// - Content columns\n// - Hyphens\n// - Placeholder text\n// - Transformations\n// - Transitions\n// - User Select\n\n\n// Animations\n.animation(@animation) {\n -webkit-animation: @animation;\n -o-animation: @animation;\n animation: @animation;\n}\n.animation-name(@name) {\n -webkit-animation-name: @name;\n animation-name: @name;\n}\n.animation-duration(@duration) {\n -webkit-animation-duration: @duration;\n animation-duration: @duration;\n}\n.animation-timing-function(@timing-function) {\n -webkit-animation-timing-function: @timing-function;\n animation-timing-function: @timing-function;\n}\n.animation-delay(@delay) {\n -webkit-animation-delay: @delay;\n animation-delay: @delay;\n}\n.animation-iteration-count(@iteration-count) {\n -webkit-animation-iteration-count: @iteration-count;\n animation-iteration-count: @iteration-count;\n}\n.animation-direction(@direction) {\n -webkit-animation-direction: @direction;\n animation-direction: @direction;\n}\n.animation-fill-mode(@fill-mode) {\n -webkit-animation-fill-mode: @fill-mode;\n animation-fill-mode: @fill-mode;\n}\n\n// Backface visibility\n// Prevent browsers from flickering when using CSS 3D transforms.\n// Default value is `visible`, but can be changed to `hidden`\n\n.backface-visibility(@visibility){\n -webkit-backface-visibility: @visibility;\n -moz-backface-visibility: @visibility;\n backface-visibility: @visibility;\n}\n\n// Drop shadows\n//\n// Note: Deprecated `.box-shadow()` as of v3.1.0 since all of Bootstrap's\n// supported browsers that have box shadow capabilities now support it.\n\n.box-shadow(@shadow) {\n -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1\n box-shadow: @shadow;\n}\n\n// Box sizing\n.box-sizing(@boxmodel) {\n -webkit-box-sizing: @boxmodel;\n -moz-box-sizing: @boxmodel;\n box-sizing: @boxmodel;\n}\n\n// CSS3 Content Columns\n.content-columns(@column-count; @column-gap: @grid-gutter-width) {\n -webkit-column-count: @column-count;\n -moz-column-count: @column-count;\n column-count: @column-count;\n -webkit-column-gap: @column-gap;\n -moz-column-gap: @column-gap;\n column-gap: @column-gap;\n}\n\n// Optional hyphenation\n.hyphens(@mode: auto) {\n word-wrap: break-word;\n -webkit-hyphens: @mode;\n -moz-hyphens: @mode;\n -ms-hyphens: @mode; // IE10+\n -o-hyphens: @mode;\n hyphens: @mode;\n}\n\n// Placeholder text\n.placeholder(@color: @input-color-placeholder) {\n // Firefox\n &::-moz-placeholder {\n color: @color;\n opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526\n }\n &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+\n &::-webkit-input-placeholder { color: @color; } // Safari and Chrome\n}\n\n// Transformations\n.scale(@ratio) {\n -webkit-transform: scale(@ratio);\n -ms-transform: scale(@ratio); // IE9 only\n -o-transform: scale(@ratio);\n transform: scale(@ratio);\n}\n.scale(@ratioX; @ratioY) {\n -webkit-transform: scale(@ratioX, @ratioY);\n -ms-transform: scale(@ratioX, @ratioY); // IE9 only\n -o-transform: scale(@ratioX, @ratioY);\n transform: scale(@ratioX, @ratioY);\n}\n.scaleX(@ratio) {\n -webkit-transform: scaleX(@ratio);\n -ms-transform: scaleX(@ratio); // IE9 only\n -o-transform: scaleX(@ratio);\n transform: scaleX(@ratio);\n}\n.scaleY(@ratio) {\n -webkit-transform: scaleY(@ratio);\n -ms-transform: scaleY(@ratio); // IE9 only\n -o-transform: scaleY(@ratio);\n transform: scaleY(@ratio);\n}\n.skew(@x; @y) {\n -webkit-transform: skewX(@x) skewY(@y);\n -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+\n -o-transform: skewX(@x) skewY(@y);\n transform: skewX(@x) skewY(@y);\n}\n.translate(@x; @y) {\n -webkit-transform: translate(@x, @y);\n -ms-transform: translate(@x, @y); // IE9 only\n -o-transform: translate(@x, @y);\n transform: translate(@x, @y);\n}\n.translate3d(@x; @y; @z) {\n -webkit-transform: translate3d(@x, @y, @z);\n transform: translate3d(@x, @y, @z);\n}\n.rotate(@degrees) {\n -webkit-transform: rotate(@degrees);\n -ms-transform: rotate(@degrees); // IE9 only\n -o-transform: rotate(@degrees);\n transform: rotate(@degrees);\n}\n.rotateX(@degrees) {\n -webkit-transform: rotateX(@degrees);\n -ms-transform: rotateX(@degrees); // IE9 only\n -o-transform: rotateX(@degrees);\n transform: rotateX(@degrees);\n}\n.rotateY(@degrees) {\n -webkit-transform: rotateY(@degrees);\n -ms-transform: rotateY(@degrees); // IE9 only\n -o-transform: rotateY(@degrees);\n transform: rotateY(@degrees);\n}\n.perspective(@perspective) {\n -webkit-perspective: @perspective;\n -moz-perspective: @perspective;\n perspective: @perspective;\n}\n.perspective-origin(@perspective) {\n -webkit-perspective-origin: @perspective;\n -moz-perspective-origin: @perspective;\n perspective-origin: @perspective;\n}\n.transform-origin(@origin) {\n -webkit-transform-origin: @origin;\n -moz-transform-origin: @origin;\n -ms-transform-origin: @origin; // IE9 only\n transform-origin: @origin;\n}\n\n\n// Transitions\n\n.transition(@transition) {\n -webkit-transition: @transition;\n -o-transition: @transition;\n transition: @transition;\n}\n.transition-property(@transition-property) {\n -webkit-transition-property: @transition-property;\n transition-property: @transition-property;\n}\n.transition-delay(@transition-delay) {\n -webkit-transition-delay: @transition-delay;\n transition-delay: @transition-delay;\n}\n.transition-duration(@transition-duration) {\n -webkit-transition-duration: @transition-duration;\n transition-duration: @transition-duration;\n}\n.transition-timing-function(@timing-function) {\n -webkit-transition-timing-function: @timing-function;\n transition-timing-function: @timing-function;\n}\n.transition-transform(@transition) {\n -webkit-transition: -webkit-transform @transition;\n -moz-transition: -moz-transform @transition;\n -o-transition: -o-transform @transition;\n transition: transform @transition;\n}\n\n\n// User select\n// For selecting text on the page\n\n.user-select(@select) {\n -webkit-user-select: @select;\n -moz-user-select: @select;\n -ms-user-select: @select; // IE10+\n user-select: @select;\n}\n","// WebKit-style focus\n\n.tab-focus() {\n // Default\n outline: thin dotted;\n // WebKit\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\n","// Image Mixins\n// - Responsive image\n// - Retina image\n\n\n// Responsive image\n//\n// Keep images from scaling beyond the width of their parents.\n.img-responsive(@display: block) {\n display: @display;\n max-width: 100%; // Part 1: Set a maximum relative to the parent\n height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching\n}\n\n\n// Retina image\n//\n// Short retina mixin for setting background-image and -size. Note that the\n// spelling of `min--moz-device-pixel-ratio` is intentional.\n.img-retina(@file-1x; @file-2x; @width-1x; @height-1x) {\n background-image: url(\"@{file-1x}\");\n\n @media\n only screen and (-webkit-min-device-pixel-ratio: 2),\n only screen and ( min--moz-device-pixel-ratio: 2),\n only screen and ( -o-min-device-pixel-ratio: 2/1),\n only screen and ( min-device-pixel-ratio: 2),\n only screen and ( min-resolution: 192dpi),\n only screen and ( min-resolution: 2dppx) {\n background-image: url(\"@{file-2x}\");\n background-size: @width-1x @height-1x;\n }\n}\n","//\n// Typography\n// --------------------------------------------------\n\n\n// Headings\n// -------------------------\n\nh1, h2, h3, h4, h5, h6,\n.h1, .h2, .h3, .h4, .h5, .h6 {\n font-family: @headings-font-family;\n font-weight: @headings-font-weight;\n line-height: @headings-line-height;\n color: @headings-color;\n\n small,\n .small {\n font-weight: normal;\n line-height: 1;\n color: @headings-small-color;\n }\n}\n\nh1, .h1,\nh2, .h2,\nh3, .h3 {\n margin-top: @line-height-computed;\n margin-bottom: (@line-height-computed / 2);\n\n small,\n .small {\n font-size: 65%;\n }\n}\nh4, .h4,\nh5, .h5,\nh6, .h6 {\n margin-top: (@line-height-computed / 2);\n margin-bottom: (@line-height-computed / 2);\n\n small,\n .small {\n font-size: 75%;\n }\n}\n\nh1, .h1 { font-size: @font-size-h1; }\nh2, .h2 { font-size: @font-size-h2; }\nh3, .h3 { font-size: @font-size-h3; }\nh4, .h4 { font-size: @font-size-h4; }\nh5, .h5 { font-size: @font-size-h5; }\nh6, .h6 { font-size: @font-size-h6; }\n\n\n// Body text\n// -------------------------\n\np {\n margin: 0 0 (@line-height-computed / 2);\n}\n\n.lead {\n margin-bottom: @line-height-computed;\n font-size: floor((@font-size-base * 1.15));\n font-weight: 300;\n line-height: 1.4;\n\n @media (min-width: @screen-sm-min) {\n font-size: (@font-size-base * 1.5);\n }\n}\n\n\n// Emphasis & misc\n// -------------------------\n\n// Ex: (12px small font / 14px base font) * 100% = about 85%\nsmall,\n.small {\n font-size: floor((100% * @font-size-small / @font-size-base));\n}\n\nmark,\n.mark {\n background-color: @state-warning-bg;\n padding: .2em;\n}\n\n// Alignment\n.text-left { text-align: left; }\n.text-right { text-align: right; }\n.text-center { text-align: center; }\n.text-justify { text-align: justify; }\n.text-nowrap { white-space: nowrap; }\n\n// Transformation\n.text-lowercase { text-transform: lowercase; }\n.text-uppercase { text-transform: uppercase; }\n.text-capitalize { text-transform: capitalize; }\n\n// Contextual colors\n.text-muted {\n color: @text-muted;\n}\n.text-primary {\n .text-emphasis-variant(@brand-primary);\n}\n.text-success {\n .text-emphasis-variant(@state-success-text);\n}\n.text-info {\n .text-emphasis-variant(@state-info-text);\n}\n.text-warning {\n .text-emphasis-variant(@state-warning-text);\n}\n.text-danger {\n .text-emphasis-variant(@state-danger-text);\n}\n\n// Contextual backgrounds\n// For now we'll leave these alongside the text classes until v4 when we can\n// safely shift things around (per SemVer rules).\n.bg-primary {\n // Given the contrast here, this is the only class to have its color inverted\n // automatically.\n color: #fff;\n .bg-variant(@brand-primary);\n}\n.bg-success {\n .bg-variant(@state-success-bg);\n}\n.bg-info {\n .bg-variant(@state-info-bg);\n}\n.bg-warning {\n .bg-variant(@state-warning-bg);\n}\n.bg-danger {\n .bg-variant(@state-danger-bg);\n}\n\n\n// Page header\n// -------------------------\n\n.page-header {\n padding-bottom: ((@line-height-computed / 2) - 1);\n margin: (@line-height-computed * 2) 0 @line-height-computed;\n border-bottom: 1px solid @page-header-border-color;\n}\n\n\n// Lists\n// -------------------------\n\n// Unordered and Ordered lists\nul,\nol {\n margin-top: 0;\n margin-bottom: (@line-height-computed / 2);\n ul,\n ol {\n margin-bottom: 0;\n }\n}\n\n// List options\n\n// Unstyled keeps list items block level, just removes default browser padding and list-style\n.list-unstyled {\n padding-left: 0;\n list-style: none;\n}\n\n// Inline turns list items into inline-block\n.list-inline {\n .list-unstyled();\n margin-left: -5px;\n\n > li {\n display: inline-block;\n padding-left: 5px;\n padding-right: 5px;\n }\n}\n\n// Description Lists\ndl {\n margin-top: 0; // Remove browser default\n margin-bottom: @line-height-computed;\n}\ndt,\ndd {\n line-height: @line-height-base;\n}\ndt {\n font-weight: bold;\n}\ndd {\n margin-left: 0; // Undo browser default\n}\n\n// Horizontal description lists\n//\n// Defaults to being stacked without any of the below styles applied, until the\n// grid breakpoint is reached (default of ~768px).\n\n.dl-horizontal {\n dd {\n &:extend(.clearfix all); // Clear the floated `dt` if an empty `dd` is present\n }\n\n @media (min-width: @grid-float-breakpoint) {\n dt {\n float: left;\n width: (@dl-horizontal-offset - 20);\n clear: left;\n text-align: right;\n .text-overflow();\n }\n dd {\n margin-left: @dl-horizontal-offset;\n }\n }\n}\n\n\n// Misc\n// -------------------------\n\n// Abbreviations and acronyms\nabbr[title],\n// Add data-* attribute to help out our tooltip plugin, per https://github.com/twbs/bootstrap/issues/5257\nabbr[data-original-title] {\n cursor: help;\n border-bottom: 1px dotted @abbr-border-color;\n}\n.initialism {\n font-size: 90%;\n text-transform: uppercase;\n}\n\n// Blockquotes\nblockquote {\n padding: (@line-height-computed / 2) @line-height-computed;\n margin: 0 0 @line-height-computed;\n font-size: @blockquote-font-size;\n border-left: 5px solid @blockquote-border-color;\n\n p,\n ul,\n ol {\n &:last-child {\n margin-bottom: 0;\n }\n }\n\n // Note: Deprecated small and .small as of v3.1.0\n // Context: https://github.com/twbs/bootstrap/issues/11660\n footer,\n small,\n .small {\n display: block;\n font-size: 80%; // back to default font-size\n line-height: @line-height-base;\n color: @blockquote-small-color;\n\n &:before {\n content: '\\2014 \\00A0'; // em dash, nbsp\n }\n }\n}\n\n// Opposite alignment of blockquote\n//\n// Heads up: `blockquote.pull-right` has been deprecated as of v3.1.0.\n.blockquote-reverse,\nblockquote.pull-right {\n padding-right: 15px;\n padding-left: 0;\n border-right: 5px solid @blockquote-border-color;\n border-left: 0;\n text-align: right;\n\n // Account for citation\n footer,\n small,\n .small {\n &:before { content: ''; }\n &:after {\n content: '\\00A0 \\2014'; // nbsp, em dash\n }\n }\n}\n\n// Addresses\naddress {\n margin-bottom: @line-height-computed;\n font-style: normal;\n line-height: @line-height-base;\n}\n","// Typography\n\n.text-emphasis-variant(@color) {\n color: @color;\n a&:hover {\n color: darken(@color, 10%);\n }\n}\n","// Contextual backgrounds\n\n.bg-variant(@color) {\n background-color: @color;\n a&:hover {\n background-color: darken(@color, 10%);\n }\n}\n","// Text overflow\n// Requires inline-block or block for proper styling\n\n.text-overflow() {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n","//\n// Code (inline and block)\n// --------------------------------------------------\n\n\n// Inline and block code styles\ncode,\nkbd,\npre,\nsamp {\n font-family: @font-family-monospace;\n}\n\n// Inline code\ncode {\n padding: 2px 4px;\n font-size: 90%;\n color: @code-color;\n background-color: @code-bg;\n border-radius: @border-radius-base;\n}\n\n// User input typically entered via keyboard\nkbd {\n padding: 2px 4px;\n font-size: 90%;\n color: @kbd-color;\n background-color: @kbd-bg;\n border-radius: @border-radius-small;\n box-shadow: inset 0 -1px 0 rgba(0,0,0,.25);\n\n kbd {\n padding: 0;\n font-size: 100%;\n font-weight: bold;\n box-shadow: none;\n }\n}\n\n// Blocks of code\npre {\n display: block;\n padding: ((@line-height-computed - 1) / 2);\n margin: 0 0 (@line-height-computed / 2);\n font-size: (@font-size-base - 1); // 14px to 13px\n line-height: @line-height-base;\n word-break: break-all;\n word-wrap: break-word;\n color: @pre-color;\n background-color: @pre-bg;\n border: 1px solid @pre-border-color;\n border-radius: @border-radius-base;\n\n // Account for some code outputs that place code tags in pre tags\n code {\n padding: 0;\n font-size: inherit;\n color: inherit;\n white-space: pre-wrap;\n background-color: transparent;\n border-radius: 0;\n }\n}\n\n// Enable scrollable blocks of code\n.pre-scrollable {\n max-height: @pre-scrollable-max-height;\n overflow-y: scroll;\n}\n","//\n// Grid system\n// --------------------------------------------------\n\n\n// Container widths\n//\n// Set the container width, and override it for fixed navbars in media queries.\n\n.container {\n .container-fixed();\n\n @media (min-width: @screen-sm-min) {\n width: @container-sm;\n }\n @media (min-width: @screen-md-min) {\n width: @container-md;\n }\n @media (min-width: @screen-lg-min) {\n width: @container-lg;\n }\n}\n\n\n// Fluid container\n//\n// Utilizes the mixin meant for fixed width containers, but without any defined\n// width for fluid, full width layouts.\n\n.container-fluid {\n .container-fixed();\n}\n\n\n// Row\n//\n// Rows contain and clear the floats of your columns.\n\n.row {\n .make-row();\n}\n\n\n// Columns\n//\n// Common styles for small and large grid columns\n\n.make-grid-columns();\n\n\n// Extra small grid\n//\n// Columns, offsets, pushes, and pulls for extra small devices like\n// smartphones.\n\n.make-grid(xs);\n\n\n// Small grid\n//\n// Columns, offsets, pushes, and pulls for the small device range, from phones\n// to tablets.\n\n@media (min-width: @screen-sm-min) {\n .make-grid(sm);\n}\n\n\n// Medium grid\n//\n// Columns, offsets, pushes, and pulls for the desktop device range.\n\n@media (min-width: @screen-md-min) {\n .make-grid(md);\n}\n\n\n// Large grid\n//\n// Columns, offsets, pushes, and pulls for the large desktop device range.\n\n@media (min-width: @screen-lg-min) {\n .make-grid(lg);\n}\n","// Grid system\n//\n// Generate semantic grid columns with these mixins.\n\n// Centered container element\n.container-fixed(@gutter: @grid-gutter-width) {\n margin-right: auto;\n margin-left: auto;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n &:extend(.clearfix all);\n}\n\n// Creates a wrapper for a series of columns\n.make-row(@gutter: @grid-gutter-width) {\n margin-left: (@gutter / -2);\n margin-right: (@gutter / -2);\n &:extend(.clearfix all);\n}\n\n// Generate the extra small columns\n.make-xs-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n float: left;\n width: percentage((@columns / @grid-columns));\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n}\n.make-xs-column-offset(@columns) {\n margin-left: percentage((@columns / @grid-columns));\n}\n.make-xs-column-push(@columns) {\n left: percentage((@columns / @grid-columns));\n}\n.make-xs-column-pull(@columns) {\n right: percentage((@columns / @grid-columns));\n}\n\n// Generate the small columns\n.make-sm-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-sm-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-offset(@columns) {\n @media (min-width: @screen-sm-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-push(@columns) {\n @media (min-width: @screen-sm-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-pull(@columns) {\n @media (min-width: @screen-sm-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n\n// Generate the medium columns\n.make-md-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-md-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-offset(@columns) {\n @media (min-width: @screen-md-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-push(@columns) {\n @media (min-width: @screen-md-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-pull(@columns) {\n @media (min-width: @screen-md-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n\n// Generate the large columns\n.make-lg-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-lg-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-offset(@columns) {\n @media (min-width: @screen-lg-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-push(@columns) {\n @media (min-width: @screen-lg-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-pull(@columns) {\n @media (min-width: @screen-lg-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n","// Framework grid generation\n//\n// Used only by Bootstrap to generate the correct number of grid classes given\n// any value of `@grid-columns`.\n\n.make-grid-columns() {\n // Common styles for all sizes of grid columns, widths 1-12\n .col(@index) { // initial\n @item: ~\".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}\";\n .col((@index + 1), @item);\n }\n .col(@index, @list) when (@index =< @grid-columns) { // general; \"=<\" isn't a typo\n @item: ~\".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}\";\n .col((@index + 1), ~\"@{list}, @{item}\");\n }\n .col(@index, @list) when (@index > @grid-columns) { // terminal\n @{list} {\n position: relative;\n // Prevent columns from collapsing when empty\n min-height: 1px;\n // Inner gutter via padding\n padding-left: (@grid-gutter-width / 2);\n padding-right: (@grid-gutter-width / 2);\n }\n }\n .col(1); // kickstart it\n}\n\n.float-grid-columns(@class) {\n .col(@index) { // initial\n @item: ~\".col-@{class}-@{index}\";\n .col((@index + 1), @item);\n }\n .col(@index, @list) when (@index =< @grid-columns) { // general\n @item: ~\".col-@{class}-@{index}\";\n .col((@index + 1), ~\"@{list}, @{item}\");\n }\n .col(@index, @list) when (@index > @grid-columns) { // terminal\n @{list} {\n float: left;\n }\n }\n .col(1); // kickstart it\n}\n\n.calc-grid-column(@index, @class, @type) when (@type = width) and (@index > 0) {\n .col-@{class}-@{index} {\n width: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = push) and (@index > 0) {\n .col-@{class}-push-@{index} {\n left: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = push) and (@index = 0) {\n .col-@{class}-push-0 {\n left: auto;\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index > 0) {\n .col-@{class}-pull-@{index} {\n right: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index = 0) {\n .col-@{class}-pull-0 {\n right: auto;\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = offset) {\n .col-@{class}-offset-@{index} {\n margin-left: percentage((@index / @grid-columns));\n }\n}\n\n// Basic looping in LESS\n.loop-grid-columns(@index, @class, @type) when (@index >= 0) {\n .calc-grid-column(@index, @class, @type);\n // next iteration\n .loop-grid-columns((@index - 1), @class, @type);\n}\n\n// Create grid for specific class\n.make-grid(@class) {\n .float-grid-columns(@class);\n .loop-grid-columns(@grid-columns, @class, width);\n .loop-grid-columns(@grid-columns, @class, pull);\n .loop-grid-columns(@grid-columns, @class, push);\n .loop-grid-columns(@grid-columns, @class, offset);\n}\n","//\n// Tables\n// --------------------------------------------------\n\n\ntable {\n background-color: @table-bg;\n}\ncaption {\n padding-top: @table-cell-padding;\n padding-bottom: @table-cell-padding;\n color: @text-muted;\n text-align: left;\n}\nth {\n text-align: left;\n}\n\n\n// Baseline styles\n\n.table {\n width: 100%;\n max-width: 100%;\n margin-bottom: @line-height-computed;\n // Cells\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n padding: @table-cell-padding;\n line-height: @line-height-base;\n vertical-align: top;\n border-top: 1px solid @table-border-color;\n }\n }\n }\n // Bottom align for column headings\n > thead > tr > th {\n vertical-align: bottom;\n border-bottom: 2px solid @table-border-color;\n }\n // Remove top border from thead by default\n > caption + thead,\n > colgroup + thead,\n > thead:first-child {\n > tr:first-child {\n > th,\n > td {\n border-top: 0;\n }\n }\n }\n // Account for multiple tbody instances\n > tbody + tbody {\n border-top: 2px solid @table-border-color;\n }\n\n // Nesting\n .table {\n background-color: @body-bg;\n }\n}\n\n\n// Condensed table w/ half padding\n\n.table-condensed {\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n padding: @table-condensed-cell-padding;\n }\n }\n }\n}\n\n\n// Bordered version\n//\n// Add borders all around the table and between all the columns.\n\n.table-bordered {\n border: 1px solid @table-border-color;\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n border: 1px solid @table-border-color;\n }\n }\n }\n > thead > tr {\n > th,\n > td {\n border-bottom-width: 2px;\n }\n }\n}\n\n\n// Zebra-striping\n//\n// Default zebra-stripe styles (alternating gray and transparent backgrounds)\n\n.table-striped {\n > tbody > tr:nth-of-type(odd) {\n background-color: @table-bg-accent;\n }\n}\n\n\n// Hover effect\n//\n// Placed here since it has to come after the potential zebra striping\n\n.table-hover {\n > tbody > tr:hover {\n background-color: @table-bg-hover;\n }\n}\n\n\n// Table cell sizing\n//\n// Reset default table behavior\n\ntable col[class*=\"col-\"] {\n position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)\n float: none;\n display: table-column;\n}\ntable {\n td,\n th {\n &[class*=\"col-\"] {\n position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)\n float: none;\n display: table-cell;\n }\n }\n}\n\n\n// Table backgrounds\n//\n// Exact selectors below required to override `.table-striped` and prevent\n// inheritance to nested tables.\n\n// Generate the contextual variants\n.table-row-variant(active; @table-bg-active);\n.table-row-variant(success; @state-success-bg);\n.table-row-variant(info; @state-info-bg);\n.table-row-variant(warning; @state-warning-bg);\n.table-row-variant(danger; @state-danger-bg);\n\n\n// Responsive tables\n//\n// Wrap your tables in `.table-responsive` and we'll make them mobile friendly\n// by enabling horizontal scrolling. Only applies <768px. Everything above that\n// will display normally.\n\n.table-responsive {\n overflow-x: auto;\n min-height: 0.01%; // Workaround for IE9 bug (see https://github.com/twbs/bootstrap/issues/14837)\n\n @media screen and (max-width: @screen-xs-max) {\n width: 100%;\n margin-bottom: (@line-height-computed * 0.75);\n overflow-y: hidden;\n -ms-overflow-style: -ms-autohiding-scrollbar;\n border: 1px solid @table-border-color;\n\n // Tighten up spacing\n > .table {\n margin-bottom: 0;\n\n // Ensure the content doesn't wrap\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n white-space: nowrap;\n }\n }\n }\n }\n\n // Special overrides for the bordered tables\n > .table-bordered {\n border: 0;\n\n // Nuke the appropriate borders so that the parent can handle them\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th:first-child,\n > td:first-child {\n border-left: 0;\n }\n > th:last-child,\n > td:last-child {\n border-right: 0;\n }\n }\n }\n\n // Only nuke the last row's bottom-border in `tbody` and `tfoot` since\n // chances are there will be only one `tr` in a `thead` and that would\n // remove the border altogether.\n > tbody,\n > tfoot {\n > tr:last-child {\n > th,\n > td {\n border-bottom: 0;\n }\n }\n }\n\n }\n }\n}\n","// Tables\n\n.table-row-variant(@state; @background) {\n // Exact selectors below required to override `.table-striped` and prevent\n // inheritance to nested tables.\n .table > thead > tr,\n .table > tbody > tr,\n .table > tfoot > tr {\n > td.@{state},\n > th.@{state},\n &.@{state} > td,\n &.@{state} > th {\n background-color: @background;\n }\n }\n\n // Hover states for `.table-hover`\n // Note: this is not available for cells or rows within `thead` or `tfoot`.\n .table-hover > tbody > tr {\n > td.@{state}:hover,\n > th.@{state}:hover,\n &.@{state}:hover > td,\n &:hover > .@{state},\n &.@{state}:hover > th {\n background-color: darken(@background, 5%);\n }\n }\n}\n","//\n// Forms\n// --------------------------------------------------\n\n\n// Normalize non-controls\n//\n// Restyle and baseline non-control form elements.\n\nfieldset {\n padding: 0;\n margin: 0;\n border: 0;\n // Chrome and Firefox set a `min-width: min-content;` on fieldsets,\n // so we reset that to ensure it behaves more like a standard block element.\n // See https://github.com/twbs/bootstrap/issues/12359.\n min-width: 0;\n}\n\nlegend {\n display: block;\n width: 100%;\n padding: 0;\n margin-bottom: @line-height-computed;\n font-size: (@font-size-base * 1.5);\n line-height: inherit;\n color: @legend-color;\n border: 0;\n border-bottom: 1px solid @legend-border-color;\n}\n\nlabel {\n display: inline-block;\n max-width: 100%; // Force IE8 to wrap long content (see https://github.com/twbs/bootstrap/issues/13141)\n margin-bottom: 5px;\n font-weight: bold;\n}\n\n\n// Normalize form controls\n//\n// While most of our form styles require extra classes, some basic normalization\n// is required to ensure optimum display with or without those classes to better\n// address browser inconsistencies.\n\n// Override content-box in Normalize (* isn't specific enough)\ninput[type=\"search\"] {\n .box-sizing(border-box);\n}\n\n// Position radios and checkboxes better\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 4px 0 0;\n margin-top: 1px \\9; // IE8-9\n line-height: normal;\n}\n\n// Set the height of file controls to match text inputs\ninput[type=\"file\"] {\n display: block;\n}\n\n// Make range inputs behave like textual form controls\ninput[type=\"range\"] {\n display: block;\n width: 100%;\n}\n\n// Make multiple select elements height not fixed\nselect[multiple],\nselect[size] {\n height: auto;\n}\n\n// Focus for file, radio, and checkbox\ninput[type=\"file\"]:focus,\ninput[type=\"radio\"]:focus,\ninput[type=\"checkbox\"]:focus {\n .tab-focus();\n}\n\n// Adjust output element\noutput {\n display: block;\n padding-top: (@padding-base-vertical + 1);\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @input-color;\n}\n\n\n// Common form controls\n//\n// Shared size and type resets for form controls. Apply `.form-control` to any\n// of the following form controls:\n//\n// select\n// textarea\n// input[type=\"text\"]\n// input[type=\"password\"]\n// input[type=\"datetime\"]\n// input[type=\"datetime-local\"]\n// input[type=\"date\"]\n// input[type=\"month\"]\n// input[type=\"time\"]\n// input[type=\"week\"]\n// input[type=\"number\"]\n// input[type=\"email\"]\n// input[type=\"url\"]\n// input[type=\"search\"]\n// input[type=\"tel\"]\n// input[type=\"color\"]\n\n.form-control {\n display: block;\n width: 100%;\n height: @input-height-base; // Make inputs at least the height of their button counterpart (base line-height + padding + border)\n padding: @padding-base-vertical @padding-base-horizontal;\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @input-color;\n background-color: @input-bg;\n background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214\n border: 1px solid @input-border;\n border-radius: @input-border-radius; // Note: This has no effect on s in CSS.\n .box-shadow(inset 0 1px 1px rgba(0,0,0,.075));\n .transition(~\"border-color ease-in-out .15s, box-shadow ease-in-out .15s\");\n\n // Customize the `:focus` state to imitate native WebKit styles.\n .form-control-focus();\n\n // Placeholder\n .placeholder();\n\n // Disabled and read-only inputs\n //\n // HTML5 says that controls under a fieldset > legend:first-child won't be\n // disabled if the fieldset is disabled. Due to implementation difficulty, we\n // don't honor that edge case; we style them as disabled anyway.\n &[disabled],\n &[readonly],\n fieldset[disabled] & {\n cursor: @cursor-disabled;\n background-color: @input-bg-disabled;\n opacity: 1; // iOS fix for unreadable disabled content; see https://github.com/twbs/bootstrap/issues/11655\n }\n\n // Reset height for `textarea`s\n textarea& {\n height: auto;\n }\n}\n\n\n// Search inputs in iOS\n//\n// This overrides the extra rounded corners on search inputs in iOS so that our\n// `.form-control` class can properly style them. Note that this cannot simply\n// be added to `.form-control` as it's not specific enough. For details, see\n// https://github.com/twbs/bootstrap/issues/11586.\n\ninput[type=\"search\"] {\n -webkit-appearance: none;\n}\n\n\n// Special styles for iOS temporal inputs\n//\n// In Mobile Safari, setting `display: block` on temporal inputs causes the\n// text within the input to become vertically misaligned. As a workaround, we\n// set a pixel line-height that matches the given height of the input, but only\n// for Safari. See https://bugs.webkit.org/show_bug.cgi?id=139848\n\n@media screen and (-webkit-min-device-pixel-ratio: 0) {\n input[type=\"date\"],\n input[type=\"time\"],\n input[type=\"datetime-local\"],\n input[type=\"month\"] {\n line-height: @input-height-base;\n\n &.input-sm,\n .input-group-sm & {\n line-height: @input-height-small;\n }\n\n &.input-lg,\n .input-group-lg & {\n line-height: @input-height-large;\n }\n }\n}\n\n\n// Form groups\n//\n// Designed to help with the organization and spacing of vertical forms. For\n// horizontal forms, use the predefined grid classes.\n\n.form-group {\n margin-bottom: 15px;\n}\n\n\n// Checkboxes and radios\n//\n// Indent the labels to position radios/checkboxes as hanging controls.\n\n.radio,\n.checkbox {\n position: relative;\n display: block;\n margin-top: 10px;\n margin-bottom: 10px;\n\n label {\n min-height: @line-height-computed; // Ensure the input doesn't jump when there is no text\n padding-left: 20px;\n margin-bottom: 0;\n font-weight: normal;\n cursor: pointer;\n }\n}\n.radio input[type=\"radio\"],\n.radio-inline input[type=\"radio\"],\n.checkbox input[type=\"checkbox\"],\n.checkbox-inline input[type=\"checkbox\"] {\n position: absolute;\n margin-left: -20px;\n margin-top: 4px \\9;\n}\n\n.radio + .radio,\n.checkbox + .checkbox {\n margin-top: -5px; // Move up sibling radios or checkboxes for tighter spacing\n}\n\n// Radios and checkboxes on same line\n.radio-inline,\n.checkbox-inline {\n display: inline-block;\n padding-left: 20px;\n margin-bottom: 0;\n vertical-align: middle;\n font-weight: normal;\n cursor: pointer;\n}\n.radio-inline + .radio-inline,\n.checkbox-inline + .checkbox-inline {\n margin-top: 0;\n margin-left: 10px; // space out consecutive inline controls\n}\n\n// Apply same disabled cursor tweak as for inputs\n// Some special care is needed because

            ,
              , or
              .\n\n.list-group {\n // No need to set list-style: none; since .list-group-item is block level\n margin-bottom: 20px;\n padding-left: 0; // reset padding because ul and ol\n}\n\n\n// Individual list items\n//\n// Use on `li`s or `div`s within the `.list-group` parent.\n\n.list-group-item {\n position: relative;\n display: block;\n padding: 10px 15px;\n // Place the border on the list items and negative margin up for better styling\n margin-bottom: -1px;\n background-color: @list-group-bg;\n border: 1px solid @list-group-border;\n\n // Round the first and last items\n &:first-child {\n .border-top-radius(@list-group-border-radius);\n }\n &:last-child {\n margin-bottom: 0;\n .border-bottom-radius(@list-group-border-radius);\n }\n}\n\n\n// Linked list items\n//\n// Use anchor elements instead of `li`s or `div`s to create linked list items.\n// Includes an extra `.active` modifier class for showing selected items.\n\na.list-group-item {\n color: @list-group-link-color;\n\n .list-group-item-heading {\n color: @list-group-link-heading-color;\n }\n\n // Hover state\n &:hover,\n &:focus {\n text-decoration: none;\n color: @list-group-link-hover-color;\n background-color: @list-group-hover-bg;\n }\n}\n\n.list-group-item {\n // Disabled state\n &.disabled,\n &.disabled:hover,\n &.disabled:focus {\n background-color: @list-group-disabled-bg;\n color: @list-group-disabled-color;\n cursor: @cursor-disabled;\n\n // Force color to inherit for custom content\n .list-group-item-heading {\n color: inherit;\n }\n .list-group-item-text {\n color: @list-group-disabled-text-color;\n }\n }\n\n // Active class on item itself, not parent\n &.active,\n &.active:hover,\n &.active:focus {\n z-index: 2; // Place active items above their siblings for proper border styling\n color: @list-group-active-color;\n background-color: @list-group-active-bg;\n border-color: @list-group-active-border;\n\n // Force color to inherit for custom content\n .list-group-item-heading,\n .list-group-item-heading > small,\n .list-group-item-heading > .small {\n color: inherit;\n }\n .list-group-item-text {\n color: @list-group-active-text-color;\n }\n }\n}\n\n\n// Contextual variants\n//\n// Add modifier classes to change text and background color on individual items.\n// Organizationally, this must come after the `:hover` states.\n\n.list-group-item-variant(success; @state-success-bg; @state-success-text);\n.list-group-item-variant(info; @state-info-bg; @state-info-text);\n.list-group-item-variant(warning; @state-warning-bg; @state-warning-text);\n.list-group-item-variant(danger; @state-danger-bg; @state-danger-text);\n\n\n// Custom content options\n//\n// Extra classes for creating well-formatted content within `.list-group-item`s.\n\n.list-group-item-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.list-group-item-text {\n margin-bottom: 0;\n line-height: 1.3;\n}\n", + "// List Groups\n\n.list-group-item-variant(@state; @background; @color) {\n .list-group-item-@{state} {\n color: @color;\n background-color: @background;\n\n a& {\n color: @color;\n\n .list-group-item-heading {\n color: inherit;\n }\n\n &:hover,\n &:focus {\n color: @color;\n background-color: darken(@background, 5%);\n }\n &.active,\n &.active:hover,\n &.active:focus {\n color: #fff;\n background-color: @color;\n border-color: @color;\n }\n }\n }\n}\n", + "//\n// Panels\n// --------------------------------------------------\n\n\n// Base class\n.panel {\n margin-bottom: @line-height-computed;\n background-color: @panel-bg;\n border: 1px solid transparent;\n border-radius: @panel-border-radius;\n .box-shadow(0 1px 1px rgba(0,0,0,.05));\n}\n\n// Panel contents\n.panel-body {\n padding: @panel-body-padding;\n &:extend(.clearfix all);\n}\n\n// Optional heading\n.panel-heading {\n padding: @panel-heading-padding;\n border-bottom: 1px solid transparent;\n .border-top-radius((@panel-border-radius - 1));\n\n > .dropdown .dropdown-toggle {\n color: inherit;\n }\n}\n\n// Within heading, strip any `h*` tag of its default margins for spacing.\n.panel-title {\n margin-top: 0;\n margin-bottom: 0;\n font-size: ceil((@font-size-base * 1.125));\n color: inherit;\n\n > a,\n > small,\n > .small,\n > small > a,\n > .small > a {\n color: inherit;\n }\n}\n\n// Optional footer (stays gray in every modifier class)\n.panel-footer {\n padding: @panel-footer-padding;\n background-color: @panel-footer-bg;\n border-top: 1px solid @panel-inner-border;\n .border-bottom-radius((@panel-border-radius - 1));\n}\n\n\n// List groups in panels\n//\n// By default, space out list group content from panel headings to account for\n// any kind of custom content between the two.\n\n.panel {\n > .list-group,\n > .panel-collapse > .list-group {\n margin-bottom: 0;\n\n .list-group-item {\n border-width: 1px 0;\n border-radius: 0;\n }\n\n // Add border top radius for first one\n &:first-child {\n .list-group-item:first-child {\n border-top: 0;\n .border-top-radius((@panel-border-radius - 1));\n }\n }\n // Add border bottom radius for last one\n &:last-child {\n .list-group-item:last-child {\n border-bottom: 0;\n .border-bottom-radius((@panel-border-radius - 1));\n }\n }\n }\n}\n// Collapse space between when there's no additional content.\n.panel-heading + .list-group {\n .list-group-item:first-child {\n border-top-width: 0;\n }\n}\n.list-group + .panel-footer {\n border-top-width: 0;\n}\n\n// Tables in panels\n//\n// Place a non-bordered `.table` within a panel (not within a `.panel-body`) and\n// watch it go full width.\n\n.panel {\n > .table,\n > .table-responsive > .table,\n > .panel-collapse > .table {\n margin-bottom: 0;\n\n caption {\n padding-left: @panel-body-padding;\n padding-right: @panel-body-padding;\n }\n }\n // Add border top radius for first one\n > .table:first-child,\n > .table-responsive:first-child > .table:first-child {\n .border-top-radius((@panel-border-radius - 1));\n\n > thead:first-child,\n > tbody:first-child {\n > tr:first-child {\n border-top-left-radius: (@panel-border-radius - 1);\n border-top-right-radius: (@panel-border-radius - 1);\n\n td:first-child,\n th:first-child {\n border-top-left-radius: (@panel-border-radius - 1);\n }\n td:last-child,\n th:last-child {\n border-top-right-radius: (@panel-border-radius - 1);\n }\n }\n }\n }\n // Add border bottom radius for last one\n > .table:last-child,\n > .table-responsive:last-child > .table:last-child {\n .border-bottom-radius((@panel-border-radius - 1));\n\n > tbody:last-child,\n > tfoot:last-child {\n > tr:last-child {\n border-bottom-left-radius: (@panel-border-radius - 1);\n border-bottom-right-radius: (@panel-border-radius - 1);\n\n td:first-child,\n th:first-child {\n border-bottom-left-radius: (@panel-border-radius - 1);\n }\n td:last-child,\n th:last-child {\n border-bottom-right-radius: (@panel-border-radius - 1);\n }\n }\n }\n }\n > .panel-body + .table,\n > .panel-body + .table-responsive,\n > .table + .panel-body,\n > .table-responsive + .panel-body {\n border-top: 1px solid @table-border-color;\n }\n > .table > tbody:first-child > tr:first-child th,\n > .table > tbody:first-child > tr:first-child td {\n border-top: 0;\n }\n > .table-bordered,\n > .table-responsive > .table-bordered {\n border: 0;\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th:first-child,\n > td:first-child {\n border-left: 0;\n }\n > th:last-child,\n > td:last-child {\n border-right: 0;\n }\n }\n }\n > thead,\n > tbody {\n > tr:first-child {\n > td,\n > th {\n border-bottom: 0;\n }\n }\n }\n > tbody,\n > tfoot {\n > tr:last-child {\n > td,\n > th {\n border-bottom: 0;\n }\n }\n }\n }\n > .table-responsive {\n border: 0;\n margin-bottom: 0;\n }\n}\n\n\n// Collapsable panels (aka, accordion)\n//\n// Wrap a series of panels in `.panel-group` to turn them into an accordion with\n// the help of our collapse JavaScript plugin.\n\n.panel-group {\n margin-bottom: @line-height-computed;\n\n // Tighten up margin so it's only between panels\n .panel {\n margin-bottom: 0;\n border-radius: @panel-border-radius;\n\n + .panel {\n margin-top: 5px;\n }\n }\n\n .panel-heading {\n border-bottom: 0;\n\n + .panel-collapse > .panel-body,\n + .panel-collapse > .list-group {\n border-top: 1px solid @panel-inner-border;\n }\n }\n\n .panel-footer {\n border-top: 0;\n + .panel-collapse .panel-body {\n border-bottom: 1px solid @panel-inner-border;\n }\n }\n}\n\n\n// Contextual variations\n.panel-default {\n .panel-variant(@panel-default-border; @panel-default-text; @panel-default-heading-bg; @panel-default-border);\n}\n.panel-primary {\n .panel-variant(@panel-primary-border; @panel-primary-text; @panel-primary-heading-bg; @panel-primary-border);\n}\n.panel-success {\n .panel-variant(@panel-success-border; @panel-success-text; @panel-success-heading-bg; @panel-success-border);\n}\n.panel-info {\n .panel-variant(@panel-info-border; @panel-info-text; @panel-info-heading-bg; @panel-info-border);\n}\n.panel-warning {\n .panel-variant(@panel-warning-border; @panel-warning-text; @panel-warning-heading-bg; @panel-warning-border);\n}\n.panel-danger {\n .panel-variant(@panel-danger-border; @panel-danger-text; @panel-danger-heading-bg; @panel-danger-border);\n}\n", + "// Panels\n\n.panel-variant(@border; @heading-text-color; @heading-bg-color; @heading-border) {\n border-color: @border;\n\n & > .panel-heading {\n color: @heading-text-color;\n background-color: @heading-bg-color;\n border-color: @heading-border;\n\n + .panel-collapse > .panel-body {\n border-top-color: @border;\n }\n .badge {\n color: @heading-bg-color;\n background-color: @heading-text-color;\n }\n }\n & > .panel-footer {\n + .panel-collapse > .panel-body {\n border-bottom-color: @border;\n }\n }\n}\n", + "// Embeds responsive\n//\n// Credit: Nicolas Gallagher and SUIT CSS.\n\n.embed-responsive {\n position: relative;\n display: block;\n height: 0;\n padding: 0;\n overflow: hidden;\n\n .embed-responsive-item,\n iframe,\n embed,\n object,\n video {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n height: 100%;\n width: 100%;\n border: 0;\n }\n\n // Modifier class for 16:9 aspect ratio\n &.embed-responsive-16by9 {\n padding-bottom: 56.25%;\n }\n\n // Modifier class for 4:3 aspect ratio\n &.embed-responsive-4by3 {\n padding-bottom: 75%;\n }\n}\n", + "//\n// Wells\n// --------------------------------------------------\n\n\n// Base class\n.well {\n min-height: 20px;\n padding: 19px;\n margin-bottom: 20px;\n background-color: @well-bg;\n border: 1px solid @well-border;\n border-radius: @border-radius-base;\n .box-shadow(inset 0 1px 1px rgba(0,0,0,.05));\n blockquote {\n border-color: #ddd;\n border-color: rgba(0,0,0,.15);\n }\n}\n\n// Sizes\n.well-lg {\n padding: 24px;\n border-radius: @border-radius-large;\n}\n.well-sm {\n padding: 9px;\n border-radius: @border-radius-small;\n}\n", + "//\n// Close icons\n// --------------------------------------------------\n\n\n.close {\n float: right;\n font-size: (@font-size-base * 1.5);\n font-weight: @close-font-weight;\n line-height: 1;\n color: @close-color;\n text-shadow: @close-text-shadow;\n .opacity(.2);\n\n &:hover,\n &:focus {\n color: @close-color;\n text-decoration: none;\n cursor: pointer;\n .opacity(.5);\n }\n\n // Additional properties for button version\n // iOS requires the button element instead of an anchor tag.\n // If you want the anchor version, it requires `href=\"#\"`.\n // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile\n button& {\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: 0;\n -webkit-appearance: none;\n }\n}\n", + "//\n// Modals\n// --------------------------------------------------\n\n// .modal-open - body class for killing the scroll\n// .modal - container to scroll within\n// .modal-dialog - positioning shell for the actual modal\n// .modal-content - actual modal w/ bg and corners and shit\n\n// Kill the scroll on the body\n.modal-open {\n overflow: hidden;\n}\n\n// Container that the modal scrolls within\n.modal {\n display: none;\n overflow: hidden;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: @zindex-modal;\n -webkit-overflow-scrolling: touch;\n\n // Prevent Chrome on Windows from adding a focus outline. For details, see\n // https://github.com/twbs/bootstrap/pull/10951.\n outline: 0;\n\n // When fading in the modal, animate it to slide down\n &.fade .modal-dialog {\n .translate(0, -25%);\n .transition-transform(~\"0.3s ease-out\");\n }\n &.in .modal-dialog { .translate(0, 0) }\n}\n.modal-open .modal {\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n// Shell div to position the modal with bottom padding\n.modal-dialog {\n position: relative;\n width: auto;\n margin: 10px;\n}\n\n// Actual modal\n.modal-content {\n position: relative;\n background-color: @modal-content-bg;\n border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)\n border: 1px solid @modal-content-border-color;\n border-radius: @border-radius-large;\n .box-shadow(0 3px 9px rgba(0,0,0,.5));\n background-clip: padding-box;\n // Remove focus outline from opened modal\n outline: 0;\n}\n\n// Modal background\n.modal-backdrop {\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n background-color: @modal-backdrop-bg;\n // Fade for backdrop\n &.fade { .opacity(0); }\n &.in { .opacity(@modal-backdrop-opacity); }\n}\n\n// Modal header\n// Top section of the modal w/ title and dismiss\n.modal-header {\n padding: @modal-title-padding;\n border-bottom: 1px solid @modal-header-border-color;\n min-height: (@modal-title-padding + @modal-title-line-height);\n}\n// Close icon\n.modal-header .close {\n margin-top: -2px;\n}\n\n// Title text within header\n.modal-title {\n margin: 0;\n line-height: @modal-title-line-height;\n}\n\n// Modal body\n// Where all modal content resides (sibling of .modal-header and .modal-footer)\n.modal-body {\n position: relative;\n padding: @modal-inner-padding;\n}\n\n// Footer (for actions)\n.modal-footer {\n padding: @modal-inner-padding;\n text-align: right; // right align buttons\n border-top: 1px solid @modal-footer-border-color;\n &:extend(.clearfix all); // clear it in case folks use .pull-* classes on buttons\n\n // Properly space out buttons\n .btn + .btn {\n margin-left: 5px;\n margin-bottom: 0; // account for input[type=\"submit\"] which gets the bottom margin like all other inputs\n }\n // but override that for button groups\n .btn-group .btn + .btn {\n margin-left: -1px;\n }\n // and override it for block buttons as well\n .btn-block + .btn-block {\n margin-left: 0;\n }\n}\n\n// Measure scrollbar width for padding body during modal show/hide\n.modal-scrollbar-measure {\n position: absolute;\n top: -9999px;\n width: 50px;\n height: 50px;\n overflow: scroll;\n}\n\n// Scale up the modal\n@media (min-width: @screen-sm-min) {\n // Automatically set modal's width for larger viewports\n .modal-dialog {\n width: @modal-md;\n margin: 30px auto;\n }\n .modal-content {\n .box-shadow(0 5px 15px rgba(0,0,0,.5));\n }\n\n // Modal sizes\n .modal-sm { width: @modal-sm; }\n}\n\n@media (min-width: @screen-md-min) {\n .modal-lg { width: @modal-lg; }\n}\n", + "//\n// Tooltips\n// --------------------------------------------------\n\n\n// Base class\n.tooltip {\n position: absolute;\n z-index: @zindex-tooltip;\n display: block;\n visibility: visible;\n // Reset font and text properties given new insertion method\n font-family: @font-family-base;\n font-size: @font-size-small;\n font-weight: normal;\n line-height: 1.4;\n .opacity(0);\n\n &.in { .opacity(@tooltip-opacity); }\n &.top { margin-top: -3px; padding: @tooltip-arrow-width 0; }\n &.right { margin-left: 3px; padding: 0 @tooltip-arrow-width; }\n &.bottom { margin-top: 3px; padding: @tooltip-arrow-width 0; }\n &.left { margin-left: -3px; padding: 0 @tooltip-arrow-width; }\n}\n\n// Wrapper for the tooltip content\n.tooltip-inner {\n max-width: @tooltip-max-width;\n padding: 3px 8px;\n color: @tooltip-color;\n text-align: center;\n text-decoration: none;\n background-color: @tooltip-bg;\n border-radius: @border-radius-base;\n}\n\n// Arrows\n.tooltip-arrow {\n position: absolute;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n// Note: Deprecated .top-left, .top-right, .bottom-left, and .bottom-right as of v3.3.1\n.tooltip {\n &.top .tooltip-arrow {\n bottom: 0;\n left: 50%;\n margin-left: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.top-left .tooltip-arrow {\n bottom: 0;\n right: @tooltip-arrow-width;\n margin-bottom: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.top-right .tooltip-arrow {\n bottom: 0;\n left: @tooltip-arrow-width;\n margin-bottom: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.right .tooltip-arrow {\n top: 50%;\n left: 0;\n margin-top: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width @tooltip-arrow-width 0;\n border-right-color: @tooltip-arrow-color;\n }\n &.left .tooltip-arrow {\n top: 50%;\n right: 0;\n margin-top: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-left-color: @tooltip-arrow-color;\n }\n &.bottom .tooltip-arrow {\n top: 0;\n left: 50%;\n margin-left: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n &.bottom-left .tooltip-arrow {\n top: 0;\n right: @tooltip-arrow-width;\n margin-top: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n &.bottom-right .tooltip-arrow {\n top: 0;\n left: @tooltip-arrow-width;\n margin-top: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n}\n", + "//\n// Popovers\n// --------------------------------------------------\n\n\n.popover {\n position: absolute;\n top: 0;\n left: 0;\n z-index: @zindex-popover;\n display: none;\n max-width: @popover-max-width;\n padding: 1px;\n // Reset font and text properties given new insertion method\n font-family: @font-family-base;\n font-size: @font-size-base;\n font-weight: normal;\n line-height: @line-height-base;\n text-align: left;\n background-color: @popover-bg;\n background-clip: padding-box;\n border: 1px solid @popover-fallback-border-color;\n border: 1px solid @popover-border-color;\n border-radius: @border-radius-large;\n .box-shadow(0 5px 10px rgba(0,0,0,.2));\n\n // Overrides for proper insertion\n white-space: normal;\n\n // Offset the popover to account for the popover arrow\n &.top { margin-top: -@popover-arrow-width; }\n &.right { margin-left: @popover-arrow-width; }\n &.bottom { margin-top: @popover-arrow-width; }\n &.left { margin-left: -@popover-arrow-width; }\n}\n\n.popover-title {\n margin: 0; // reset heading margin\n padding: 8px 14px;\n font-size: @font-size-base;\n background-color: @popover-title-bg;\n border-bottom: 1px solid darken(@popover-title-bg, 5%);\n border-radius: (@border-radius-large - 1) (@border-radius-large - 1) 0 0;\n}\n\n.popover-content {\n padding: 9px 14px;\n}\n\n// Arrows\n//\n// .arrow is outer, .arrow:after is inner\n\n.popover > .arrow {\n &,\n &:after {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n }\n}\n.popover > .arrow {\n border-width: @popover-arrow-outer-width;\n}\n.popover > .arrow:after {\n border-width: @popover-arrow-width;\n content: \"\";\n}\n\n.popover {\n &.top > .arrow {\n left: 50%;\n margin-left: -@popover-arrow-outer-width;\n border-bottom-width: 0;\n border-top-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-top-color: @popover-arrow-outer-color;\n bottom: -@popover-arrow-outer-width;\n &:after {\n content: \" \";\n bottom: 1px;\n margin-left: -@popover-arrow-width;\n border-bottom-width: 0;\n border-top-color: @popover-arrow-color;\n }\n }\n &.right > .arrow {\n top: 50%;\n left: -@popover-arrow-outer-width;\n margin-top: -@popover-arrow-outer-width;\n border-left-width: 0;\n border-right-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-right-color: @popover-arrow-outer-color;\n &:after {\n content: \" \";\n left: 1px;\n bottom: -@popover-arrow-width;\n border-left-width: 0;\n border-right-color: @popover-arrow-color;\n }\n }\n &.bottom > .arrow {\n left: 50%;\n margin-left: -@popover-arrow-outer-width;\n border-top-width: 0;\n border-bottom-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-bottom-color: @popover-arrow-outer-color;\n top: -@popover-arrow-outer-width;\n &:after {\n content: \" \";\n top: 1px;\n margin-left: -@popover-arrow-width;\n border-top-width: 0;\n border-bottom-color: @popover-arrow-color;\n }\n }\n\n &.left > .arrow {\n top: 50%;\n right: -@popover-arrow-outer-width;\n margin-top: -@popover-arrow-outer-width;\n border-right-width: 0;\n border-left-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-left-color: @popover-arrow-outer-color;\n &:after {\n content: \" \";\n right: 1px;\n border-right-width: 0;\n border-left-color: @popover-arrow-color;\n bottom: -@popover-arrow-width;\n }\n }\n}\n", + "//\n// Carousel\n// --------------------------------------------------\n\n\n// Wrapper for the slide container and indicators\n.carousel {\n position: relative;\n}\n\n.carousel-inner {\n position: relative;\n overflow: hidden;\n width: 100%;\n\n > .item {\n display: none;\n position: relative;\n .transition(.6s ease-in-out left);\n\n // Account for jankitude on images\n > img,\n > a > img {\n &:extend(.img-responsive);\n line-height: 1;\n }\n\n // WebKit CSS3 transforms for supported devices\n @media all and (transform-3d), (-webkit-transform-3d) {\n .transition-transform(~'0.6s ease-in-out');\n .backface-visibility(~'hidden');\n .perspective(1000);\n\n &.next,\n &.active.right {\n .translate3d(100%, 0, 0);\n left: 0;\n }\n &.prev,\n &.active.left {\n .translate3d(-100%, 0, 0);\n left: 0;\n }\n &.next.left,\n &.prev.right,\n &.active {\n .translate3d(0, 0, 0);\n left: 0;\n }\n }\n }\n\n > .active,\n > .next,\n > .prev {\n display: block;\n }\n\n > .active {\n left: 0;\n }\n\n > .next,\n > .prev {\n position: absolute;\n top: 0;\n width: 100%;\n }\n\n > .next {\n left: 100%;\n }\n > .prev {\n left: -100%;\n }\n > .next.left,\n > .prev.right {\n left: 0;\n }\n\n > .active.left {\n left: -100%;\n }\n > .active.right {\n left: 100%;\n }\n\n}\n\n// Left/right controls for nav\n// ---------------------------\n\n.carousel-control {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n width: @carousel-control-width;\n .opacity(@carousel-control-opacity);\n font-size: @carousel-control-font-size;\n color: @carousel-control-color;\n text-align: center;\n text-shadow: @carousel-text-shadow;\n // We can't have this transition here because WebKit cancels the carousel\n // animation if you trip this while in the middle of another animation.\n\n // Set gradients for backgrounds\n &.left {\n #gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001));\n }\n &.right {\n left: auto;\n right: 0;\n #gradient > .horizontal(@start-color: rgba(0,0,0,.0001); @end-color: rgba(0,0,0,.5));\n }\n\n // Hover/focus state\n &:hover,\n &:focus {\n outline: 0;\n color: @carousel-control-color;\n text-decoration: none;\n .opacity(.9);\n }\n\n // Toggles\n .icon-prev,\n .icon-next,\n .glyphicon-chevron-left,\n .glyphicon-chevron-right {\n position: absolute;\n top: 50%;\n z-index: 5;\n display: inline-block;\n }\n .icon-prev,\n .glyphicon-chevron-left {\n left: 50%;\n margin-left: -10px;\n }\n .icon-next,\n .glyphicon-chevron-right {\n right: 50%;\n margin-right: -10px;\n }\n .icon-prev,\n .icon-next {\n width: 20px;\n height: 20px;\n margin-top: -10px;\n line-height: 1;\n font-family: serif;\n }\n\n\n .icon-prev {\n &:before {\n content: '\\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039)\n }\n }\n .icon-next {\n &:before {\n content: '\\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A)\n }\n }\n}\n\n// Optional indicator pips\n//\n// Add an unordered list with the following class and add a list item for each\n// slide your carousel holds.\n\n.carousel-indicators {\n position: absolute;\n bottom: 10px;\n left: 50%;\n z-index: 15;\n width: 60%;\n margin-left: -30%;\n padding-left: 0;\n list-style: none;\n text-align: center;\n\n li {\n display: inline-block;\n width: 10px;\n height: 10px;\n margin: 1px;\n text-indent: -999px;\n border: 1px solid @carousel-indicator-border-color;\n border-radius: 10px;\n cursor: pointer;\n\n // IE8-9 hack for event handling\n //\n // Internet Explorer 8-9 does not support clicks on elements without a set\n // `background-color`. We cannot use `filter` since that's not viewed as a\n // background color by the browser. Thus, a hack is needed.\n // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Internet_Explorer\n //\n // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we\n // set alpha transparency for the best results possible.\n background-color: #000 \\9; // IE8\n background-color: rgba(0,0,0,0); // IE9\n }\n .active {\n margin: 0;\n width: 12px;\n height: 12px;\n background-color: @carousel-indicator-active-bg;\n }\n}\n\n// Optional captions\n// -----------------------------\n// Hidden by default for smaller viewports\n.carousel-caption {\n position: absolute;\n left: 15%;\n right: 15%;\n bottom: 20px;\n z-index: 10;\n padding-top: 20px;\n padding-bottom: 20px;\n color: @carousel-caption-color;\n text-align: center;\n text-shadow: @carousel-text-shadow;\n & .btn {\n text-shadow: none; // No shadow for button elements in carousel-caption\n }\n}\n\n\n// Scale up controls for tablets and up\n@media screen and (min-width: @screen-sm-min) {\n\n // Scale up the controls a smidge\n .carousel-control {\n .glyphicon-chevron-left,\n .glyphicon-chevron-right,\n .icon-prev,\n .icon-next {\n width: 30px;\n height: 30px;\n margin-top: -15px;\n font-size: 30px;\n }\n .glyphicon-chevron-left,\n .icon-prev {\n margin-left: -15px;\n }\n .glyphicon-chevron-right,\n .icon-next {\n margin-right: -15px;\n }\n }\n\n // Show and left align the captions\n .carousel-caption {\n left: 20%;\n right: 20%;\n padding-bottom: 30px;\n }\n\n // Move up the indicators\n .carousel-indicators {\n bottom: 20px;\n }\n}\n", + "// Clearfix\n//\n// For modern browsers\n// 1. The space content is one way to avoid an Opera bug when the\n// contenteditable attribute is included anywhere else in the document.\n// Otherwise it causes space to appear at the top and bottom of elements\n// that are clearfixed.\n// 2. The use of `table` rather than `block` is only necessary if using\n// `:before` to contain the top-margins of child elements.\n//\n// Source: http://nicolasgallagher.com/micro-clearfix-hack/\n\n.clearfix() {\n &:before,\n &:after {\n content: \" \"; // 1\n display: table; // 2\n }\n &:after {\n clear: both;\n }\n}\n", + "// Center-align a block level element\n\n.center-block() {\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n", + "// CSS image replacement\n//\n// Heads up! v3 launched with with only `.hide-text()`, but per our pattern for\n// mixins being reused as classes with the same name, this doesn't hold up. As\n// of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`.\n//\n// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757\n\n// Deprecated as of v3.0.1 (will be removed in v4)\n.hide-text() {\n font: ~\"0/0\" a;\n color: transparent;\n text-shadow: none;\n background-color: transparent;\n border: 0;\n}\n\n// New mixin to use as of v3.0.1\n.text-hide() {\n .hide-text();\n}\n", + "//\n// Responsive: Utility classes\n// --------------------------------------------------\n\n\n// IE10 in Windows (Phone) 8\n//\n// Support for responsive views via media queries is kind of borked in IE10, for\n// Surface/desktop in split view and for Windows Phone 8. This particular fix\n// must be accompanied by a snippet of JavaScript to sniff the user agent and\n// apply some conditional CSS to *only* the Surface/desktop Windows 8. Look at\n// our Getting Started page for more information on this bug.\n//\n// For more information, see the following:\n//\n// Issue: https://github.com/twbs/bootstrap/issues/10497\n// Docs: http://getbootstrap.com/getting-started/#support-ie10-width\n// Source: http://timkadlec.com/2013/01/windows-phone-8-and-device-width/\n// Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/\n\n@-ms-viewport {\n width: device-width;\n}\n\n\n// Visibility utilities\n// Note: Deprecated .visible-xs, .visible-sm, .visible-md, and .visible-lg as of v3.2.0\n.visible-xs,\n.visible-sm,\n.visible-md,\n.visible-lg {\n .responsive-invisibility();\n}\n\n.visible-xs-block,\n.visible-xs-inline,\n.visible-xs-inline-block,\n.visible-sm-block,\n.visible-sm-inline,\n.visible-sm-inline-block,\n.visible-md-block,\n.visible-md-inline,\n.visible-md-inline-block,\n.visible-lg-block,\n.visible-lg-inline,\n.visible-lg-inline-block {\n display: none !important;\n}\n\n.visible-xs {\n @media (max-width: @screen-xs-max) {\n .responsive-visibility();\n }\n}\n.visible-xs-block {\n @media (max-width: @screen-xs-max) {\n display: block !important;\n }\n}\n.visible-xs-inline {\n @media (max-width: @screen-xs-max) {\n display: inline !important;\n }\n}\n.visible-xs-inline-block {\n @media (max-width: @screen-xs-max) {\n display: inline-block !important;\n }\n}\n\n.visible-sm {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n .responsive-visibility();\n }\n}\n.visible-sm-block {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: block !important;\n }\n}\n.visible-sm-inline {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: inline !important;\n }\n}\n.visible-sm-inline-block {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: inline-block !important;\n }\n}\n\n.visible-md {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n .responsive-visibility();\n }\n}\n.visible-md-block {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: block !important;\n }\n}\n.visible-md-inline {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: inline !important;\n }\n}\n.visible-md-inline-block {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: inline-block !important;\n }\n}\n\n.visible-lg {\n @media (min-width: @screen-lg-min) {\n .responsive-visibility();\n }\n}\n.visible-lg-block {\n @media (min-width: @screen-lg-min) {\n display: block !important;\n }\n}\n.visible-lg-inline {\n @media (min-width: @screen-lg-min) {\n display: inline !important;\n }\n}\n.visible-lg-inline-block {\n @media (min-width: @screen-lg-min) {\n display: inline-block !important;\n }\n}\n\n.hidden-xs {\n @media (max-width: @screen-xs-max) {\n .responsive-invisibility();\n }\n}\n.hidden-sm {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n .responsive-invisibility();\n }\n}\n.hidden-md {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n .responsive-invisibility();\n }\n}\n.hidden-lg {\n @media (min-width: @screen-lg-min) {\n .responsive-invisibility();\n }\n}\n\n\n// Print utilities\n//\n// Media queries are placed on the inside to be mixin-friendly.\n\n// Note: Deprecated .visible-print as of v3.2.0\n.visible-print {\n .responsive-invisibility();\n\n @media print {\n .responsive-visibility();\n }\n}\n.visible-print-block {\n display: none !important;\n\n @media print {\n display: block !important;\n }\n}\n.visible-print-inline {\n display: none !important;\n\n @media print {\n display: inline !important;\n }\n}\n.visible-print-inline-block {\n display: none !important;\n\n @media print {\n display: inline-block !important;\n }\n}\n\n.hidden-print {\n @media print {\n .responsive-invisibility();\n }\n}\n", + "// Responsive utilities\n\n//\n// More easily include all the states for responsive-utilities.less.\n.responsive-visibility() {\n display: block !important;\n table& { display: table; }\n tr& { display: table-row !important; }\n th&,\n td& { display: table-cell !important; }\n}\n\n.responsive-invisibility() {\n display: none !important;\n}\n" + ] +} \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/css/libs/fontawesome/font-awesome.css b/projects/webui/base/src/main/resources/css/libs/fontawesome/font-awesome.css index 2dcdc220..91d34006 100644 --- a/projects/webui/base/src/main/resources/css/libs/fontawesome/font-awesome.css +++ b/projects/webui/base/src/main/resources/css/libs/fontawesome/font-awesome.css @@ -5,1797 +5,2347 @@ /* FONT PATH * -------------------------- */ @font-face { - font-family: 'FontAwesome'; - src: url('../fonts/fontawesome-webfont.eot?v=4.3.0'); - src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.3.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.3.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.3.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular') format('svg'); - font-weight: normal; - font-style: normal; + font-family: 'FontAwesome'; + src: url('../fonts/fontawesome-webfont.eot?v=4.3.0'); + src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.3.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.3.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.3.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular') format('svg'); + font-weight: normal; + font-style: normal; } + .fa { - display: inline-block; - font: normal normal normal 14px/1 FontAwesome; - font-size: inherit; - text-rendering: auto; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - transform: translate(0, 0); -} + display: inline-block; + font: normal normal normal 14px/1 FontAwesome; + font-size: inherit; + text-rendering: auto; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + transform: translate(0, 0); +} + /* makes the font 33% larger relative to the icon container */ .fa-lg { - font-size: 1.33333333em; - line-height: 0.75em; - vertical-align: -15%; + font-size: 1.33333333em; + line-height: 0.75em; + vertical-align: -15%; } + .fa-2x { - font-size: 2em; + font-size: 2em; } + .fa-3x { - font-size: 3em; + font-size: 3em; } + .fa-4x { - font-size: 4em; + font-size: 4em; } + .fa-5x { - font-size: 5em; + font-size: 5em; } + .fa-fw { - width: 1.28571429em; - text-align: center; + width: 1.28571429em; + text-align: center; } + .fa-ul { - padding-left: 0; - margin-left: 2.14285714em; - list-style-type: none; + padding-left: 0; + margin-left: 2.14285714em; + list-style-type: none; } + .fa-ul > li { - position: relative; + position: relative; } + .fa-li { - position: absolute; - left: -2.14285714em; - width: 2.14285714em; - top: 0.14285714em; - text-align: center; + position: absolute; + left: -2.14285714em; + width: 2.14285714em; + top: 0.14285714em; + text-align: center; } + .fa-li.fa-lg { - left: -1.85714286em; + left: -1.85714286em; } + .fa-border { - padding: .2em .25em .15em; - border: solid 0.08em #eeeeee; - border-radius: .1em; + padding: .2em .25em .15em; + border: solid 0.08em #eeeeee; + border-radius: .1em; } + .pull-right { - float: right; + float: right; } + .pull-left { - float: left; + float: left; } + .fa.pull-left { - margin-right: .3em; + margin-right: .3em; } + .fa.pull-right { - margin-left: .3em; + margin-left: .3em; } + .fa-spin { - -webkit-animation: fa-spin 2s infinite linear; - animation: fa-spin 2s infinite linear; + -webkit-animation: fa-spin 2s infinite linear; + animation: fa-spin 2s infinite linear; } + .fa-pulse { - -webkit-animation: fa-spin 1s infinite steps(8); - animation: fa-spin 1s infinite steps(8); + -webkit-animation: fa-spin 1s infinite steps(8); + animation: fa-spin 1s infinite steps(8); } + @-webkit-keyframes fa-spin { - 0% { - -webkit-transform: rotate(0deg); - transform: rotate(0deg); - } - 100% { - -webkit-transform: rotate(359deg); - transform: rotate(359deg); - } -} + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} + @keyframes fa-spin { - 0% { - -webkit-transform: rotate(0deg); - transform: rotate(0deg); - } - 100% { - -webkit-transform: rotate(359deg); - transform: rotate(359deg); - } -} + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(359deg); + transform: rotate(359deg); + } +} + .fa-rotate-90 { - filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); - -webkit-transform: rotate(90deg); - -ms-transform: rotate(90deg); - transform: rotate(90deg); + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); + -webkit-transform: rotate(90deg); + -ms-transform: rotate(90deg); + transform: rotate(90deg); } + .fa-rotate-180 { - filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); - -webkit-transform: rotate(180deg); - -ms-transform: rotate(180deg); - transform: rotate(180deg); + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); + -webkit-transform: rotate(180deg); + -ms-transform: rotate(180deg); + transform: rotate(180deg); } + .fa-rotate-270 { - filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); - -webkit-transform: rotate(270deg); - -ms-transform: rotate(270deg); - transform: rotate(270deg); + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -webkit-transform: rotate(270deg); + -ms-transform: rotate(270deg); + transform: rotate(270deg); } + .fa-flip-horizontal { - filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1); - -webkit-transform: scale(-1, 1); - -ms-transform: scale(-1, 1); - transform: scale(-1, 1); + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1); + -webkit-transform: scale(-1, 1); + -ms-transform: scale(-1, 1); + transform: scale(-1, 1); } + .fa-flip-vertical { - filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1); - -webkit-transform: scale(1, -1); - -ms-transform: scale(1, -1); - transform: scale(1, -1); + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1); + -webkit-transform: scale(1, -1); + -ms-transform: scale(1, -1); + transform: scale(1, -1); } + :root .fa-rotate-90, :root .fa-rotate-180, :root .fa-rotate-270, :root .fa-flip-horizontal, :root .fa-flip-vertical { - filter: none; + filter: none; } + .fa-stack { - position: relative; - display: inline-block; - width: 2em; - height: 2em; - line-height: 2em; - vertical-align: middle; -} + position: relative; + display: inline-block; + width: 2em; + height: 2em; + line-height: 2em; + vertical-align: middle; +} + .fa-stack-1x, .fa-stack-2x { - position: absolute; - left: 0; - width: 100%; - text-align: center; + position: absolute; + left: 0; + width: 100%; + text-align: center; } + .fa-stack-1x { - line-height: inherit; + line-height: inherit; } + .fa-stack-2x { - font-size: 2em; + font-size: 2em; } + .fa-inverse { - color: #ffffff; + color: #ffffff; } + /* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent icons */ .fa-glass:before { - content: "\f000"; + content: "\f000"; } + .fa-music:before { - content: "\f001"; + content: "\f001"; } + .fa-search:before { - content: "\f002"; + content: "\f002"; } + .fa-envelope-o:before { - content: "\f003"; + content: "\f003"; } + .fa-heart:before { - content: "\f004"; + content: "\f004"; } + .fa-star:before { - content: "\f005"; + content: "\f005"; } + .fa-star-o:before { - content: "\f006"; + content: "\f006"; } + .fa-user:before { - content: "\f007"; + content: "\f007"; } + .fa-film:before { - content: "\f008"; + content: "\f008"; } + .fa-th-large:before { - content: "\f009"; + content: "\f009"; } + .fa-th:before { - content: "\f00a"; + content: "\f00a"; } + .fa-th-list:before { - content: "\f00b"; + content: "\f00b"; } + .fa-check:before { - content: "\f00c"; + content: "\f00c"; } + .fa-remove:before, .fa-close:before, .fa-times:before { - content: "\f00d"; + content: "\f00d"; } + .fa-search-plus:before { - content: "\f00e"; + content: "\f00e"; } + .fa-search-minus:before { - content: "\f010"; + content: "\f010"; } + .fa-power-off:before { - content: "\f011"; + content: "\f011"; } + .fa-signal:before { - content: "\f012"; + content: "\f012"; } + .fa-gear:before, .fa-cog:before { - content: "\f013"; + content: "\f013"; } + .fa-trash-o:before { - content: "\f014"; + content: "\f014"; } + .fa-home:before { - content: "\f015"; + content: "\f015"; } + .fa-file-o:before { - content: "\f016"; + content: "\f016"; } + .fa-clock-o:before { - content: "\f017"; + content: "\f017"; } + .fa-road:before { - content: "\f018"; + content: "\f018"; } + .fa-download:before { - content: "\f019"; + content: "\f019"; } + .fa-arrow-circle-o-down:before { - content: "\f01a"; + content: "\f01a"; } + .fa-arrow-circle-o-up:before { - content: "\f01b"; + content: "\f01b"; } + .fa-inbox:before { - content: "\f01c"; + content: "\f01c"; } + .fa-play-circle-o:before { - content: "\f01d"; + content: "\f01d"; } + .fa-rotate-right:before, .fa-repeat:before { - content: "\f01e"; + content: "\f01e"; } + .fa-refresh:before { - content: "\f021"; + content: "\f021"; } + .fa-list-alt:before { - content: "\f022"; + content: "\f022"; } + .fa-lock:before { - content: "\f023"; + content: "\f023"; } + .fa-flag:before { - content: "\f024"; + content: "\f024"; } + .fa-headphones:before { - content: "\f025"; + content: "\f025"; } + .fa-volume-off:before { - content: "\f026"; + content: "\f026"; } + .fa-volume-down:before { - content: "\f027"; + content: "\f027"; } + .fa-volume-up:before { - content: "\f028"; + content: "\f028"; } + .fa-qrcode:before { - content: "\f029"; + content: "\f029"; } + .fa-barcode:before { - content: "\f02a"; + content: "\f02a"; } + .fa-tag:before { - content: "\f02b"; + content: "\f02b"; } + .fa-tags:before { - content: "\f02c"; + content: "\f02c"; } + .fa-book:before { - content: "\f02d"; + content: "\f02d"; } + .fa-bookmark:before { - content: "\f02e"; + content: "\f02e"; } + .fa-print:before { - content: "\f02f"; + content: "\f02f"; } + .fa-camera:before { - content: "\f030"; + content: "\f030"; } + .fa-font:before { - content: "\f031"; + content: "\f031"; } + .fa-bold:before { - content: "\f032"; + content: "\f032"; } + .fa-italic:before { - content: "\f033"; + content: "\f033"; } + .fa-text-height:before { - content: "\f034"; + content: "\f034"; } + .fa-text-width:before { - content: "\f035"; + content: "\f035"; } + .fa-align-left:before { - content: "\f036"; + content: "\f036"; } + .fa-align-center:before { - content: "\f037"; + content: "\f037"; } + .fa-align-right:before { - content: "\f038"; + content: "\f038"; } + .fa-align-justify:before { - content: "\f039"; + content: "\f039"; } + .fa-list:before { - content: "\f03a"; + content: "\f03a"; } + .fa-dedent:before, .fa-outdent:before { - content: "\f03b"; + content: "\f03b"; } + .fa-indent:before { - content: "\f03c"; + content: "\f03c"; } + .fa-video-camera:before { - content: "\f03d"; + content: "\f03d"; } + .fa-photo:before, .fa-image:before, .fa-picture-o:before { - content: "\f03e"; + content: "\f03e"; } + .fa-pencil:before { - content: "\f040"; + content: "\f040"; } + .fa-map-marker:before { - content: "\f041"; + content: "\f041"; } + .fa-adjust:before { - content: "\f042"; + content: "\f042"; } + .fa-tint:before { - content: "\f043"; + content: "\f043"; } + .fa-edit:before, .fa-pencil-square-o:before { - content: "\f044"; + content: "\f044"; } + .fa-share-square-o:before { - content: "\f045"; + content: "\f045"; } + .fa-check-square-o:before { - content: "\f046"; + content: "\f046"; } + .fa-arrows:before { - content: "\f047"; + content: "\f047"; } + .fa-step-backward:before { - content: "\f048"; + content: "\f048"; } + .fa-fast-backward:before { - content: "\f049"; + content: "\f049"; } + .fa-backward:before { - content: "\f04a"; + content: "\f04a"; } + .fa-play:before { - content: "\f04b"; + content: "\f04b"; } + .fa-pause:before { - content: "\f04c"; + content: "\f04c"; } + .fa-stop:before { - content: "\f04d"; + content: "\f04d"; } + .fa-forward:before { - content: "\f04e"; + content: "\f04e"; } + .fa-fast-forward:before { - content: "\f050"; + content: "\f050"; } + .fa-step-forward:before { - content: "\f051"; + content: "\f051"; } + .fa-eject:before { - content: "\f052"; + content: "\f052"; } + .fa-chevron-left:before { - content: "\f053"; + content: "\f053"; } + .fa-chevron-right:before { - content: "\f054"; + content: "\f054"; } + .fa-plus-circle:before { - content: "\f055"; + content: "\f055"; } + .fa-minus-circle:before { - content: "\f056"; + content: "\f056"; } + .fa-times-circle:before { - content: "\f057"; + content: "\f057"; } + .fa-check-circle:before { - content: "\f058"; + content: "\f058"; } + .fa-question-circle:before { - content: "\f059"; + content: "\f059"; } + .fa-info-circle:before { - content: "\f05a"; + content: "\f05a"; } + .fa-crosshairs:before { - content: "\f05b"; + content: "\f05b"; } + .fa-times-circle-o:before { - content: "\f05c"; + content: "\f05c"; } + .fa-check-circle-o:before { - content: "\f05d"; + content: "\f05d"; } + .fa-ban:before { - content: "\f05e"; + content: "\f05e"; } + .fa-arrow-left:before { - content: "\f060"; + content: "\f060"; } + .fa-arrow-right:before { - content: "\f061"; + content: "\f061"; } + .fa-arrow-up:before { - content: "\f062"; + content: "\f062"; } + .fa-arrow-down:before { - content: "\f063"; + content: "\f063"; } + .fa-mail-forward:before, .fa-share:before { - content: "\f064"; + content: "\f064"; } + .fa-expand:before { - content: "\f065"; + content: "\f065"; } + .fa-compress:before { - content: "\f066"; + content: "\f066"; } + .fa-plus:before { - content: "\f067"; + content: "\f067"; } + .fa-minus:before { - content: "\f068"; + content: "\f068"; } + .fa-asterisk:before { - content: "\f069"; + content: "\f069"; } + .fa-exclamation-circle:before { - content: "\f06a"; + content: "\f06a"; } + .fa-gift:before { - content: "\f06b"; + content: "\f06b"; } + .fa-leaf:before { - content: "\f06c"; + content: "\f06c"; } + .fa-fire:before { - content: "\f06d"; + content: "\f06d"; } + .fa-eye:before { - content: "\f06e"; + content: "\f06e"; } + .fa-eye-slash:before { - content: "\f070"; + content: "\f070"; } + .fa-warning:before, .fa-exclamation-triangle:before { - content: "\f071"; + content: "\f071"; } + .fa-plane:before { - content: "\f072"; + content: "\f072"; } + .fa-calendar:before { - content: "\f073"; + content: "\f073"; } + .fa-random:before { - content: "\f074"; + content: "\f074"; } + .fa-comment:before { - content: "\f075"; + content: "\f075"; } + .fa-magnet:before { - content: "\f076"; + content: "\f076"; } + .fa-chevron-up:before { - content: "\f077"; + content: "\f077"; } + .fa-chevron-down:before { - content: "\f078"; + content: "\f078"; } + .fa-retweet:before { - content: "\f079"; + content: "\f079"; } + .fa-shopping-cart:before { - content: "\f07a"; + content: "\f07a"; } + .fa-folder:before { - content: "\f07b"; + content: "\f07b"; } + .fa-folder-open:before { - content: "\f07c"; + content: "\f07c"; } + .fa-arrows-v:before { - content: "\f07d"; + content: "\f07d"; } + .fa-arrows-h:before { - content: "\f07e"; + content: "\f07e"; } + .fa-bar-chart-o:before, .fa-bar-chart:before { - content: "\f080"; + content: "\f080"; } + .fa-twitter-square:before { - content: "\f081"; + content: "\f081"; } + .fa-facebook-square:before { - content: "\f082"; + content: "\f082"; } + .fa-camera-retro:before { - content: "\f083"; + content: "\f083"; } + .fa-key:before { - content: "\f084"; + content: "\f084"; } + .fa-gears:before, .fa-cogs:before { - content: "\f085"; + content: "\f085"; } + .fa-comments:before { - content: "\f086"; + content: "\f086"; } + .fa-thumbs-o-up:before { - content: "\f087"; + content: "\f087"; } + .fa-thumbs-o-down:before { - content: "\f088"; + content: "\f088"; } + .fa-star-half:before { - content: "\f089"; + content: "\f089"; } + .fa-heart-o:before { - content: "\f08a"; + content: "\f08a"; } + .fa-sign-out:before { - content: "\f08b"; + content: "\f08b"; } + .fa-linkedin-square:before { - content: "\f08c"; + content: "\f08c"; } + .fa-thumb-tack:before { - content: "\f08d"; + content: "\f08d"; } + .fa-external-link:before { - content: "\f08e"; + content: "\f08e"; } + .fa-sign-in:before { - content: "\f090"; + content: "\f090"; } + .fa-trophy:before { - content: "\f091"; + content: "\f091"; } + .fa-github-square:before { - content: "\f092"; + content: "\f092"; } + .fa-upload:before { - content: "\f093"; + content: "\f093"; } + .fa-lemon-o:before { - content: "\f094"; + content: "\f094"; } + .fa-phone:before { - content: "\f095"; + content: "\f095"; } + .fa-square-o:before { - content: "\f096"; + content: "\f096"; } + .fa-bookmark-o:before { - content: "\f097"; + content: "\f097"; } + .fa-phone-square:before { - content: "\f098"; + content: "\f098"; } + .fa-twitter:before { - content: "\f099"; + content: "\f099"; } + .fa-facebook-f:before, .fa-facebook:before { - content: "\f09a"; + content: "\f09a"; } + .fa-github:before { - content: "\f09b"; + content: "\f09b"; } + .fa-unlock:before { - content: "\f09c"; + content: "\f09c"; } + .fa-credit-card:before { - content: "\f09d"; + content: "\f09d"; } + .fa-rss:before { - content: "\f09e"; + content: "\f09e"; } + .fa-hdd-o:before { - content: "\f0a0"; + content: "\f0a0"; } + .fa-bullhorn:before { - content: "\f0a1"; + content: "\f0a1"; } + .fa-bell:before { - content: "\f0f3"; + content: "\f0f3"; } + .fa-certificate:before { - content: "\f0a3"; + content: "\f0a3"; } + .fa-hand-o-right:before { - content: "\f0a4"; + content: "\f0a4"; } + .fa-hand-o-left:before { - content: "\f0a5"; + content: "\f0a5"; } + .fa-hand-o-up:before { - content: "\f0a6"; + content: "\f0a6"; } + .fa-hand-o-down:before { - content: "\f0a7"; + content: "\f0a7"; } + .fa-arrow-circle-left:before { - content: "\f0a8"; + content: "\f0a8"; } + .fa-arrow-circle-right:before { - content: "\f0a9"; + content: "\f0a9"; } + .fa-arrow-circle-up:before { - content: "\f0aa"; + content: "\f0aa"; } + .fa-arrow-circle-down:before { - content: "\f0ab"; + content: "\f0ab"; } + .fa-globe:before { - content: "\f0ac"; + content: "\f0ac"; } + .fa-wrench:before { - content: "\f0ad"; + content: "\f0ad"; } + .fa-tasks:before { - content: "\f0ae"; + content: "\f0ae"; } + .fa-filter:before { - content: "\f0b0"; + content: "\f0b0"; } + .fa-briefcase:before { - content: "\f0b1"; + content: "\f0b1"; } + .fa-arrows-alt:before { - content: "\f0b2"; + content: "\f0b2"; } + .fa-group:before, .fa-users:before { - content: "\f0c0"; + content: "\f0c0"; } + .fa-chain:before, .fa-link:before { - content: "\f0c1"; + content: "\f0c1"; } + .fa-cloud:before { - content: "\f0c2"; + content: "\f0c2"; } + .fa-flask:before { - content: "\f0c3"; + content: "\f0c3"; } + .fa-cut:before, .fa-scissors:before { - content: "\f0c4"; + content: "\f0c4"; } + .fa-copy:before, .fa-files-o:before { - content: "\f0c5"; + content: "\f0c5"; } + .fa-paperclip:before { - content: "\f0c6"; + content: "\f0c6"; } + .fa-save:before, .fa-floppy-o:before { - content: "\f0c7"; + content: "\f0c7"; } + .fa-square:before { - content: "\f0c8"; + content: "\f0c8"; } + .fa-navicon:before, .fa-reorder:before, .fa-bars:before { - content: "\f0c9"; + content: "\f0c9"; } + .fa-list-ul:before { - content: "\f0ca"; + content: "\f0ca"; } + .fa-list-ol:before { - content: "\f0cb"; + content: "\f0cb"; } + .fa-strikethrough:before { - content: "\f0cc"; + content: "\f0cc"; } + .fa-underline:before { - content: "\f0cd"; + content: "\f0cd"; } + .fa-table:before { - content: "\f0ce"; + content: "\f0ce"; } + .fa-magic:before { - content: "\f0d0"; + content: "\f0d0"; } + .fa-truck:before { - content: "\f0d1"; + content: "\f0d1"; } + .fa-pinterest:before { - content: "\f0d2"; + content: "\f0d2"; } + .fa-pinterest-square:before { - content: "\f0d3"; + content: "\f0d3"; } + .fa-google-plus-square:before { - content: "\f0d4"; + content: "\f0d4"; } + .fa-google-plus:before { - content: "\f0d5"; + content: "\f0d5"; } + .fa-money:before { - content: "\f0d6"; + content: "\f0d6"; } + .fa-caret-down:before { - content: "\f0d7"; + content: "\f0d7"; } + .fa-caret-up:before { - content: "\f0d8"; + content: "\f0d8"; } + .fa-caret-left:before { - content: "\f0d9"; + content: "\f0d9"; } + .fa-caret-right:before { - content: "\f0da"; + content: "\f0da"; } + .fa-columns:before { - content: "\f0db"; + content: "\f0db"; } + .fa-unsorted:before, .fa-sort:before { - content: "\f0dc"; + content: "\f0dc"; } + .fa-sort-down:before, .fa-sort-desc:before { - content: "\f0dd"; + content: "\f0dd"; } + .fa-sort-up:before, .fa-sort-asc:before { - content: "\f0de"; + content: "\f0de"; } + .fa-envelope:before { - content: "\f0e0"; + content: "\f0e0"; } + .fa-linkedin:before { - content: "\f0e1"; + content: "\f0e1"; } + .fa-rotate-left:before, .fa-undo:before { - content: "\f0e2"; + content: "\f0e2"; } + .fa-legal:before, .fa-gavel:before { - content: "\f0e3"; + content: "\f0e3"; } + .fa-dashboard:before, .fa-tachometer:before { - content: "\f0e4"; + content: "\f0e4"; } + .fa-comment-o:before { - content: "\f0e5"; + content: "\f0e5"; } + .fa-comments-o:before { - content: "\f0e6"; + content: "\f0e6"; } + .fa-flash:before, .fa-bolt:before { - content: "\f0e7"; + content: "\f0e7"; } + .fa-sitemap:before { - content: "\f0e8"; + content: "\f0e8"; } + .fa-umbrella:before { - content: "\f0e9"; + content: "\f0e9"; } + .fa-paste:before, .fa-clipboard:before { - content: "\f0ea"; + content: "\f0ea"; } + .fa-lightbulb-o:before { - content: "\f0eb"; + content: "\f0eb"; } + .fa-exchange:before { - content: "\f0ec"; + content: "\f0ec"; } + .fa-cloud-download:before { - content: "\f0ed"; + content: "\f0ed"; } + .fa-cloud-upload:before { - content: "\f0ee"; + content: "\f0ee"; } + .fa-user-md:before { - content: "\f0f0"; + content: "\f0f0"; } + .fa-stethoscope:before { - content: "\f0f1"; + content: "\f0f1"; } + .fa-suitcase:before { - content: "\f0f2"; + content: "\f0f2"; } + .fa-bell-o:before { - content: "\f0a2"; + content: "\f0a2"; } + .fa-coffee:before { - content: "\f0f4"; + content: "\f0f4"; } + .fa-cutlery:before { - content: "\f0f5"; + content: "\f0f5"; } + .fa-file-text-o:before { - content: "\f0f6"; + content: "\f0f6"; } + .fa-building-o:before { - content: "\f0f7"; + content: "\f0f7"; } + .fa-hospital-o:before { - content: "\f0f8"; + content: "\f0f8"; } + .fa-ambulance:before { - content: "\f0f9"; + content: "\f0f9"; } + .fa-medkit:before { - content: "\f0fa"; + content: "\f0fa"; } + .fa-fighter-jet:before { - content: "\f0fb"; + content: "\f0fb"; } + .fa-beer:before { - content: "\f0fc"; + content: "\f0fc"; } + .fa-h-square:before { - content: "\f0fd"; + content: "\f0fd"; } + .fa-plus-square:before { - content: "\f0fe"; + content: "\f0fe"; } + .fa-angle-double-left:before { - content: "\f100"; + content: "\f100"; } + .fa-angle-double-right:before { - content: "\f101"; + content: "\f101"; } + .fa-angle-double-up:before { - content: "\f102"; + content: "\f102"; } + .fa-angle-double-down:before { - content: "\f103"; + content: "\f103"; } + .fa-angle-left:before { - content: "\f104"; + content: "\f104"; } + .fa-angle-right:before { - content: "\f105"; + content: "\f105"; } + .fa-angle-up:before { - content: "\f106"; + content: "\f106"; } + .fa-angle-down:before { - content: "\f107"; + content: "\f107"; } + .fa-desktop:before { - content: "\f108"; + content: "\f108"; } + .fa-laptop:before { - content: "\f109"; + content: "\f109"; } + .fa-tablet:before { - content: "\f10a"; + content: "\f10a"; } + .fa-mobile-phone:before, .fa-mobile:before { - content: "\f10b"; + content: "\f10b"; } + .fa-circle-o:before { - content: "\f10c"; + content: "\f10c"; } + .fa-quote-left:before { - content: "\f10d"; + content: "\f10d"; } + .fa-quote-right:before { - content: "\f10e"; + content: "\f10e"; } + .fa-spinner:before { - content: "\f110"; + content: "\f110"; } + .fa-circle:before { - content: "\f111"; + content: "\f111"; } + .fa-mail-reply:before, .fa-reply:before { - content: "\f112"; + content: "\f112"; } + .fa-github-alt:before { - content: "\f113"; + content: "\f113"; } + .fa-folder-o:before { - content: "\f114"; + content: "\f114"; } + .fa-folder-open-o:before { - content: "\f115"; + content: "\f115"; } + .fa-smile-o:before { - content: "\f118"; + content: "\f118"; } + .fa-frown-o:before { - content: "\f119"; + content: "\f119"; } + .fa-meh-o:before { - content: "\f11a"; + content: "\f11a"; } + .fa-gamepad:before { - content: "\f11b"; + content: "\f11b"; } + .fa-keyboard-o:before { - content: "\f11c"; + content: "\f11c"; } + .fa-flag-o:before { - content: "\f11d"; + content: "\f11d"; } + .fa-flag-checkered:before { - content: "\f11e"; + content: "\f11e"; } + .fa-terminal:before { - content: "\f120"; + content: "\f120"; } + .fa-code:before { - content: "\f121"; + content: "\f121"; } + .fa-mail-reply-all:before, .fa-reply-all:before { - content: "\f122"; + content: "\f122"; } + .fa-star-half-empty:before, .fa-star-half-full:before, .fa-star-half-o:before { - content: "\f123"; + content: "\f123"; } + .fa-location-arrow:before { - content: "\f124"; + content: "\f124"; } + .fa-crop:before { - content: "\f125"; + content: "\f125"; } + .fa-code-fork:before { - content: "\f126"; + content: "\f126"; } + .fa-unlink:before, .fa-chain-broken:before { - content: "\f127"; + content: "\f127"; } + .fa-question:before { - content: "\f128"; + content: "\f128"; } + .fa-info:before { - content: "\f129"; + content: "\f129"; } + .fa-exclamation:before { - content: "\f12a"; + content: "\f12a"; } + .fa-superscript:before { - content: "\f12b"; + content: "\f12b"; } + .fa-subscript:before { - content: "\f12c"; + content: "\f12c"; } + .fa-eraser:before { - content: "\f12d"; + content: "\f12d"; } + .fa-puzzle-piece:before { - content: "\f12e"; + content: "\f12e"; } + .fa-microphone:before { - content: "\f130"; + content: "\f130"; } + .fa-microphone-slash:before { - content: "\f131"; + content: "\f131"; } + .fa-shield:before { - content: "\f132"; + content: "\f132"; } + .fa-calendar-o:before { - content: "\f133"; + content: "\f133"; } + .fa-fire-extinguisher:before { - content: "\f134"; + content: "\f134"; } + .fa-rocket:before { - content: "\f135"; + content: "\f135"; } + .fa-maxcdn:before { - content: "\f136"; + content: "\f136"; } + .fa-chevron-circle-left:before { - content: "\f137"; + content: "\f137"; } + .fa-chevron-circle-right:before { - content: "\f138"; + content: "\f138"; } + .fa-chevron-circle-up:before { - content: "\f139"; + content: "\f139"; } + .fa-chevron-circle-down:before { - content: "\f13a"; + content: "\f13a"; } + .fa-html5:before { - content: "\f13b"; + content: "\f13b"; } + .fa-css3:before { - content: "\f13c"; + content: "\f13c"; } + .fa-anchor:before { - content: "\f13d"; + content: "\f13d"; } + .fa-unlock-alt:before { - content: "\f13e"; + content: "\f13e"; } + .fa-bullseye:before { - content: "\f140"; + content: "\f140"; } + .fa-ellipsis-h:before { - content: "\f141"; + content: "\f141"; } + .fa-ellipsis-v:before { - content: "\f142"; + content: "\f142"; } + .fa-rss-square:before { - content: "\f143"; + content: "\f143"; } + .fa-play-circle:before { - content: "\f144"; + content: "\f144"; } + .fa-ticket:before { - content: "\f145"; + content: "\f145"; } + .fa-minus-square:before { - content: "\f146"; + content: "\f146"; } + .fa-minus-square-o:before { - content: "\f147"; + content: "\f147"; } + .fa-level-up:before { - content: "\f148"; + content: "\f148"; } + .fa-level-down:before { - content: "\f149"; + content: "\f149"; } + .fa-check-square:before { - content: "\f14a"; + content: "\f14a"; } + .fa-pencil-square:before { - content: "\f14b"; + content: "\f14b"; } + .fa-external-link-square:before { - content: "\f14c"; + content: "\f14c"; } + .fa-share-square:before { - content: "\f14d"; + content: "\f14d"; } + .fa-compass:before { - content: "\f14e"; + content: "\f14e"; } + .fa-toggle-down:before, .fa-caret-square-o-down:before { - content: "\f150"; + content: "\f150"; } + .fa-toggle-up:before, .fa-caret-square-o-up:before { - content: "\f151"; + content: "\f151"; } + .fa-toggle-right:before, .fa-caret-square-o-right:before { - content: "\f152"; + content: "\f152"; } + .fa-euro:before, .fa-eur:before { - content: "\f153"; + content: "\f153"; } + .fa-gbp:before { - content: "\f154"; + content: "\f154"; } + .fa-dollar:before, .fa-usd:before { - content: "\f155"; + content: "\f155"; } + .fa-rupee:before, .fa-inr:before { - content: "\f156"; + content: "\f156"; } + .fa-cny:before, .fa-rmb:before, .fa-yen:before, .fa-jpy:before { - content: "\f157"; + content: "\f157"; } + .fa-ruble:before, .fa-rouble:before, .fa-rub:before { - content: "\f158"; + content: "\f158"; } + .fa-won:before, .fa-krw:before { - content: "\f159"; + content: "\f159"; } + .fa-bitcoin:before, .fa-btc:before { - content: "\f15a"; + content: "\f15a"; } + .fa-file:before { - content: "\f15b"; + content: "\f15b"; } + .fa-file-text:before { - content: "\f15c"; + content: "\f15c"; } + .fa-sort-alpha-asc:before { - content: "\f15d"; + content: "\f15d"; } + .fa-sort-alpha-desc:before { - content: "\f15e"; + content: "\f15e"; } + .fa-sort-amount-asc:before { - content: "\f160"; + content: "\f160"; } + .fa-sort-amount-desc:before { - content: "\f161"; + content: "\f161"; } + .fa-sort-numeric-asc:before { - content: "\f162"; + content: "\f162"; } + .fa-sort-numeric-desc:before { - content: "\f163"; + content: "\f163"; } + .fa-thumbs-up:before { - content: "\f164"; + content: "\f164"; } + .fa-thumbs-down:before { - content: "\f165"; + content: "\f165"; } + .fa-youtube-square:before { - content: "\f166"; + content: "\f166"; } + .fa-youtube:before { - content: "\f167"; + content: "\f167"; } + .fa-xing:before { - content: "\f168"; + content: "\f168"; } + .fa-xing-square:before { - content: "\f169"; + content: "\f169"; } + .fa-youtube-play:before { - content: "\f16a"; + content: "\f16a"; } + .fa-dropbox:before { - content: "\f16b"; + content: "\f16b"; } + .fa-stack-overflow:before { - content: "\f16c"; + content: "\f16c"; } + .fa-instagram:before { - content: "\f16d"; + content: "\f16d"; } + .fa-flickr:before { - content: "\f16e"; + content: "\f16e"; } + .fa-adn:before { - content: "\f170"; + content: "\f170"; } + .fa-bitbucket:before { - content: "\f171"; + content: "\f171"; } + .fa-bitbucket-square:before { - content: "\f172"; + content: "\f172"; } + .fa-tumblr:before { - content: "\f173"; + content: "\f173"; } + .fa-tumblr-square:before { - content: "\f174"; + content: "\f174"; } + .fa-long-arrow-down:before { - content: "\f175"; + content: "\f175"; } + .fa-long-arrow-up:before { - content: "\f176"; + content: "\f176"; } + .fa-long-arrow-left:before { - content: "\f177"; + content: "\f177"; } + .fa-long-arrow-right:before { - content: "\f178"; + content: "\f178"; } + .fa-apple:before { - content: "\f179"; + content: "\f179"; } + .fa-windows:before { - content: "\f17a"; + content: "\f17a"; } + .fa-android:before { - content: "\f17b"; + content: "\f17b"; } + .fa-linux:before { - content: "\f17c"; + content: "\f17c"; } + .fa-dribbble:before { - content: "\f17d"; + content: "\f17d"; } + .fa-skype:before { - content: "\f17e"; + content: "\f17e"; } + .fa-foursquare:before { - content: "\f180"; + content: "\f180"; } + .fa-trello:before { - content: "\f181"; + content: "\f181"; } + .fa-female:before { - content: "\f182"; + content: "\f182"; } + .fa-male:before { - content: "\f183"; + content: "\f183"; } + .fa-gittip:before, .fa-gratipay:before { - content: "\f184"; + content: "\f184"; } + .fa-sun-o:before { - content: "\f185"; + content: "\f185"; } + .fa-moon-o:before { - content: "\f186"; + content: "\f186"; } + .fa-archive:before { - content: "\f187"; + content: "\f187"; } + .fa-bug:before { - content: "\f188"; + content: "\f188"; } + .fa-vk:before { - content: "\f189"; + content: "\f189"; } + .fa-weibo:before { - content: "\f18a"; + content: "\f18a"; } + .fa-renren:before { - content: "\f18b"; + content: "\f18b"; } + .fa-pagelines:before { - content: "\f18c"; + content: "\f18c"; } + .fa-stack-exchange:before { - content: "\f18d"; + content: "\f18d"; } + .fa-arrow-circle-o-right:before { - content: "\f18e"; + content: "\f18e"; } + .fa-arrow-circle-o-left:before { - content: "\f190"; + content: "\f190"; } + .fa-toggle-left:before, .fa-caret-square-o-left:before { - content: "\f191"; + content: "\f191"; } + .fa-dot-circle-o:before { - content: "\f192"; + content: "\f192"; } + .fa-wheelchair:before { - content: "\f193"; + content: "\f193"; } + .fa-vimeo-square:before { - content: "\f194"; + content: "\f194"; } + .fa-turkish-lira:before, .fa-try:before { - content: "\f195"; + content: "\f195"; } + .fa-plus-square-o:before { - content: "\f196"; + content: "\f196"; } + .fa-space-shuttle:before { - content: "\f197"; + content: "\f197"; } + .fa-slack:before { - content: "\f198"; + content: "\f198"; } + .fa-envelope-square:before { - content: "\f199"; + content: "\f199"; } + .fa-wordpress:before { - content: "\f19a"; + content: "\f19a"; } + .fa-openid:before { - content: "\f19b"; + content: "\f19b"; } + .fa-institution:before, .fa-bank:before, .fa-university:before { - content: "\f19c"; + content: "\f19c"; } + .fa-mortar-board:before, .fa-graduation-cap:before { - content: "\f19d"; + content: "\f19d"; } + .fa-yahoo:before { - content: "\f19e"; + content: "\f19e"; } + .fa-google:before { - content: "\f1a0"; + content: "\f1a0"; } + .fa-reddit:before { - content: "\f1a1"; + content: "\f1a1"; } + .fa-reddit-square:before { - content: "\f1a2"; + content: "\f1a2"; } + .fa-stumbleupon-circle:before { - content: "\f1a3"; + content: "\f1a3"; } + .fa-stumbleupon:before { - content: "\f1a4"; + content: "\f1a4"; } + .fa-delicious:before { - content: "\f1a5"; + content: "\f1a5"; } + .fa-digg:before { - content: "\f1a6"; + content: "\f1a6"; } + .fa-pied-piper:before { - content: "\f1a7"; + content: "\f1a7"; } + .fa-pied-piper-alt:before { - content: "\f1a8"; + content: "\f1a8"; } + .fa-drupal:before { - content: "\f1a9"; + content: "\f1a9"; } + .fa-joomla:before { - content: "\f1aa"; + content: "\f1aa"; } + .fa-language:before { - content: "\f1ab"; + content: "\f1ab"; } + .fa-fax:before { - content: "\f1ac"; + content: "\f1ac"; } + .fa-building:before { - content: "\f1ad"; + content: "\f1ad"; } + .fa-child:before { - content: "\f1ae"; + content: "\f1ae"; } + .fa-paw:before { - content: "\f1b0"; + content: "\f1b0"; } + .fa-spoon:before { - content: "\f1b1"; + content: "\f1b1"; } + .fa-cube:before { - content: "\f1b2"; + content: "\f1b2"; } + .fa-cubes:before { - content: "\f1b3"; + content: "\f1b3"; } + .fa-behance:before { - content: "\f1b4"; + content: "\f1b4"; } + .fa-behance-square:before { - content: "\f1b5"; + content: "\f1b5"; } + .fa-steam:before { - content: "\f1b6"; + content: "\f1b6"; } + .fa-steam-square:before { - content: "\f1b7"; + content: "\f1b7"; } + .fa-recycle:before { - content: "\f1b8"; + content: "\f1b8"; } + .fa-automobile:before, .fa-car:before { - content: "\f1b9"; + content: "\f1b9"; } + .fa-cab:before, .fa-taxi:before { - content: "\f1ba"; + content: "\f1ba"; } + .fa-tree:before { - content: "\f1bb"; + content: "\f1bb"; } + .fa-spotify:before { - content: "\f1bc"; + content: "\f1bc"; } + .fa-deviantart:before { - content: "\f1bd"; + content: "\f1bd"; } + .fa-soundcloud:before { - content: "\f1be"; + content: "\f1be"; } + .fa-database:before { - content: "\f1c0"; + content: "\f1c0"; } + .fa-file-pdf-o:before { - content: "\f1c1"; + content: "\f1c1"; } + .fa-file-word-o:before { - content: "\f1c2"; + content: "\f1c2"; } + .fa-file-excel-o:before { - content: "\f1c3"; + content: "\f1c3"; } + .fa-file-powerpoint-o:before { - content: "\f1c4"; + content: "\f1c4"; } + .fa-file-photo-o:before, .fa-file-picture-o:before, .fa-file-image-o:before { - content: "\f1c5"; + content: "\f1c5"; } + .fa-file-zip-o:before, .fa-file-archive-o:before { - content: "\f1c6"; + content: "\f1c6"; } + .fa-file-sound-o:before, .fa-file-audio-o:before { - content: "\f1c7"; + content: "\f1c7"; } + .fa-file-movie-o:before, .fa-file-video-o:before { - content: "\f1c8"; + content: "\f1c8"; } + .fa-file-code-o:before { - content: "\f1c9"; + content: "\f1c9"; } + .fa-vine:before { - content: "\f1ca"; + content: "\f1ca"; } + .fa-codepen:before { - content: "\f1cb"; + content: "\f1cb"; } + .fa-jsfiddle:before { - content: "\f1cc"; + content: "\f1cc"; } + .fa-life-bouy:before, .fa-life-buoy:before, .fa-life-saver:before, .fa-support:before, .fa-life-ring:before { - content: "\f1cd"; + content: "\f1cd"; } + .fa-circle-o-notch:before { - content: "\f1ce"; + content: "\f1ce"; } + .fa-ra:before, .fa-rebel:before { - content: "\f1d0"; + content: "\f1d0"; } + .fa-ge:before, .fa-empire:before { - content: "\f1d1"; + content: "\f1d1"; } + .fa-git-square:before { - content: "\f1d2"; + content: "\f1d2"; } + .fa-git:before { - content: "\f1d3"; + content: "\f1d3"; } + .fa-hacker-news:before { - content: "\f1d4"; + content: "\f1d4"; } + .fa-tencent-weibo:before { - content: "\f1d5"; + content: "\f1d5"; } + .fa-qq:before { - content: "\f1d6"; + content: "\f1d6"; } + .fa-wechat:before, .fa-weixin:before { - content: "\f1d7"; + content: "\f1d7"; } + .fa-send:before, .fa-paper-plane:before { - content: "\f1d8"; + content: "\f1d8"; } + .fa-send-o:before, .fa-paper-plane-o:before { - content: "\f1d9"; + content: "\f1d9"; } + .fa-history:before { - content: "\f1da"; + content: "\f1da"; } + .fa-genderless:before, .fa-circle-thin:before { - content: "\f1db"; + content: "\f1db"; } + .fa-header:before { - content: "\f1dc"; + content: "\f1dc"; } + .fa-paragraph:before { - content: "\f1dd"; + content: "\f1dd"; } + .fa-sliders:before { - content: "\f1de"; + content: "\f1de"; } + .fa-share-alt:before { - content: "\f1e0"; + content: "\f1e0"; } + .fa-share-alt-square:before { - content: "\f1e1"; + content: "\f1e1"; } + .fa-bomb:before { - content: "\f1e2"; + content: "\f1e2"; } + .fa-soccer-ball-o:before, .fa-futbol-o:before { - content: "\f1e3"; + content: "\f1e3"; } + .fa-tty:before { - content: "\f1e4"; + content: "\f1e4"; } + .fa-binoculars:before { - content: "\f1e5"; + content: "\f1e5"; } + .fa-plug:before { - content: "\f1e6"; + content: "\f1e6"; } + .fa-slideshare:before { - content: "\f1e7"; + content: "\f1e7"; } + .fa-twitch:before { - content: "\f1e8"; + content: "\f1e8"; } + .fa-yelp:before { - content: "\f1e9"; + content: "\f1e9"; } + .fa-newspaper-o:before { - content: "\f1ea"; + content: "\f1ea"; } + .fa-wifi:before { - content: "\f1eb"; + content: "\f1eb"; } + .fa-calculator:before { - content: "\f1ec"; + content: "\f1ec"; } + .fa-paypal:before { - content: "\f1ed"; + content: "\f1ed"; } + .fa-google-wallet:before { - content: "\f1ee"; + content: "\f1ee"; } + .fa-cc-visa:before { - content: "\f1f0"; + content: "\f1f0"; } + .fa-cc-mastercard:before { - content: "\f1f1"; + content: "\f1f1"; } + .fa-cc-discover:before { - content: "\f1f2"; + content: "\f1f2"; } + .fa-cc-amex:before { - content: "\f1f3"; + content: "\f1f3"; } + .fa-cc-paypal:before { - content: "\f1f4"; + content: "\f1f4"; } + .fa-cc-stripe:before { - content: "\f1f5"; + content: "\f1f5"; } + .fa-bell-slash:before { - content: "\f1f6"; + content: "\f1f6"; } + .fa-bell-slash-o:before { - content: "\f1f7"; + content: "\f1f7"; } + .fa-trash:before { - content: "\f1f8"; + content: "\f1f8"; } + .fa-copyright:before { - content: "\f1f9"; + content: "\f1f9"; } + .fa-at:before { - content: "\f1fa"; + content: "\f1fa"; } + .fa-eyedropper:before { - content: "\f1fb"; + content: "\f1fb"; } + .fa-paint-brush:before { - content: "\f1fc"; + content: "\f1fc"; } + .fa-birthday-cake:before { - content: "\f1fd"; + content: "\f1fd"; } + .fa-area-chart:before { - content: "\f1fe"; + content: "\f1fe"; } + .fa-pie-chart:before { - content: "\f200"; + content: "\f200"; } + .fa-line-chart:before { - content: "\f201"; + content: "\f201"; } + .fa-lastfm:before { - content: "\f202"; + content: "\f202"; } + .fa-lastfm-square:before { - content: "\f203"; + content: "\f203"; } + .fa-toggle-off:before { - content: "\f204"; + content: "\f204"; } + .fa-toggle-on:before { - content: "\f205"; + content: "\f205"; } + .fa-bicycle:before { - content: "\f206"; + content: "\f206"; } + .fa-bus:before { - content: "\f207"; + content: "\f207"; } + .fa-ioxhost:before { - content: "\f208"; + content: "\f208"; } + .fa-angellist:before { - content: "\f209"; + content: "\f209"; } + .fa-cc:before { - content: "\f20a"; + content: "\f20a"; } + .fa-shekel:before, .fa-sheqel:before, .fa-ils:before { - content: "\f20b"; + content: "\f20b"; } + .fa-meanpath:before { - content: "\f20c"; + content: "\f20c"; } + .fa-buysellads:before { - content: "\f20d"; + content: "\f20d"; } + .fa-connectdevelop:before { - content: "\f20e"; + content: "\f20e"; } + .fa-dashcube:before { - content: "\f210"; + content: "\f210"; } + .fa-forumbee:before { - content: "\f211"; + content: "\f211"; } + .fa-leanpub:before { - content: "\f212"; + content: "\f212"; } + .fa-sellsy:before { - content: "\f213"; + content: "\f213"; } + .fa-shirtsinbulk:before { - content: "\f214"; + content: "\f214"; } + .fa-simplybuilt:before { - content: "\f215"; + content: "\f215"; } + .fa-skyatlas:before { - content: "\f216"; + content: "\f216"; } + .fa-cart-plus:before { - content: "\f217"; + content: "\f217"; } + .fa-cart-arrow-down:before { - content: "\f218"; + content: "\f218"; } + .fa-diamond:before { - content: "\f219"; + content: "\f219"; } + .fa-ship:before { - content: "\f21a"; + content: "\f21a"; } + .fa-user-secret:before { - content: "\f21b"; + content: "\f21b"; } + .fa-motorcycle:before { - content: "\f21c"; + content: "\f21c"; } + .fa-street-view:before { - content: "\f21d"; + content: "\f21d"; } + .fa-heartbeat:before { - content: "\f21e"; + content: "\f21e"; } + .fa-venus:before { - content: "\f221"; + content: "\f221"; } + .fa-mars:before { - content: "\f222"; + content: "\f222"; } + .fa-mercury:before { - content: "\f223"; + content: "\f223"; } + .fa-transgender:before { - content: "\f224"; + content: "\f224"; } + .fa-transgender-alt:before { - content: "\f225"; + content: "\f225"; } + .fa-venus-double:before { - content: "\f226"; + content: "\f226"; } + .fa-mars-double:before { - content: "\f227"; + content: "\f227"; } + .fa-venus-mars:before { - content: "\f228"; + content: "\f228"; } + .fa-mars-stroke:before { - content: "\f229"; + content: "\f229"; } + .fa-mars-stroke-v:before { - content: "\f22a"; + content: "\f22a"; } + .fa-mars-stroke-h:before { - content: "\f22b"; + content: "\f22b"; } + .fa-neuter:before { - content: "\f22c"; + content: "\f22c"; } + .fa-facebook-official:before { - content: "\f230"; + content: "\f230"; } + .fa-pinterest-p:before { - content: "\f231"; + content: "\f231"; } + .fa-whatsapp:before { - content: "\f232"; + content: "\f232"; } + .fa-server:before { - content: "\f233"; + content: "\f233"; } + .fa-user-plus:before { - content: "\f234"; + content: "\f234"; } + .fa-user-times:before { - content: "\f235"; + content: "\f235"; } + .fa-hotel:before, .fa-bed:before { - content: "\f236"; + content: "\f236"; } + .fa-viacoin:before { - content: "\f237"; + content: "\f237"; } + .fa-train:before { - content: "\f238"; + content: "\f238"; } + .fa-subway:before { - content: "\f239"; + content: "\f239"; } + .fa-medium:before { - content: "\f23a"; + content: "\f23a"; } diff --git a/projects/webui/base/src/main/resources/css/main.css b/projects/webui/base/src/main/resources/css/main.css index faa4131e..1d303075 100644 --- a/projects/webui/base/src/main/resources/css/main.css +++ b/projects/webui/base/src/main/resources/css/main.css @@ -1,147 +1,147 @@ html, body { - height: 100%; + height: 100%; } #wrap { - min-height: 100%; - height: auto; - margin: 0 auto -130px; - padding: 0 0 130px; + min-height: 100%; + height: auto; + margin: 0 auto -130px; + padding: 0 0 130px; } #header { - border: 0px; - background: url('/openmuc/images/header-bg.jpg') repeat-x; + border: 0px; + background: url('/openmuc/images/header-bg.jpg') repeat-x; } @media (min-width: 768px) { - #openmuc-navbar .navbar-nav>li>a { - padding-top: 25px; - padding-bottom: 25px; - margin: 0px 2px; - } - - #openmuc-navbar .navbar-text { - margin-top: 20px; - margin-bottom: 20px; - } + #openmuc-navbar .navbar-nav > li > a { + padding-top: 25px; + padding-bottom: 25px; + margin: 0px 2px; + } + + #openmuc-navbar .navbar-text { + margin-top: 20px; + margin-bottom: 20px; + } } #openmuc-navbar .navbar-text .btn-sm { - margin-left: 15px; + margin-left: 15px; } -#openmuc-navbar a{ - cursor: pointer; +#openmuc-navbar a { + cursor: pointer; } #openmuc-navbar .dropdown li a { - padding-top: 8px; - padding-bottom: 8px; + padding-top: 8px; + padding-bottom: 8px; } #footer { - text-align: center; - height: 70px; - padding: 15px 20px; + text-align: center; + height: 70px; + padding: 15px 20px; - background: #E9EDEB; - margin-top: 60px; + background: #E9EDEB; + margin-top: 60px; } .alert.top-right { - position: absolute; - top: 40px; - right: 10px; - z-index: 1000; + position: absolute; + top: 40px; + right: 10px; + z-index: 1000; } .navbar-brand { - height: auto; - margin-right: 30px; + height: auto; + margin-right: 30px; } .ng-invalid.ng-dirty { - border-color: #b94a48; + border-color: #b94a48; } .ng-invalid.form-submitted { - border-color: #b94a48; + border-color: #b94a48; } .form-error-message { - color: #b94a48; + color: #b94a48; } @media (min-width: 768px) { - .lang-menu.navbar-btn { - margin-top: 17px; - margin-right: 20px; - } + .lang-menu.navbar-btn { + margin-top: 17px; + margin-right: 20px; + } } @media (max-width: 768px) { - .lang-menu.navbar-btn { - margin-left: 15px; - } + .lang-menu.navbar-btn { + margin-left: 15px; + } } .flag { - display: inline-block; - width: 24px; - height: 16px; - position: relative; - top: 3px; + display: inline-block; + width: 24px; + height: 16px; + position: relative; + top: 3px; } .flag-de { - background: url('/openmuc/images/flag-de.gif'); + background: url('/openmuc/images/flag-de.gif'); } .flag-en { - background: url('/openmuc/images/flag-en.gif'); + background: url('/openmuc/images/flag-en.gif'); } .dropdown-label { - padding: 0 3px; + padding: 0 3px; } .dropdown .icon { - color: #79B0A6; - margin-right: 10px; - font-size: 20px; - width: 28px; - text-align: center; + color: #79B0A6; + margin-right: 10px; + font-size: 20px; + width: 28px; + text-align: center; } .dropdown .icon img { - width: 20px; + width: 20px; } /* FORMS */ .form-horizontal .fa-info-circle { - color: #009474; + color: #009474; } .help-label { - position: relative; - top: 5px; + position: relative; + top: 5px; } /* TABLES */ table.table-fixed { - table-layout: fixed; + table-layout: fixed; } /* HEADER */ .sub-category-heading { - margin-top: 0px; - top: -20px; - position: relative; - color: #008669; - margin-bottom: 20px; + margin-top: 0px; + top: -20px; + position: relative; + color: #008669; + margin-bottom: 20px; } \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/html/dashboard/index.html b/projects/webui/base/src/main/resources/html/dashboard/index.html index 9b47d7ae..afea16f5 100644 --- a/projects/webui/base/src/main/resources/html/dashboard/index.html +++ b/projects/webui/base/src/main/resources/html/dashboard/index.html @@ -1,20 +1,20 @@ -
              +
              -
              -
              \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/html/sessions/new.html b/projects/webui/base/src/main/resources/html/sessions/new.html index c0b9e889..38b0c2a0 100644 --- a/projects/webui/base/src/main/resources/html/sessions/new.html +++ b/projects/webui/base/src/main/resources/html/sessions/new.html @@ -1,22 +1,22 @@ -
              -
              +
              +
              -
              -
              -
              -
              - -
              -
              - -
              - - -
              -
              +
              +
              +
              +
              + +
              +
              + +
              + + +
              +
              \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/app.i18n.js b/projects/webui/base/src/main/resources/js/app.i18n.js index 9d39de5c..77386954 100644 --- a/projects/webui/base/src/main/resources/js/app.i18n.js +++ b/projects/webui/base/src/main/resources/js/app.i18n.js @@ -1,255 +1,255 @@ -(function(){ - - var app = angular.module('openmuc.i18n', ['pascalprecht.translate']); +(function () { + + var app = angular.module('openmuc.i18n', ['pascalprecht.translate']); + + app.config(function ($translateProvider) { - app.config(function ($translateProvider) { - $translateProvider.translations('en', { - WELCOME_TO_OPEN_MUC: 'Welcome to the OpenMUC Framework Administration Utility', - APPLICATIONS: 'Applications', - DRIVERS: 'Drivers', - DASHBOARD: 'Dashboard', - DEVICES: 'Devices', - CHANNELS: 'Channels', - PLOTTER: 'Plotter', - DATA_PLOTTER: 'Data Plotter', - BAR_PLOTTER: 'Bar Plotter', - LIVE_PLOTTER: 'Live Plotter', - DATA_LISTER: 'Data Lister', - LIVE_PLOTTER_FLOT: 'Live Plotter (Flot)', - USERS: 'Users', - BUTTON_LANG_EN: 'English', - BUTTON_LANG_DE: 'German', - LANGUAGE: 'Language', - CHANNEL_CONFIGURATOR: 'Channel Configurator', - USER_CONFIGURATOR: 'User Configurator', - DATA_EXPORTER: 'Data Exporter', - HOME: 'Home', - CONFIGURATION: 'Configuration', - NEW: 'New', - EDIT: 'Edit', - DELETE: 'Delete', - SEARCH: 'Search', - OPEN: 'Open', - CHANNEL_ACCESS_TOOL: 'Channel Access Tool', - CHANNELS_ACCESS_TOOL: 'Channels Access Tool', - LOGOUT: 'Logout', - EDIT_PROFILE: 'Edit profile', - EDIT_DRIVER: 'Edit driver', - NEW_DRIVER: 'New driver', - SCAN_DRIVER: 'Scan driver', - NEW_DEVICE: 'New device', - EDIT_DEVICE: 'Edit device', - NEW_CHANNEL: 'New channel', - EDIT_CHANNEL: 'Edit channel', - ADD_DRIVER: 'Add new driver', - NO_DRIVERS: 'No drivers', - DRIVER_ID: 'Driver ID', - ACTION: 'Action', - RUNNING: 'Running', - ADD_NEW_DRIVER_CONFIGURATION: 'Add new driver configuration', - DRIVER_CONFIGURATIONS: 'Driver configurations', - DRIVER_ID_HINT: 'The ID that uniquely identifies the driver you want to configure. The driver ID must contain only lower case ASCII letters and digits. Check the driver section in the OpenMUC user guide if you do not know the ID of your driver.', - DRIVER_SAMPLING_TIMEOUT_HINT: 'Maximum time that a sampling task may take. The latest record is marked with a timeout flag if the sampling task takes longer.', - DRIVER_CONNECT_RETRY_INTERVAL_HINT: 'The amount of time to wait after an unsuccessful connection attempt before retrying to connect.', - DRIVER_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this driver. If a driver is disabled this will implicitly override the disabled setting of all devices and channels of this driver. Therefor even if you explicitly enable a device by setting its disabled setting to false it will still be disabled if its driver was disabled. Note that this setting does not stop or otherwise change the state of the driver bundle.', - DRIVER_DISABLED: 'Disabled', - DRIVER_CONNECT_RETRY_INTERVAL: 'Connect Retry Interval', - DRIVER_SAMPLING_TIMEOUT: 'Sampling Timeout', - DRIVER_ID: 'ID', - REQUIRED_FIELDS: 'Required fields', - DEFAULT_LEFT_BLANK: 'Default (if left blank)', - FALSE: 'False', - TRUE: 'True', - UNLIMITED: 'unlimited', - DRIVER_ID_REQUIRED: 'The driver ID is required.', - SUBMIT: 'Submit', - DRIVER_UPDATED_SUCCESSFULLY: 'The driver was successfully updated.', - DRIVER_UPDATED_ERROR: 'The driver was not successfully updated.', - NO_DEVICES: 'No devices', - OPTIONS: 'Options', - STATE: 'State', - ADD_DEVICE: 'Add new device', - ADD_DEVICE_TO: 'Add new device to', - DEVICE_CONFIGURATION: 'Device configuration', - DEVICE_ID: 'ID', - DEVICE_DESCRIPTION: 'Description', - DEVICE_ADDRESS: 'Device Address', - DEVICE_SETTINGS: 'Settings', - DEVICE_SAMPLING_TIMEOUT: 'Sampling Timeout', - DEVICE_CONNECT_RETRY_INTERVAL: 'Connect Retry Interval', - DEVICE_DISABLED: 'Disabled', - DEVICE_VALUE_SET_DRIVER_CONFIGURATION: 'Value set in driver configuration', - DEVICE_NAME_REQUIRED: 'The device name is required', - DEVICE_ID_HINT: 'The ID of the device.', - DEVICE_DESCRIPTION_HINT: 'The description of the device. Exists for informational purposes only.', - DEVICE_SAMPLING_TIMEOUT_HINT: 'Maximum time that a sampling task may take. The latest record is marked with a timeout flag if the sampling task takes longer.', - DEVICE_CONNECT_RETRY_INTERVAL_HINT: 'The amount of time to wait after an unsuccessful connection attempt before retrying to connect.', - DEVICE_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this device. If a device is disabled this will implicitly override the disabled setting of all channels of this device. Therefor even if you explicitly enable a channel by setting its disabled setting to false it will still be disabled if its device (or driver) was disabled.', - DRIVER: 'Driver', - ADD_CHANNEL: 'Add new channel', - CHANNEL_ID: 'ID', - DESCRIPTION: 'Description', - DEVICE: 'Device', - ADD_CHANNEL_TO: 'Add new channel to device', - EDIT_CHANNEL: 'Edit channel', - CHANNEL_CONFIGURATION: 'Channel configuration', - CHANNEL_DESCRIPTION: 'Description', - CHANNEL_ADDRESS: 'Channel Address', - CHANNEL_VALUE_TYPE: 'Channel Type', - CHANNEL_VALUE_LENGTH: 'Value Length', - CHANNEL_SCALING_FACTOR: 'Scaling Factor', - CHANNEL_VALUE_OFFSET: 'Value Offset', - CHANNEL_UNIT: 'Unit', - CHANNEL_LOGGING_INTERVAL: 'Logging Interval', - CHANNEL_LOGGING_TIME_OFFSET: 'Logging Time Offset', - CHANNEL_LISTENING_FOR_DATA: 'Listening for Data', - CHANNEL_SAMPLING_INTERVAL: 'Sampling Inverval', - CHANNEL_SAMPLING_TIME_OFFSET: 'Sampling Time Offset', - CHANNEL_SAMPLING_GROUP: 'Sampling Group', - CHANNEL_DISABLED: 'Disabled', - CHANNEL_ID_HINT: 'The ID of the channel.', - CHANNEL_DESCRIPTION_HINT: 'The description of the channel. Exists for informational purposes only.', - CHANNEL_VALUE_TYPE_HINT: 'Data type of the channel. Used on data logger. Driver implementation do NOT receive this settings.', - CHANNEL_VALUE_LENGTH_HINT: 'Only used if valueType == BYTE_ARRAY. Determines the maximum length of the byte array.', - CHANNEL_SCALING_FACTOR_HINT: 'Is used to scale a value read by a driver or set by an application. The value read by an driver is multiplied with the scalingFactor and a value set by an application is divided by the scalingFactor.', - CHANNEL_VALUE_OFFSET_HINT: 'Is used to offset a value read by a driver or set by an application. The offset is added to a value read by a driver and subtracted from a value set by an application.', - CHANNEL_UNIT_HINT: 'Physical unit of this channel. For information only (info can be accessed by an app or driver)', - CHANNEL_LOGGING_INTERVAL_HINT: 'Time difference until this channel is logged again. -1 or omitting loggingInterval disables logging.', - CHANNEL_LOGGING_TIME_OFFSET_HINT: 'Offset of the logging time.', - CHANNEL_LISTENING_FOR_DATA_HINT: 'Determines if this channel shall passively listen for incoming value changes from the driver.', - CHANNEL_SAMPLING_INTERVAL_HINT: 'Time interval between two attempts to read this channel. -1 or omitting samlingOffset disables sampling on this channel.', - CHANNEL_SAMPLING_TIME_OFFSET_HINT: 'Offset of the sampling time.', - CHANNEL_SAMPLING_GROUP_HINT: 'For grouping channels. All channels with the same samplingGroup and same samplingInterval are in one group. The purpous of samplingGroups is to improve the drivers performance - if possible.', - CHANNEL_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this channel.', - DISABLED: 'Disabled', - CHANNEL_ID_REQUIRED: 'The channel id is required.', - NO_OPTIONS_FILES: 'No Options files found', - NO_USERS: 'No users found', - ADD_USER: 'Add new user', - USERNAME: 'Username', - PASSWORD: 'Password', - CONFIRM_PASSWORD: 'Confirm Password', - NO_CHANNELS: 'No channels', - PLOT_OPTIONS: 'Plot options', - START_DATE: 'Start date', - END_DATE: 'End date', - CHANNEL: 'Channel', - PLOT_DATA: 'Plot Data', - NO_DATA_TO_DISPLAY: 'No Data', - SELECT_CHANNELS_TO_EXPORT: 'Select channels to export', - PLOT_TIME_PERIOD: 'Time period', - REFRESH: 'Refresh', - ADD_DEVICES: 'Add devices', - SCAN_DRIVER_SETTINGS_HINT: 'Communication parameters that may be needed by the driver in order to scan for new devices. Typical settings are baudrate, username/password, and other protocol options. Syntax for the dummy driver: N.A.', - SCANNING: 'Scanning', - SCAN_FOR_DEVICES: 'Scan for devices', - SCAN_DEVICE: 'Scanned channels of device', - SCAN_DEVICE_TAB: 'Scan device', - SELECT_CHANNEL: 'Select channels',// (Max 3)', - SECONDS: 'Seconds', - MINUTES: 'Minutes', - HOURS: 'Hours', - SHOULD_BE_INTEGER: 'Should be a number', - DRIVER_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', - DEVICE_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', - CHANNEL_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', - ADD_CHANNELS: 'Add channels', - NOW: 'Now', - DRIVER_CREATED_SUCCESSFULLY: 'The driver was successfully created.', - DRIVER_CREATED_ERROR: 'The driver was not created. Something went wrong.', - DRIVER_UPDATED_SUCCESSFULLY: 'The driver was successfully updated.', - DRIVER_UPDATED_ERROR: 'The driver was not successfully updated. Something went wrong.', - DRIVER_SCAN_DEVICE_CREATED_SUCCESSFULLY: 'The device was successfully created.', - DRIVER_SCAN_DEVICE_CREATED_ERROR: 'The device was not created. Something went wrong.', - DRIVER_DELETED_SUCCESSFULLY: 'The driver was successfully deleted.', - DEVICE_CREATED_SUCCESSFULLY: 'The device was successfully created.', - DEVICE_CREATED_ERROR: 'The device was not created. Something went wrong.', - DEVICE_UPDATED_SUCCESSFULLY: 'The device was successfully updated.', - DEVICE_UPDATED_ERROR: 'The device was not updated. Something went wrong.', - DEVICE_DELETED_SUCCESSFULLY: 'The device was successfully deleted.', - CHANNEL_CREATED_SUCCESSFULLY: 'The channel was successfully created.', - CHANNEL_CREATED_ERROR: 'The channel was not created. Something went wrong.', - CHANNEL_UPDATED_SUCCESSFULLY: 'The channel was successfully updated.', - CHANNEL_UPDATED_ERROR: 'The channel was not successfully updated. Something went wrong.', - CHANNEL_DELETED_SUCCESSFULLY: 'The channel was successfully deleted.', - SELECT_AT_LEAST_ONE_DEVICE: 'Please select at least one device.', - USER_UPDATED_SUCCESSFULLY: 'The username was successfully updated.', - USER_UPDATED_ERROR: 'The username was not updated. Something went wrong.', - USER_PASSWORD_UPDATED_SUCCESSFULLY: 'The password was successfully updated.', - USER_PASSWORD_UPDATED_ERROR: 'The password was not updated. Something went wrong.', - USER_CREATED_SUCCESSFULLY: 'The user was successfully saved.', - USER_CREATED_ERROR: 'The user was not successfully saved. Something went wrong.', - SUCCESSFULLY_LOGGED_OUT: 'You have successfully logged out', - SESSION_EXPIRED: 'Your session has expired. Please login again', - LOADING_APP_DEPENDENCES_ERROR: 'There was an error loading the app dependences', - LOGIN_CREDENTIALS_INCORRECT: 'Username or password is incorrect', - LATEST_RECORD_UPDATED_EVERY_SECOND: 'The latest record is updated roughly every second.', - LATEST_RECORD: 'Latest record', - WRITE: 'Write', - VALUE: 'Value', - VALUES: 'Values', - DATE: 'Date', - TIME: 'Time', - FLAG: 'Flag', - BACK_TO_SELECTION: 'Back to selection', - CHANNEL_ACCESS_TOOL_CHANNEL_ID: 'Channel ID', - ACCESS_SELECTED: 'Access selected', - CHANNEL_ACCESS_TOOL_DEVICE_ID: 'Device ID', - WRITE_VALUE: 'Write value', - OPENMUC_CONFIG_FILES: 'OpenMUC config files', - FILE: 'File', - EXPORT_DATA_AS_CSV: 'Export data as CSV', - EXPORT_OPTIONS: 'Export options', - EXPORT_DATA_SINCE: 'Export data since', - EXPORT_DATA_UNTIL: 'Export data until', - TIME_FORMAT: 'Time format', - GENERATE_DATA: 'Generate data', - EXPORT: 'Export', - LOGIN: 'Login', - USERS_CONFIGURATION: 'Users Configuration', - USERNAME_REQUIRED: 'The username is required.', - PASSWORD_REQUIRED: 'The password is required.', - PASSWORD_CONFIRMATION_REQUIRED: 'The password confirmation is required', - PASSWORD_DO_NOT_MATCH: 'Passwords do not match.', - SAVE: 'Save', - EDIT_USER: 'Edit user', - CHANGE_USERNAME: 'Change Username', - CHANGE_PASSWORD: 'Change Password', - NEW_USERNAME: 'New Username', - NEW_PASSWORD: 'New Password', - CHANGE: 'Change', - OLD_PASSWORD: 'Old Password', - RETYPE_PASSWORD: 'Retype Password', - NEW_PASSWORD_CONFIRMATION_REQUIRED: 'The new password confirmation is required.', - NEW_PASSWORD_REQUIRED: 'The new password is required.', - OLD_PASSWORD_REQUIRED: 'The old password is required.', - USER_DELETED_SUCCESSFULLY: 'The user was successfully deleted.', - PV_BATTERY_VISUALIZATION: 'PV Battery Visualization', - MEDIA_VIEWER: 'Media Viewer', - NO_MEDIA: 'No media files found', - CHANNEL_VALUE_UPDATED_SUCCESSFULLY: 'The new value was written to the channel', - CHANNEL_VALUE_UPDATED_ERROR: 'The new value was not written to the channel. Something went wrong.', - }); - - $translateProvider.translations('de', { - DRIVERS: 'Treiber', - DASHBOARD: 'Dashboard', - DEVICES: 'Geräte', - CHANNELS: 'Kanäle', - PLOTTER: 'Plotter', - USERS: 'Users', - BUTTON_LANG_EN: 'Englisch', - BUTTON_LANG_DE: 'Deutsch', - LANGUAGE: 'Sprache', - NOW: 'Jetzt', - SECONDS: 'Sekunden', - MINUTES: 'Minuten', - HOURS: 'Stunden', - }); - + WELCOME_TO_OPEN_MUC: 'Welcome to the OpenMUC Framework Administration Utility', + APPLICATIONS: 'Applications', + DRIVERS: 'Drivers', + DASHBOARD: 'Dashboard', + DEVICES: 'Devices', + CHANNELS: 'Channels', + PLOTTER: 'Plotter', + DATA_PLOTTER: 'Data Plotter', + BAR_PLOTTER: 'Bar Plotter', + LIVE_PLOTTER: 'Live Plotter', + DATA_LISTER: 'Data Lister', + LIVE_PLOTTER_FLOT: 'Live Plotter (Flot)', + USERS: 'Users', + BUTTON_LANG_EN: 'English', + BUTTON_LANG_DE: 'German', + LANGUAGE: 'Language', + CHANNEL_CONFIGURATOR: 'Channel Configurator', + USER_CONFIGURATOR: 'User Configurator', + DATA_EXPORTER: 'Data Exporter', + HOME: 'Home', + CONFIGURATION: 'Configuration', + NEW: 'New', + EDIT: 'Edit', + DELETE: 'Delete', + SEARCH: 'Search', + OPEN: 'Open', + CHANNEL_ACCESS_TOOL: 'Channel Access Tool', + CHANNELS_ACCESS_TOOL: 'Channels Access Tool', + LOGOUT: 'Logout', + EDIT_PROFILE: 'Edit profile', + EDIT_DRIVER: 'Edit driver', + NEW_DRIVER: 'New driver', + SCAN_DRIVER: 'Scan driver', + NEW_DEVICE: 'New device', + EDIT_DEVICE: 'Edit device', + NEW_CHANNEL: 'New channel', + EDIT_CHANNEL: 'Edit channel', + ADD_DRIVER: 'Add new driver', + NO_DRIVERS: 'No drivers', + DRIVER_ID: 'Driver ID', + ACTION: 'Action', + RUNNING: 'Running', + ADD_NEW_DRIVER_CONFIGURATION: 'Add new driver configuration', + DRIVER_CONFIGURATIONS: 'Driver configurations', + DRIVER_ID_HINT: 'The ID that uniquely identifies the driver you want to configure. The driver ID must contain only lower case ASCII letters and digits. Check the driver section in the OpenMUC user guide if you do not know the ID of your driver.', + DRIVER_SAMPLING_TIMEOUT_HINT: 'Maximum time that a sampling task may take. The latest record is marked with a timeout flag if the sampling task takes longer.', + DRIVER_CONNECT_RETRY_INTERVAL_HINT: 'The amount of time to wait after an unsuccessful connection attempt before retrying to connect.', + DRIVER_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this driver. If a driver is disabled this will implicitly override the disabled setting of all devices and channels of this driver. Therefor even if you explicitly enable a device by setting its disabled setting to false it will still be disabled if its driver was disabled. Note that this setting does not stop or otherwise change the state of the driver bundle.', + DRIVER_DISABLED: 'Disabled', + DRIVER_CONNECT_RETRY_INTERVAL: 'Connect Retry Interval', + DRIVER_SAMPLING_TIMEOUT: 'Sampling Timeout', + DRIVER_ID: 'ID', + REQUIRED_FIELDS: 'Required fields', + DEFAULT_LEFT_BLANK: 'Default (if left blank)', + FALSE: 'False', + TRUE: 'True', + UNLIMITED: 'unlimited', + DRIVER_ID_REQUIRED: 'The driver ID is required.', + SUBMIT: 'Submit', + DRIVER_UPDATED_SUCCESSFULLY: 'The driver was successfully updated.', + DRIVER_UPDATED_ERROR: 'The driver was not successfully updated.', + NO_DEVICES: 'No devices', + OPTIONS: 'Options', + STATE: 'State', + ADD_DEVICE: 'Add new device', + ADD_DEVICE_TO: 'Add new device to', + DEVICE_CONFIGURATION: 'Device configuration', + DEVICE_ID: 'ID', + DEVICE_DESCRIPTION: 'Description', + DEVICE_ADDRESS: 'Device Address', + DEVICE_SETTINGS: 'Settings', + DEVICE_SAMPLING_TIMEOUT: 'Sampling Timeout', + DEVICE_CONNECT_RETRY_INTERVAL: 'Connect Retry Interval', + DEVICE_DISABLED: 'Disabled', + DEVICE_VALUE_SET_DRIVER_CONFIGURATION: 'Value set in driver configuration', + DEVICE_NAME_REQUIRED: 'The device name is required', + DEVICE_ID_HINT: 'The ID of the device.', + DEVICE_DESCRIPTION_HINT: 'The description of the device. Exists for informational purposes only.', + DEVICE_SAMPLING_TIMEOUT_HINT: 'Maximum time that a sampling task may take. The latest record is marked with a timeout flag if the sampling task takes longer.', + DEVICE_CONNECT_RETRY_INTERVAL_HINT: 'The amount of time to wait after an unsuccessful connection attempt before retrying to connect.', + DEVICE_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this device. If a device is disabled this will implicitly override the disabled setting of all channels of this device. Therefor even if you explicitly enable a channel by setting its disabled setting to false it will still be disabled if its device (or driver) was disabled.', + DRIVER: 'Driver', + ADD_CHANNEL: 'Add new channel', + CHANNEL_ID: 'ID', + DESCRIPTION: 'Description', + DEVICE: 'Device', + ADD_CHANNEL_TO: 'Add new channel to device', + EDIT_CHANNEL: 'Edit channel', + CHANNEL_CONFIGURATION: 'Channel configuration', + CHANNEL_DESCRIPTION: 'Description', + CHANNEL_ADDRESS: 'Channel Address', + CHANNEL_VALUE_TYPE: 'Channel Type', + CHANNEL_VALUE_LENGTH: 'Value Length', + CHANNEL_SCALING_FACTOR: 'Scaling Factor', + CHANNEL_VALUE_OFFSET: 'Value Offset', + CHANNEL_UNIT: 'Unit', + CHANNEL_LOGGING_INTERVAL: 'Logging Interval', + CHANNEL_LOGGING_TIME_OFFSET: 'Logging Time Offset', + CHANNEL_LISTENING_FOR_DATA: 'Listening for Data', + CHANNEL_SAMPLING_INTERVAL: 'Sampling Inverval', + CHANNEL_SAMPLING_TIME_OFFSET: 'Sampling Time Offset', + CHANNEL_SAMPLING_GROUP: 'Sampling Group', + CHANNEL_DISABLED: 'Disabled', + CHANNEL_ID_HINT: 'The ID of the channel.', + CHANNEL_DESCRIPTION_HINT: 'The description of the channel. Exists for informational purposes only.', + CHANNEL_VALUE_TYPE_HINT: 'Data type of the channel. Used on data logger. Driver implementation do NOT receive this settings.', + CHANNEL_VALUE_LENGTH_HINT: 'Only used if valueType == BYTE_ARRAY. Determines the maximum length of the byte array.', + CHANNEL_SCALING_FACTOR_HINT: 'Is used to scale a value read by a driver or set by an application. The value read by an driver is multiplied with the scalingFactor and a value set by an application is divided by the scalingFactor.', + CHANNEL_VALUE_OFFSET_HINT: 'Is used to offset a value read by a driver or set by an application. The offset is added to a value read by a driver and subtracted from a value set by an application.', + CHANNEL_UNIT_HINT: 'Physical unit of this channel. For information only (info can be accessed by an app or driver)', + CHANNEL_LOGGING_INTERVAL_HINT: 'Time difference until this channel is logged again. -1 or omitting loggingInterval disables logging.', + CHANNEL_LOGGING_TIME_OFFSET_HINT: 'Offset of the logging time.', + CHANNEL_LISTENING_FOR_DATA_HINT: 'Determines if this channel shall passively listen for incoming value changes from the driver.', + CHANNEL_SAMPLING_INTERVAL_HINT: 'Time interval between two attempts to read this channel. -1 or omitting samlingOffset disables sampling on this channel.', + CHANNEL_SAMPLING_TIME_OFFSET_HINT: 'Offset of the sampling time.', + CHANNEL_SAMPLING_GROUP_HINT: 'For grouping channels. All channels with the same samplingGroup and same samplingInterval are in one group. The purpous of samplingGroups is to improve the drivers performance - if possible.', + CHANNEL_DISABLED_HINT: 'Disables all communication activity (e.g. sampling, writing, connecting) for this channel.', + DISABLED: 'Disabled', + CHANNEL_ID_REQUIRED: 'The channel id is required.', + NO_OPTIONS_FILES: 'No Options files found', + NO_USERS: 'No users found', + ADD_USER: 'Add new user', + USERNAME: 'Username', + PASSWORD: 'Password', + CONFIRM_PASSWORD: 'Confirm Password', + NO_CHANNELS: 'No channels', + PLOT_OPTIONS: 'Plot options', + START_DATE: 'Start date', + END_DATE: 'End date', + CHANNEL: 'Channel', + PLOT_DATA: 'Plot Data', + NO_DATA_TO_DISPLAY: 'No Data', + SELECT_CHANNELS_TO_EXPORT: 'Select channels to export', + PLOT_TIME_PERIOD: 'Time period', + REFRESH: 'Refresh', + ADD_DEVICES: 'Add devices', + SCAN_DRIVER_SETTINGS_HINT: 'Communication parameters that may be needed by the driver in order to scan for new devices. Typical settings are baudrate, username/password, and other protocol options. Syntax for the dummy driver: N.A.', + SCANNING: 'Scanning', + SCAN_FOR_DEVICES: 'Scan for devices', + SCAN_DEVICE: 'Scanned channels of device', + SCAN_DEVICE_TAB: 'Scan device', + SELECT_CHANNEL: 'Select channels',// (Max 3)', + SECONDS: 'Seconds', + MINUTES: 'Minutes', + HOURS: 'Hours', + SHOULD_BE_INTEGER: 'Should be a number', + DRIVER_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', + DEVICE_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', + CHANNEL_ID_PATTERN_INCORRECT: 'Should contain only letters, numbers, underscores and dashes.', + ADD_CHANNELS: 'Add channels', + NOW: 'Now', + DRIVER_CREATED_SUCCESSFULLY: 'The driver was successfully created.', + DRIVER_CREATED_ERROR: 'The driver was not created. Something went wrong.', + DRIVER_UPDATED_SUCCESSFULLY: 'The driver was successfully updated.', + DRIVER_UPDATED_ERROR: 'The driver was not successfully updated. Something went wrong.', + DRIVER_SCAN_DEVICE_CREATED_SUCCESSFULLY: 'The device was successfully created.', + DRIVER_SCAN_DEVICE_CREATED_ERROR: 'The device was not created. Something went wrong.', + DRIVER_DELETED_SUCCESSFULLY: 'The driver was successfully deleted.', + DEVICE_CREATED_SUCCESSFULLY: 'The device was successfully created.', + DEVICE_CREATED_ERROR: 'The device was not created. Something went wrong.', + DEVICE_UPDATED_SUCCESSFULLY: 'The device was successfully updated.', + DEVICE_UPDATED_ERROR: 'The device was not updated. Something went wrong.', + DEVICE_DELETED_SUCCESSFULLY: 'The device was successfully deleted.', + CHANNEL_CREATED_SUCCESSFULLY: 'The channel was successfully created.', + CHANNEL_CREATED_ERROR: 'The channel was not created. Something went wrong.', + CHANNEL_UPDATED_SUCCESSFULLY: 'The channel was successfully updated.', + CHANNEL_UPDATED_ERROR: 'The channel was not successfully updated. Something went wrong.', + CHANNEL_DELETED_SUCCESSFULLY: 'The channel was successfully deleted.', + SELECT_AT_LEAST_ONE_DEVICE: 'Please select at least one device.', + USER_UPDATED_SUCCESSFULLY: 'The username was successfully updated.', + USER_UPDATED_ERROR: 'The username was not updated. Something went wrong.', + USER_PASSWORD_UPDATED_SUCCESSFULLY: 'The password was successfully updated.', + USER_PASSWORD_UPDATED_ERROR: 'The password was not updated. Something went wrong.', + USER_CREATED_SUCCESSFULLY: 'The user was successfully saved.', + USER_CREATED_ERROR: 'The user was not successfully saved. Something went wrong.', + SUCCESSFULLY_LOGGED_OUT: 'You have successfully logged out', + SESSION_EXPIRED: 'Your session has expired. Please login again', + LOADING_APP_DEPENDENCES_ERROR: 'There was an error loading the app dependences', + LOGIN_CREDENTIALS_INCORRECT: 'Username or password is incorrect', + LATEST_RECORD_UPDATED_EVERY_SECOND: 'The latest record is updated roughly every second.', + LATEST_RECORD: 'Latest record', + WRITE: 'Write', + VALUE: 'Value', + VALUES: 'Values', + DATE: 'Date', + TIME: 'Time', + FLAG: 'Flag', + BACK_TO_SELECTION: 'Back to selection', + CHANNEL_ACCESS_TOOL_CHANNEL_ID: 'Channel ID', + ACCESS_SELECTED: 'Access selected', + CHANNEL_ACCESS_TOOL_DEVICE_ID: 'Device ID', + WRITE_VALUE: 'Write value', + OPENMUC_CONFIG_FILES: 'OpenMUC config files', + FILE: 'File', + EXPORT_DATA_AS_CSV: 'Export data as CSV', + EXPORT_OPTIONS: 'Export options', + EXPORT_DATA_SINCE: 'Export data since', + EXPORT_DATA_UNTIL: 'Export data until', + TIME_FORMAT: 'Time format', + GENERATE_DATA: 'Generate data', + EXPORT: 'Export', + LOGIN: 'Login', + USERS_CONFIGURATION: 'Users Configuration', + USERNAME_REQUIRED: 'The username is required.', + PASSWORD_REQUIRED: 'The password is required.', + PASSWORD_CONFIRMATION_REQUIRED: 'The password confirmation is required', + PASSWORD_DO_NOT_MATCH: 'Passwords do not match.', + SAVE: 'Save', + EDIT_USER: 'Edit user', + CHANGE_USERNAME: 'Change Username', + CHANGE_PASSWORD: 'Change Password', + NEW_USERNAME: 'New Username', + NEW_PASSWORD: 'New Password', + CHANGE: 'Change', + OLD_PASSWORD: 'Old Password', + RETYPE_PASSWORD: 'Retype Password', + NEW_PASSWORD_CONFIRMATION_REQUIRED: 'The new password confirmation is required.', + NEW_PASSWORD_REQUIRED: 'The new password is required.', + OLD_PASSWORD_REQUIRED: 'The old password is required.', + USER_DELETED_SUCCESSFULLY: 'The user was successfully deleted.', + PV_BATTERY_VISUALIZATION: 'PV Battery Visualization', + MEDIA_VIEWER: 'Media Viewer', + NO_MEDIA: 'No media files found', + CHANNEL_VALUE_UPDATED_SUCCESSFULLY: 'The new value was written to the channel', + CHANNEL_VALUE_UPDATED_ERROR: 'The new value was not written to the channel. Something went wrong.', + }); + + $translateProvider.translations('de', { + DRIVERS: 'Treiber', + DASHBOARD: 'Dashboard', + DEVICES: 'Geräte', + CHANNELS: 'Kanäle', + PLOTTER: 'Plotter', + USERS: 'Users', + BUTTON_LANG_EN: 'Englisch', + BUTTON_LANG_DE: 'Deutsch', + LANGUAGE: 'Sprache', + NOW: 'Jetzt', + SECONDS: 'Sekunden', + MINUTES: 'Minuten', + HOURS: 'Stunden', + }); + $translateProvider.useCookieStorage(); - $translateProvider.preferredLanguage('en'); + $translateProvider.preferredLanguage('en'); }); - + })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/app.js b/projects/webui/base/src/main/resources/js/app.js index 8aebf84b..7967db79 100644 --- a/projects/webui/base/src/main/resources/js/app.js +++ b/projects/webui/base/src/main/resources/js/app.js @@ -1,37 +1,37 @@ -(function(){ - - var app = angular.module('openmuc', ['openmuc.auth', - 'openmuc.common', - 'openmuc.constants', - 'openmuc.dashboard', - 'openmuc.filters', - 'openmuc.i18n', - 'openmuc.sessions', - 'ngCookies', - 'mgcrea.ngStrap', - 'ngAnimate', - 'validation.match', - 'ui.router', - 'oc.lazyLoad']); +(function () { + + var app = angular.module('openmuc', ['openmuc.auth', + 'openmuc.common', + 'openmuc.constants', + 'openmuc.dashboard', + 'openmuc.filters', + 'openmuc.i18n', + 'openmuc.sessions', + 'ngCookies', + 'mgcrea.ngStrap', + 'ngAnimate', + 'validation.match', + 'ui.router', + 'oc.lazyLoad']); + + angular.module('openmuc.auth', []); + angular.module('openmuc.common', []); + angular.module('openmuc.constants', []); + angular.module('openmuc.dashboard', []); + angular.module('openmuc.filters', []); + angular.module('openmuc.sessions', []); + + // TODO: Move me to somewhere else + + app.config(function ($alertProvider) { + angular.extend($alertProvider.defaults, { + placement: 'top-right', + animation: 'am-fade-and-slide-top', + duration: 5, + keyboard: true, + dismissable: true, + show: true + }); + }); - angular.module('openmuc.auth', []); - angular.module('openmuc.common', []); - angular.module('openmuc.constants', []); - angular.module('openmuc.dashboard', []); - angular.module('openmuc.filters', []); - angular.module('openmuc.sessions', []); - - // TODO: Move me to somewhere else - - app.config(function($alertProvider) { - angular.extend($alertProvider.defaults, { - placement: 'top-right', - animation: 'am-fade-and-slide-top', - duration: 5, - keyboard: true, - dismissable: true, - show: true - }); - }); - })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/app.routes.js b/projects/webui/base/src/main/resources/js/app.routes.js index 6afc173c..f745697a 100644 --- a/projects/webui/base/src/main/resources/js/app.routes.js +++ b/projects/webui/base/src/main/resources/js/app.routes.js @@ -1,40 +1,40 @@ -(function(){ - - var app = angular.module('openmuc'); +(function () { + + var app = angular.module('openmuc'); + + app.config(['$stateProvider', '$urlRouterProvider', + function ($stateProvider, $urlRouterProvider) { + $urlRouterProvider.otherwise('/'); + + $stateProvider. + state('home', { + url: "/", + templateUrl: '/openmuc/html/sessions/new.html', + controller: 'LoginController', + requireLogin: false, + }). + state('dashboard', { + url: "/dashboard", + templateUrl: "/openmuc/html/dashboard/index.html", + controller: 'DashboardController', + requireLogin: true, + resolve: { + openmuc: ['AppsDependenciesService', function (AppsDependenciesService) { + return AppsDependenciesService.loadDependencies(); + }] + } + }) + + }]); + + app.run(['$rootScope', '$alert', '$state', 'AuthService', function ($rootScope, $alert, $state, AuthService) { + $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { + if (toState.requireLogin && !AuthService.isLoggedIn()) { + $alert({content: 'You need to be authenticated to see this page!', type: 'warning'}); + AuthService.redirectToLogin(); + event.preventDefault(); + } + }); + }]); - app.config(['$stateProvider', '$urlRouterProvider', - function($stateProvider, $urlRouterProvider) { - $urlRouterProvider.otherwise('/'); - - $stateProvider. - state('home', { - url: "/", - templateUrl: '/openmuc/html/sessions/new.html', - controller: 'LoginController', - requireLogin: false, - }). - state('dashboard', { - url: "/dashboard", - templateUrl: "/openmuc/html/dashboard/index.html", - controller: 'DashboardController', - requireLogin: true, - resolve: { - openmuc: ['AppsDependenciesService', function (AppsDependenciesService) { - return AppsDependenciesService.loadDependencies(); - }] - } - }) - - }]); - - app.run(['$rootScope', '$alert', '$state', 'AuthService', function ($rootScope, $alert, $state, AuthService) { - $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){ - if (toState.requireLogin && !AuthService.isLoggedIn()){ - $alert({content: 'You need to be authenticated to see this page!', type: 'warning'}); - AuthService.redirectToLogin(); - event.preventDefault(); - } - }); - }]); - })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/application/applicationController.js b/projects/webui/base/src/main/resources/js/application/applicationController.js index be065ddc..5ce2a9d4 100644 --- a/projects/webui/base/src/main/resources/js/application/applicationController.js +++ b/projects/webui/base/src/main/resources/js/application/applicationController.js @@ -1,44 +1,44 @@ -(function(){ - - var injectParams = ['$scope', '$state', '$cookieStore', '$alert', '$translate', 'AuthService']; - - var ApplicationController = function($scope, $state, $cookieStore, $alert, $translate, AuthService) { - - $translate('SUCCESSFULLY_LOGGED_OUT').then(function(text) { - $scope.loggedOutText = text; - }); - - $scope.isLoggedIn = function() { - return AuthService.isLoggedIn(); - } - - $scope.currentUsername = function() { - return AuthService.currentUsername(); - } - - $scope.logout = function() { - AuthService.logout(); - - $alert({content: $scope.loggedOutText, type: 'success'}); - $state.go('home'); - }; - - $scope.changeLanguage = function (key) { - $translate.use(key); - }; - - $scope.currentLanguageIsEnglish = function() { - return $translate.use() == 'en'; - }; - - $scope.currentLanguageIsGerman = function() { - return $translate.use() == 'de'; - }; - - }; - - ApplicationController.$inject = injectParams; - - angular.module('openmuc.common').controller('ApplicationController', ApplicationController); - +(function () { + + var injectParams = ['$scope', '$state', '$cookieStore', '$alert', '$translate', 'AuthService']; + + var ApplicationController = function ($scope, $state, $cookieStore, $alert, $translate, AuthService) { + + $translate('SUCCESSFULLY_LOGGED_OUT').then(function (text) { + $scope.loggedOutText = text; + }); + + $scope.isLoggedIn = function () { + return AuthService.isLoggedIn(); + } + + $scope.currentUsername = function () { + return AuthService.currentUsername(); + } + + $scope.logout = function () { + AuthService.logout(); + + $alert({content: $scope.loggedOutText, type: 'success'}); + $state.go('home'); + }; + + $scope.changeLanguage = function (key) { + $translate.use(key); + }; + + $scope.currentLanguageIsEnglish = function () { + return $translate.use() == 'en'; + }; + + $scope.currentLanguageIsGerman = function () { + return $translate.use() == 'de'; + }; + + }; + + ApplicationController.$inject = injectParams; + + angular.module('openmuc.common').controller('ApplicationController', ApplicationController); + })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/apps/appsDependenciesService.js b/projects/webui/base/src/main/resources/js/apps/appsDependenciesService.js index 22f6c79f..1303ff72 100644 --- a/projects/webui/base/src/main/resources/js/apps/appsDependenciesService.js +++ b/projects/webui/base/src/main/resources/js/apps/appsDependenciesService.js @@ -1,34 +1,34 @@ -(function(){ - - var injectParams = ['$ocLazyLoad', 'AvailableAppsService']; - - var AppsDependenciesService = function($ocLazyLoad, AvailableAppsService) { - - this.loadDependencies = function() { - var files = []; - - return AvailableAppsService.getAll().then(function(response){ - $.each(response, function(index, value) { - files.push(value.alias + '/js/app.js'); - files.push(value.alias + '/js/app.routes.js'); - }); - - return $ocLazyLoad.load( - { - name: "openmuc", - files: files - } - ); - - }, function(data) { - }); - - } - - }; +(function () { + + var injectParams = ['$ocLazyLoad', 'AvailableAppsService']; + + var AppsDependenciesService = function ($ocLazyLoad, AvailableAppsService) { + + this.loadDependencies = function () { + var files = []; + + return AvailableAppsService.getAll().then(function (response) { + $.each(response, function (index, value) { + files.push(value.alias + '/js/app.js'); + files.push(value.alias + '/js/app.routes.js'); + }); + + return $ocLazyLoad.load( + { + name: "openmuc", + files: files + } + ); + + }, function (data) { + }); + + } + + }; AppsDependenciesService.$inject = injectParams; - angular.module('openmuc.common').service('AppsDependenciesService', AppsDependenciesService); + angular.module('openmuc.common').service('AppsDependenciesService', AppsDependenciesService); })(); diff --git a/projects/webui/base/src/main/resources/js/apps/availableAppsService.js b/projects/webui/base/src/main/resources/js/apps/availableAppsService.js index e6de9be9..3f05ba69 100644 --- a/projects/webui/base/src/main/resources/js/apps/availableAppsService.js +++ b/projects/webui/base/src/main/resources/js/apps/availableAppsService.js @@ -1,17 +1,17 @@ -(function(){ +(function () { - var injectParams = ['$http', 'SETTINGS']; - - var AvailableAppsService = function($http, SETTINGS) { - this.getAll = function() { - return $http.get(SETTINGS.APPS_URL).then(function(response){ - return response.data; - }); - } + var injectParams = ['$http', 'SETTINGS']; + + var AvailableAppsService = function ($http, SETTINGS) { + this.getAll = function () { + return $http.get(SETTINGS.APPS_URL).then(function (response) { + return response.data; + }); + } }; AvailableAppsService.$inject = injectParams; - angular.module('openmuc.common').service('AvailableAppsService', AvailableAppsService); + angular.module('openmuc.common').service('AvailableAppsService', AvailableAppsService); })(); diff --git a/projects/webui/base/src/main/resources/js/authentication/authService.js b/projects/webui/base/src/main/resources/js/authentication/authService.js index 3cb24d16..ac908bca 100644 --- a/projects/webui/base/src/main/resources/js/authentication/authService.js +++ b/projects/webui/base/src/main/resources/js/authentication/authService.js @@ -1,54 +1,54 @@ -(function(){ - - var injectParams = ['$rootScope', '$http', '$state', '$cookieStore', '$state', 'SETTINGS']; - - var AuthService = function($rootScope, $http, $state, $cookieStore, $state, SETTINGS) { - - this.login = function(credentials) { - - var req = { - method: 'POST', - url: SETTINGS.LOGIN_URL, - data: $.param({user: credentials.user, pwd: credentials.pwd}), - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - }; - - return $http(req).then(function(response) { - return response.data; - }); - }; - - this.isLoggedIn = function() { - if ($cookieStore.get('user')) { - return true; - } else { - return false; - } - }; - - this.currentUsername = function() { - return $cookieStore.get('user').user; - } - - this.setCurrentUser = function (user) { - $cookieStore.put('user', user); - }; - - this.redirectToLogin = function() { - $state.go('home'); - }; - - this.logout = function() { - $rootScope.currentUser = null; - $cookieStore.remove('user'); - }; - - }; - - AuthService.$inject = injectParams; - - angular.module('openmuc.auth').service('AuthService', AuthService); - +(function () { + + var injectParams = ['$rootScope', '$http', '$state', '$cookieStore', '$state', 'SETTINGS']; + + var AuthService = function ($rootScope, $http, $state, $cookieStore, $state, SETTINGS) { + + this.login = function (credentials) { + + var req = { + method: 'POST', + url: SETTINGS.LOGIN_URL, + data: $.param({user: credentials.user, pwd: credentials.pwd}), + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }; + + return $http(req).then(function (response) { + return response.data; + }); + }; + + this.isLoggedIn = function () { + if ($cookieStore.get('user')) { + return true; + } else { + return false; + } + }; + + this.currentUsername = function () { + return $cookieStore.get('user').user; + } + + this.setCurrentUser = function (user) { + $cookieStore.put('user', user); + }; + + this.redirectToLogin = function () { + $state.go('home'); + }; + + this.logout = function () { + $rootScope.currentUser = null; + $cookieStore.remove('user'); + }; + + }; + + AuthService.$inject = injectParams; + + angular.module('openmuc.auth').service('AuthService', AuthService); + })(); diff --git a/projects/webui/base/src/main/resources/js/authentication/restServerAuthService.js b/projects/webui/base/src/main/resources/js/authentication/restServerAuthService.js index afad0c9f..f8ae48b4 100644 --- a/projects/webui/base/src/main/resources/js/authentication/restServerAuthService.js +++ b/projects/webui/base/src/main/resources/js/authentication/restServerAuthService.js @@ -1,15 +1,15 @@ -(function(){ - - var injectParams = []; - - var RestServerAuthService = function() { - this.getAuthHash = function() { - return 'Basic ' + btoa("admin:admin"); - }; +(function () { + + var injectParams = []; + + var RestServerAuthService = function () { + this.getAuthHash = function () { + return 'Basic ' + btoa("admin:admin"); + }; }; RestServerAuthService.$inject = injectParams; - angular.module('openmuc.auth').service('RestServerAuthService', RestServerAuthService); + angular.module('openmuc.auth').service('RestServerAuthService', RestServerAuthService); })(); diff --git a/projects/webui/base/src/main/resources/js/commons/constants.js b/projects/webui/base/src/main/resources/js/commons/constants.js index cffcee31..ef6d1d01 100644 --- a/projects/webui/base/src/main/resources/js/commons/constants.js +++ b/projects/webui/base/src/main/resources/js/commons/constants.js @@ -1,20 +1,20 @@ -(function(){ - - var app = angular.module('openmuc.constants'); - - app.constant('SETTINGS', { - API_URL: '/rest/', - DRIVERS_URL: 'drivers/', - CHANNELS_URL: 'channels/', - CHANNELS_HISTORY_URL: '/history', - DEVICES_URL: 'devices/', - SCAN_URL: 'scan', - APPS_URL: '/applications', - CONFIGS_URL: '/configs', - LOGIN_URL: '/login', - USERS_URL: 'users/', - MEDIA_CONFIG_URL: '/conf/webui/mediaviewer', - DATAPLOTTER_CONFIG_URL: '/conf/webui/dataplotter' - }); +(function () { + + var app = angular.module('openmuc.constants'); + + app.constant('SETTINGS', { + API_URL: '/rest/', + DRIVERS_URL: 'drivers/', + CHANNELS_URL: 'channels/', + CHANNELS_HISTORY_URL: '/history', + DEVICES_URL: 'devices/', + SCAN_URL: 'scan', + APPS_URL: '/applications', + CONFIGS_URL: '/configs', + LOGIN_URL: '/login', + USERS_URL: 'users/', + MEDIA_CONFIG_URL: '/conf/webui/mediaviewer', + DATAPLOTTER_CONFIG_URL: '/conf/webui/dataplotter' + }); })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/commons/filters.js b/projects/webui/base/src/main/resources/js/commons/filters.js index c1c10c9d..76116595 100644 --- a/projects/webui/base/src/main/resources/js/commons/filters.js +++ b/projects/webui/base/src/main/resources/js/commons/filters.js @@ -1,15 +1,15 @@ -(function(){ - - var injectParams = []; - - var yesNoIcon = function() { - return function(input) { - return input ? 'fa fa-check' : 'fa fa-times'; - }; - }; - - yesNoIcon.$inject = injectParams; - - angular.module('openmuc.filters').filter('yesNoIcon', yesNoIcon); +(function () { + + var injectParams = []; + + var yesNoIcon = function () { + return function (input) { + return input ? 'fa fa-check' : 'fa fa-times'; + }; + }; + + yesNoIcon.$inject = injectParams; + + angular.module('openmuc.filters').filter('yesNoIcon', yesNoIcon); })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/commons/tabsController.js b/projects/webui/base/src/main/resources/js/commons/tabsController.js index 85693fb0..d791abc6 100644 --- a/projects/webui/base/src/main/resources/js/commons/tabsController.js +++ b/projects/webui/base/src/main/resources/js/commons/tabsController.js @@ -1,80 +1,80 @@ -(function(){ - - var injectParams = ['$scope', '$location']; - - var TabsController = function($scope, $location) { - $scope.isTabActive = function(url) { - return $location.url().search(url) > -1; - }; - - $scope.isDriversPage = function() { - return $location.url() == "/channelconfigurator/"; - }; - - $scope.isDevicesPage = function() { - return $location.url() == "/channelconfigurator/devices"; - }; - - $scope.isChannelsPage = function() { - return $location.url() == "/channelconfigurator/channels"; - }; - - $scope.isOptionsPage = function() { - return $location.url() == "/channelconfigurator/options"; - }; - - $scope.isDriversEditPage = function() { - return $location.url().search('/drivers/edit') > -1; - }; - - $scope.isDevicesEditPage = function() { - return $location.url().search('/devices/edit') > -1; - }; - - $scope.isChannelsEditPage = function() { - return $location.url().search('/channels/edit') > -1; - }; - - $scope.isDriversNewPage = function() { - return $location.url().search('/drivers/new') > -1; - }; - - $scope.isDevicesNewPage = function() { - return $location.url().search('/devices/new') > -1; - }; - - $scope.isChannelsNewPage = function() { - return $location.url().search('/channels/new') > -1; - }; - - $scope.isDriversScanPage = function() { - return $location.url().search('/drivers/scan') > -1; - }; - - $scope.isDevicesScanPage = function() { - return $location.url().search('/devices/scan') > -1; - } - - $scope.isDataPlotterPage = function() { - return $location.url() == '/dataplotter/data/'; - }; - - $scope.isLivePlotterPage = function() { - return $location.url() == '/dataplotter/live/'; - }; - - $scope.isPlotterPageActive = function(type, name) { - if ($location.url() == '/dataplotter/'+type+"/"+encodeURIComponent(name)) { - return true; - } else { - return false; - } - }; - - }; - - TabsController.$inject = injectParams; - - angular.module('openmuc.common').controller('TabsController', TabsController); - +(function () { + + var injectParams = ['$scope', '$location']; + + var TabsController = function ($scope, $location) { + $scope.isTabActive = function (url) { + return $location.url().search(url) > -1; + }; + + $scope.isDriversPage = function () { + return $location.url() == "/channelconfigurator/"; + }; + + $scope.isDevicesPage = function () { + return $location.url() == "/channelconfigurator/devices"; + }; + + $scope.isChannelsPage = function () { + return $location.url() == "/channelconfigurator/channels"; + }; + + $scope.isOptionsPage = function () { + return $location.url() == "/channelconfigurator/options"; + }; + + $scope.isDriversEditPage = function () { + return $location.url().search('/drivers/edit') > -1; + }; + + $scope.isDevicesEditPage = function () { + return $location.url().search('/devices/edit') > -1; + }; + + $scope.isChannelsEditPage = function () { + return $location.url().search('/channels/edit') > -1; + }; + + $scope.isDriversNewPage = function () { + return $location.url().search('/drivers/new') > -1; + }; + + $scope.isDevicesNewPage = function () { + return $location.url().search('/devices/new') > -1; + }; + + $scope.isChannelsNewPage = function () { + return $location.url().search('/channels/new') > -1; + }; + + $scope.isDriversScanPage = function () { + return $location.url().search('/drivers/scan') > -1; + }; + + $scope.isDevicesScanPage = function () { + return $location.url().search('/devices/scan') > -1; + } + + $scope.isDataPlotterPage = function () { + return $location.url() == '/dataplotter/data/'; + }; + + $scope.isLivePlotterPage = function () { + return $location.url() == '/dataplotter/live/'; + }; + + $scope.isPlotterPageActive = function (type, name) { + if ($location.url() == '/dataplotter/' + type + "/" + encodeURIComponent(name)) { + return true; + } else { + return false; + } + }; + + }; + + TabsController.$inject = injectParams; + + angular.module('openmuc.common').controller('TabsController', TabsController); + })(); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/dashboard/dashboardController.js b/projects/webui/base/src/main/resources/js/dashboard/dashboardController.js index 7d7b0077..8edfaefd 100644 --- a/projects/webui/base/src/main/resources/js/dashboard/dashboardController.js +++ b/projects/webui/base/src/main/resources/js/dashboard/dashboardController.js @@ -1,40 +1,40 @@ -(function(){ - - var injectParams = ['$scope', '$state', '$alert', '$translate', 'AvailableAppsService', 'AuthService']; - - var DashboardController = function($scope, $state, $alert, $translate, AvailableAppsService, AuthService) { - - $translate('LOADING_APP_DEPENDENCES_ERROR').then(function(text) { - $scope.loadingAppDependencesErrorText = text; - }); - - $translate('SESSION_EXPIRED').then(function(text) { - $scope.sessionExpiredText = text; - }); - - var appsAliases = []; - $scope.availableApps = []; - - AvailableAppsService.getAll().then(function(response){ - $scope.availableApps = response; - - $.each(response, function(index, value) { - appsAliases.push(value.alias); - }); - }, function(error) { - if (error.status == 401) { - AuthService.logout(); - $alert({content: $scope.sessionExpiredText, type: 'warning'}); - $state.go('home'); - } else { - $alert({content: $scope.loadingAppDependencesErrorText, type: 'warning'}); - } - }); - - }; - - DashboardController.$inject = injectParams; - - angular.module('openmuc.dashboard').controller('DashboardController', DashboardController); +(function () { + + var injectParams = ['$scope', '$state', '$alert', '$translate', 'AvailableAppsService', 'AuthService']; + + var DashboardController = function ($scope, $state, $alert, $translate, AvailableAppsService, AuthService) { + + $translate('LOADING_APP_DEPENDENCES_ERROR').then(function (text) { + $scope.loadingAppDependencesErrorText = text; + }); + + $translate('SESSION_EXPIRED').then(function (text) { + $scope.sessionExpiredText = text; + }); + + var appsAliases = []; + $scope.availableApps = []; + + AvailableAppsService.getAll().then(function (response) { + $scope.availableApps = response; + + $.each(response, function (index, value) { + appsAliases.push(value.alias); + }); + }, function (error) { + if (error.status == 401) { + AuthService.logout(); + $alert({content: $scope.sessionExpiredText, type: 'warning'}); + $state.go('home'); + } else { + $alert({content: $scope.loadingAppDependencesErrorText, type: 'warning'}); + } + }); + + }; + + DashboardController.$inject = injectParams; + + angular.module('openmuc.dashboard').controller('DashboardController', DashboardController); })(); diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-animate.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-animate.js index 503010ad..d445ac4f 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-animate.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-animate.js @@ -3,193 +3,194 @@ * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; - -/* jshint maxlen: false */ - -/** - * @ngdoc module - * @name ngAnimate - * @description - * - * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. - * - *
              - * - * # Usage - * - * To see animations in action, all that is required is to define the appropriate CSS classes - * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: - * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation - * by using the `$animate` service. - * - * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: - * - * | Directive | Supported Animations | - * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| - * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | - * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave | - * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave | - * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave | - * | {@link ng.directive:ngIf#animations ngIf} | enter and leave | - * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) | - * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) | - * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | - * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) | - * | {@link module:ngMessages#animations ngMessage} | enter and leave | - * - * You can find out more information about animations upon visiting each directive page. - * - * Below is an example of how to apply animations to a directive that supports animation hooks: - * - * ```html - * - * - * - * - * ``` - * - * Keep in mind that, by default, if an animation is running, any child elements cannot be animated - * until the parent element's animation has completed. This blocking feature can be overridden by - * placing the `ng-animate-children` attribute on a parent container tag. - * - * ```html - *
              - *
              - *
              - * ... - *
              - *
              - *
              - * ``` - * - * When the `on` expression value changes and an animation is triggered then each of the elements within - * will all animate without the block being applied to child elements. - * - * ## Are animations run when the application starts? - * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid - * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work, - * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering - * layout changes in the application will trigger animations as normal. - * - * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular - * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests - * are complete. - * - * ## CSS-defined Animations - * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes - * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported - * and can be used to play along with this naming structure. - * - * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: - * - * ```html - * + * + * + * + * ``` + * + * Keep in mind that, by default, if an animation is running, any child elements cannot be animated + * until the parent element's animation has completed. This blocking feature can be overridden by + * placing the `ng-animate-children` attribute on a parent container tag. + * + * ```html + *
              + *
              + *
              + * ... + *
              + *
              + *
              + * ``` + * + * When the `on` expression value changes and an animation is triggered then each of the elements within + * will all animate without the block being applied to child elements. + * + * ## Are animations run when the application starts? + * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid + * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work, + * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering + * layout changes in the application will trigger animations as normal. + * + * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular + * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests + * are complete. + * + * ## CSS-defined Animations + * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes + * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported + * and can be used to play along with this naming structure. + * + * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: + * + * ```html + * - * - *
              - *
              - *
              - * ``` - * - * The following code below demonstrates how to perform animations using **CSS animations** with Angular: - * - * ```html - * + * + *
              + *
              + *
              + * ``` + * + * The following code below demonstrates how to perform animations using **CSS animations** with Angular: + * + * ```html + * - * - *
              - *
              - *
              - * ``` - * - * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. - * - * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add - * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically - * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be - * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end - * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element - * has no CSS transition/animation classes applied to it. - * - * ### Structural transition animations - * - * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition - * value to force the browser into rendering the styles defined in the setup (.ng-enter, .ng-leave - * or .ng-move) class. This means that any active transition animations operating on the element - * will be cut off to make way for the enter, leave or move animation. - * - * ### Class-based transition animations - * - * Class-based transitions refer to transition animations that are triggered when a CSS class is - * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`, - * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`). - * They are different when compared to structural animations since they **do not cancel existing - * animations** nor do they **block successive transitions** from rendering on the same element. - * This distinction allows for **multiple class-based transitions** to be performed on the same element. - * - * In addition to ngAnimate supporting the default (natural) functionality of class-based transition - * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the - * developer in further styling the element throughout the transition animation. Earlier versions - * of ngAnimate may have caused natural CSS transitions to break and not render properly due to - * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class - * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of - * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS - * class transitions are compatible with ngAnimate. - * - * There is, however, one special case when dealing with class-based transitions in ngAnimate. - * When rendering class-based transitions that make use of the setup and active CSS classes - * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define - * the transition value **on the active CSS class** and not the setup class. - * - * ```css - * .fade-add { + * + * + *
              + *
              + *
              + * ``` + * + * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. + * + * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add + * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically + * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be + * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end + * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element + * has no CSS transition/animation classes applied to it. + * + * ### Structural transition animations + * + * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition + * value to force the browser into rendering the styles defined in the setup (.ng-enter, .ng-leave + * or .ng-move) class. This means that any active transition animations operating on the element + * will be cut off to make way for the enter, leave or move animation. + * + * ### Class-based transition animations + * + * Class-based transitions refer to transition animations that are triggered when a CSS class is + * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`, + * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`). + * They are different when compared to structural animations since they **do not cancel existing + * animations** nor do they **block successive transitions** from rendering on the same element. + * This distinction allows for **multiple class-based transitions** to be performed on the same element. + * + * In addition to ngAnimate supporting the default (natural) functionality of class-based transition + * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the + * developer in further styling the element throughout the transition animation. Earlier versions + * of ngAnimate may have caused natural CSS transitions to break and not render properly due to + * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class + * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of + * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS + * class transitions are compatible with ngAnimate. + * + * There is, however, one special case when dealing with class-based transitions in ngAnimate. + * When rendering class-based transitions that make use of the setup and active CSS classes + * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define + * the transition value **on the active CSS class** and not the setup class. + * + * ```css + * .fade-add { * /* remember to place a 0s transition here * to ensure that the styles are applied instantly * even if the element already has a transition style */ @@ -198,48 +199,48 @@ * /* starting CSS styles */ * opacity:1; * } - * .fade-add.fade-add-active { + * .fade-add.fade-add-active { * /* this will be the length of the animation */ * transition:1s linear all; * opacity:0; * } - * ``` - * - * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it - * has a duration of zero. This may not be required, however, incase the browser is unable to render - * the styling present in this CSS class instantly then it could be that the browser is attempting - * to perform an unnecessary transition. - * - * This workaround, however, does not apply to standard class-based transitions that are rendered - * when a CSS class containing a transition is applied to an element: - * - * ```css - * .fade { + * ``` + * + * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it + * has a duration of zero. This may not be required, however, incase the browser is unable to render + * the styling present in this CSS class instantly then it could be that the browser is attempting + * to perform an unnecessary transition. + * + * This workaround, however, does not apply to standard class-based transitions that are rendered + * when a CSS class containing a transition is applied to an element: + * + * ```css + * .fade { * /* this works as expected */ * transition:1s linear all; * opacity:0; * } - * ``` - * - * Please keep this in mind when coding the CSS markup that will be used within class-based transitions. - * Also, try not to mix the two class-based animation flavors together since the CSS code may become - * overly complex. - * - * ### CSS Staggering Animations - * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a - * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be - * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for - * the animation. The style property expected within the stagger class can either be a **transition-delay** or an - * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). - * - * ```css - * .my-animation.ng-enter { + * ``` + * + * Please keep this in mind when coding the CSS markup that will be used within class-based transitions. + * Also, try not to mix the two class-based animation flavors together since the CSS code may become + * overly complex. + * + * ### CSS Staggering Animations + * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a + * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be + * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for + * the animation. The style property expected within the stagger class can either be a **transition-delay** or an + * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). + * + * ```css + * .my-animation.ng-enter { * /* standard transition code */ * -webkit-transition: 1s linear all; * transition: 1s linear all; * opacity:0; * } - * .my-animation.ng-enter-stagger { + * .my-animation.ng-enter-stagger { * /* this will have a 100ms delay between each successive leave animation */ * -webkit-transition-delay: 0.1s; * transition-delay: 0.1s; @@ -249,45 +250,45 @@ * -webkit-transition-duration: 0s; * transition-duration: 0s; * } - * .my-animation.ng-enter.ng-enter-active { + * .my-animation.ng-enter.ng-enter-active { * /* standard transition styles */ * opacity:1; * } - * ``` - * - * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations - * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this - * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation - * will also be reset if more than 10ms has passed after the last animation has been fired. - * - * The following code will issue the **ng-leave-stagger** event on the element provided: - * - * ```js - * var kids = parent.children(); - * - * $animate.leave(kids[0]); //stagger index=0 - * $animate.leave(kids[1]); //stagger index=1 - * $animate.leave(kids[2]); //stagger index=2 - * $animate.leave(kids[3]); //stagger index=3 - * $animate.leave(kids[4]); //stagger index=4 - * - * $timeout(function() { + * ``` + * + * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations + * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this + * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation + * will also be reset if more than 10ms has passed after the last animation has been fired. + * + * The following code will issue the **ng-leave-stagger** event on the element provided: + * + * ```js + * var kids = parent.children(); + * + * $animate.leave(kids[0]); //stagger index=0 + * $animate.leave(kids[1]); //stagger index=1 + * $animate.leave(kids[2]); //stagger index=2 + * $animate.leave(kids[3]); //stagger index=3 + * $animate.leave(kids[4]); //stagger index=4 + * + * $timeout(function() { * //stagger has reset itself * $animate.leave(kids[5]); //stagger index=0 * $animate.leave(kids[6]); //stagger index=1 * }, 100, false); - * ``` - * - * Stagger animations are currently only supported within CSS-defined animations. - * - * ## JavaScript-defined Animations - * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not - * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. - * - * ```js - * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. - * var ngModule = angular.module('YourApp', ['ngAnimate']); - * ngModule.animation('.my-crazy-animation', function() { + * ``` + * + * Stagger animations are currently only supported within CSS-defined animations. + * + * ## JavaScript-defined Animations + * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not + * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. + * + * ```js + * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. + * var ngModule = angular.module('YourApp', ['ngAnimate']); + * ngModule.animation('.my-crazy-animation', function() { * return { * enter: function(element, done) { * //run the animation here and call done when the animation is complete @@ -313,29 +314,29 @@ * removeClass: function(element, className, done) { } * }; * }); - * ``` - * - * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run - * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits - * the element's CSS class attribute value and then run the matching animation event function (if found). - * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will - * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). - * - * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. - * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, - * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation - * or transition code that is defined via a stylesheet). - * - * - * ### Applying Directive-specific Styles to an Animation - * In some cases a directive or service may want to provide `$animate` with extra details that the animation will - * include into its animation. Let's say for example we wanted to render an animation that animates an element - * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click - * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function - * call to `$animate.addClass`. - * - * ```js - * canvas.on('click', function(e) { + * ``` + * + * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run + * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits + * the element's CSS class attribute value and then run the matching animation event function (if found). + * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will + * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). + * + * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. + * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, + * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation + * or transition code that is defined via a stylesheet). + * + * + * ### Applying Directive-specific Styles to an Animation + * In some cases a directive or service may want to provide `$animate` with extra details that the animation will + * include into its animation. Let's say for example we wanted to render an animation that animates an element + * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click + * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function + * call to `$animate.addClass`. + * + * ```js + * canvas.on('click', function(e) { * $animate.addClass(element, 'on', { * to: { * left : e.client.x + 'px', @@ -343,15 +344,15 @@ * } * }): * }); - * ``` - * - * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will - * also include and transition the styling of the `left` and `top` properties into its running animation. If we want - * to provide some starting animation values then we can do so by placing the starting animations styles into an object - * called `from` in the same object as the `to` animations. - * - * ```js - * canvas.on('click', function(e) { + * ``` + * + * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will + * also include and transition the styling of the `left` and `top` properties into its running animation. If we want + * to provide some starting animation values then we can do so by placing the starting animations styles into an object + * called `from` in the same object as the `to` animations. + * + * ```js + * canvas.on('click', function(e) { * $animate.addClass(element, 'on', { * from: { * position: 'absolute', @@ -364,1749 +365,1755 @@ * } * }): * }); - * ``` - * - * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the - * element. If `ngAnimate` is not present then the styles will be applied immediately. - * - */ - -angular.module('ngAnimate', ['ng']) - - /** - * @ngdoc provider - * @name $animateProvider - * @description - * - * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. - * When an animation is triggered, the $animate service will query the $animate service to find any animations that match - * the provided name value. - * - * Requires the {@link ngAnimate `ngAnimate`} module to be installed. - * - * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. - * - */ - .directive('ngAnimateChildren', function() { - var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; - return function(scope, element, attrs) { - var val = attrs.ngAnimateChildren; - if (angular.isString(val) && val.length === 0) { //empty attribute - element.data(NG_ANIMATE_CHILDREN, true); - } else { - scope.$watch(val, function(value) { - element.data(NG_ANIMATE_CHILDREN, !!value); - }); - } - }; - }) - - //this private service is only used within CSS-enabled animations - //IE8 + IE9 do not support rAF natively, but that is fine since they - //also don't support transitions and keyframes which means that the code - //below will never be used by the two browsers. - .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) { - var bod = $document[0].body; - return function(fn) { - //the returned function acts as the cancellation function - return $$rAF(function() { - //the line below will force the browser to perform a repaint - //so that all the animated elements within the animation frame - //will be properly updated and drawn on screen. This is - //required to perform multi-class CSS based animations with - //Firefox. DO NOT REMOVE THIS LINE. - var a = bod.offsetWidth + 1; - fn(); - }); - }; - }]) - - .config(['$provide', '$animateProvider', function($provide, $animateProvider) { - var noop = angular.noop; - var forEach = angular.forEach; - var selectors = $animateProvider.$$selectors; - var isArray = angular.isArray; - var isString = angular.isString; - var isObject = angular.isObject; - - var ELEMENT_NODE = 1; - var NG_ANIMATE_STATE = '$$ngAnimateState'; - var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; - var NG_ANIMATE_CLASS_NAME = 'ng-animate'; - var rootAnimateState = {running: true}; - - function extractElementNode(element) { - for(var i = 0; i < element.length; i++) { - var elm = element[i]; - if (elm.nodeType == ELEMENT_NODE) { - return elm; - } - } - } - - function prepareElement(element) { - return element && angular.element(element); - } - - function stripCommentsFromElement(element) { - return angular.element(extractElementNode(element)); - } - - function isMatchingElement(elm1, elm2) { - return extractElementNode(elm1) == extractElementNode(elm2); - } - - $provide.decorator('$animate', - ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', - function($delegate, $$q, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document, $templateRequest) { - - $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); - - // Wait until all directive and route-related templates are downloaded and - // compiled. The $templateRequest.totalPendingRequests variable keeps track of - // all of the remote templates being currently downloaded. If there are no - // templates currently downloading then the watcher will still fire anyway. - var deregisterWatch = $rootScope.$watch( - function() { return $templateRequest.totalPendingRequests; }, - function(val, oldVal) { - if (val !== 0) return; - deregisterWatch(); - - // Now that all templates have been downloaded, $animate will wait until - // the post digest queue is empty before enabling animations. By having two - // calls to $postDigest calls we can ensure that the flag is enabled at the - // very end of the post digest queue. Since all of the animations in $animate - // use $postDigest, it's important that the code below executes at the end. - // This basically means that the page is fully downloaded and compiled before - // any animations are triggered. - $rootScope.$$postDigest(function() { - $rootScope.$$postDigest(function() { - rootAnimateState.running = false; - }); - }); - } - ); - - var globalAnimationCounter = 0; - var classNameFilter = $animateProvider.classNameFilter(); - var isAnimatableClassName = !classNameFilter - ? function() { return true; } - : function(className) { - return classNameFilter.test(className); - }; - - function classBasedAnimationsBlocked(element, setter) { - var data = element.data(NG_ANIMATE_STATE) || {}; - if (setter) { - data.running = true; - data.structural = true; - element.data(NG_ANIMATE_STATE, data); - } - return data.disabled || (data.running && data.structural); - } - - function runAnimationPostDigest(fn) { - var cancelFn, defer = $$q.defer(); - defer.promise.$$cancelFn = function() { - cancelFn && cancelFn(); - }; - $rootScope.$$postDigest(function() { - cancelFn = fn(function() { - defer.resolve(); - }); - }); - return defer.promise; - } - - function parseAnimateOptions(options) { - // some plugin code may still be passing in the callback - // function as the last param for the $animate methods so - // it's best to only allow string or array values for now - if (isObject(options)) { - if (options.tempClasses && isString(options.tempClasses)) { - options.tempClasses = options.tempClasses.split(/\s+/); - } - return options; - } - } - - function resolveElementClasses(element, cache, runningAnimations) { - runningAnimations = runningAnimations || {}; - - var lookup = {}; - forEach(runningAnimations, function(data, selector) { - forEach(selector.split(' '), function(s) { - lookup[s]=data; - }); - }); - - var hasClasses = Object.create(null); - forEach((element.attr('class') || '').split(/\s+/), function(className) { - hasClasses[className] = true; - }); - - var toAdd = [], toRemove = []; - forEach(cache.classes, function(status, className) { - var hasClass = hasClasses[className]; - var matchingAnimation = lookup[className] || {}; - - // When addClass and removeClass is called then $animate will check to - // see if addClass and removeClass cancel each other out. When there are - // more calls to removeClass than addClass then the count falls below 0 - // and then the removeClass animation will be allowed. Otherwise if the - // count is above 0 then that means an addClass animation will commence. - // Once an animation is allowed then the code will also check to see if - // there exists any on-going animation that is already adding or remvoing - // the matching CSS class. - if (status === false) { - //does it have the class or will it have the class - if (hasClass || matchingAnimation.event == 'addClass') { - toRemove.push(className); - } - } else if (status === true) { - //is the class missing or will it be removed? - if (!hasClass || matchingAnimation.event == 'removeClass') { - toAdd.push(className); - } - } - }); - - return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')]; - } - - function lookup(name) { - if (name) { - var matches = [], - flagMap = {}, - classes = name.substr(1).split('.'); - - //the empty string value is the default animation - //operation which performs CSS transition and keyframe - //animations sniffing. This is always included for each - //element animation procedure if the browser supports - //transitions and/or keyframe animations. The default - //animation is added to the top of the list to prevent - //any previous animations from affecting the element styling - //prior to the element being animated. - if ($sniffer.transitions || $sniffer.animations) { - matches.push($injector.get(selectors[''])); - } - - for(var i=0; i < classes.length; i++) { - var klass = classes[i], - selectorFactoryName = selectors[klass]; - if (selectorFactoryName && !flagMap[klass]) { - matches.push($injector.get(selectorFactoryName)); - flagMap[klass] = true; - } - } - return matches; - } - } - - function animationRunner(element, animationEvent, className, options) { - //transcluded directives may sometimes fire an animation using only comment nodes - //best to catch this early on to prevent any animation operations from occurring - var node = element[0]; - if (!node) { - return; - } - - if (options) { - options.to = options.to || {}; - options.from = options.from || {}; - } - - var classNameAdd; - var classNameRemove; - if (isArray(className)) { - classNameAdd = className[0]; - classNameRemove = className[1]; - if (!classNameAdd) { - className = classNameRemove; - animationEvent = 'removeClass'; - } else if (!classNameRemove) { - className = classNameAdd; - animationEvent = 'addClass'; - } else { - className = classNameAdd + ' ' + classNameRemove; - } - } - - var isSetClassOperation = animationEvent == 'setClass'; - var isClassBased = isSetClassOperation - || animationEvent == 'addClass' - || animationEvent == 'removeClass' - || animationEvent == 'animate'; - - var currentClassName = element.attr('class'); - var classes = currentClassName + ' ' + className; - if (!isAnimatableClassName(classes)) { - return; - } - - var beforeComplete = noop, - beforeCancel = [], - before = [], - afterComplete = noop, - afterCancel = [], - after = []; - - var animationLookup = (' ' + classes).replace(/\s+/g,'.'); - forEach(lookup(animationLookup), function(animationFactory) { - var created = registerAnimation(animationFactory, animationEvent); - if (!created && isSetClassOperation) { - registerAnimation(animationFactory, 'addClass'); - registerAnimation(animationFactory, 'removeClass'); - } - }); - - function registerAnimation(animationFactory, event) { - var afterFn = animationFactory[event]; - var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; - if (afterFn || beforeFn) { - if (event == 'leave') { - beforeFn = afterFn; - //when set as null then animation knows to skip this phase - afterFn = null; - } - after.push({ - event : event, fn : afterFn - }); - before.push({ - event : event, fn : beforeFn - }); - return true; - } - } - - function run(fns, cancellations, allCompleteFn) { - var animations = []; - forEach(fns, function(animation) { - animation.fn && animations.push(animation); - }); - - var count = 0; - function afterAnimationComplete(index) { - if (cancellations) { - (cancellations[index] || noop)(); - if (++count < animations.length) return; - cancellations = null; - } - allCompleteFn(); - } - - //The code below adds directly to the array in order to work with - //both sync and async animations. Sync animations are when the done() - //operation is called right away. DO NOT REFACTOR! - forEach(animations, function(animation, index) { - var progress = function() { - afterAnimationComplete(index); + * ``` + * + * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the + * element. If `ngAnimate` is not present then the styles will be applied immediately. + * + */ + + angular.module('ngAnimate', ['ng']) + + /** + * @ngdoc provider + * @name $animateProvider + * @description + * + * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. + * When an animation is triggered, the $animate service will query the $animate service to find any animations that match + * the provided name value. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * + */ + .directive('ngAnimateChildren', function () { + var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; + return function (scope, element, attrs) { + var val = attrs.ngAnimateChildren; + if (angular.isString(val) && val.length === 0) { //empty attribute + element.data(NG_ANIMATE_CHILDREN, true); + } else { + scope.$watch(val, function (value) { + element.data(NG_ANIMATE_CHILDREN, !!value); + }); + } + }; + }) + + //this private service is only used within CSS-enabled animations + //IE8 + IE9 do not support rAF natively, but that is fine since they + //also don't support transitions and keyframes which means that the code + //below will never be used by the two browsers. + .factory('$$animateReflow', ['$$rAF', '$document', function ($$rAF, $document) { + var bod = $document[0].body; + return function (fn) { + //the returned function acts as the cancellation function + return $$rAF(function () { + //the line below will force the browser to perform a repaint + //so that all the animated elements within the animation frame + //will be properly updated and drawn on screen. This is + //required to perform multi-class CSS based animations with + //Firefox. DO NOT REMOVE THIS LINE. + var a = bod.offsetWidth + 1; + fn(); + }); }; - switch(animation.event) { - case 'setClass': - cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options)); - break; - case 'animate': - cancellations.push(animation.fn(element, className, options.from, options.to, progress)); - break; - case 'addClass': - cancellations.push(animation.fn(element, classNameAdd || className, progress, options)); - break; - case 'removeClass': - cancellations.push(animation.fn(element, classNameRemove || className, progress, options)); - break; - default: - cancellations.push(animation.fn(element, progress, options)); - break; + }]) + + .config(['$provide', '$animateProvider', function ($provide, $animateProvider) { + var noop = angular.noop; + var forEach = angular.forEach; + var selectors = $animateProvider.$$selectors; + var isArray = angular.isArray; + var isString = angular.isString; + var isObject = angular.isObject; + + var ELEMENT_NODE = 1; + var NG_ANIMATE_STATE = '$$ngAnimateState'; + var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren'; + var NG_ANIMATE_CLASS_NAME = 'ng-animate'; + var rootAnimateState = {running: true}; + + function extractElementNode(element) { + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType == ELEMENT_NODE) { + return elm; + } + } } - }); - - if (cancellations && cancellations.length === 0) { - allCompleteFn(); - } - } - - return { - node : node, - event : animationEvent, - className : className, - isClassBased : isClassBased, - isSetClassOperation : isSetClassOperation, - applyStyles : function() { - if (options) { - element.css(angular.extend(options.from || {}, options.to || {})); + + function prepareElement(element) { + return element && angular.element(element); } - }, - before : function(allCompleteFn) { - beforeComplete = allCompleteFn; - run(before, beforeCancel, function() { - beforeComplete = noop; - allCompleteFn(); - }); - }, - after : function(allCompleteFn) { - afterComplete = allCompleteFn; - run(after, afterCancel, function() { - afterComplete = noop; - allCompleteFn(); - }); - }, - cancel : function() { - if (beforeCancel) { - forEach(beforeCancel, function(cancelFn) { - (cancelFn || noop)(true); - }); - beforeComplete(true); + + function stripCommentsFromElement(element) { + return angular.element(extractElementNode(element)); } - if (afterCancel) { - forEach(afterCancel, function(cancelFn) { - (cancelFn || noop)(true); - }); - afterComplete(true); + + function isMatchingElement(elm1, elm2) { + return extractElementNode(elm1) == extractElementNode(elm2); } - } - }; - } - - /** - * @ngdoc service - * @name $animate - * @kind object - * - * @description - * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. - * When any of these operations are run, the $animate service - * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) - * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. - * - * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives - * will work out of the box without any extra configuration. - * - * Requires the {@link ngAnimate `ngAnimate`} module to be installed. - * - * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. - * ## Callback Promises - * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The - * promise itself is then resolved once the animation has completed itself, has been cancelled or has been - * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still - * call the resolve function of the animation.) - * - * ```js - * $animate.enter(element, container).then(function() { + + $provide.decorator('$animate', + ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', + function ($delegate, $$q, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document, $templateRequest) { + + $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); + + // Wait until all directive and route-related templates are downloaded and + // compiled. The $templateRequest.totalPendingRequests variable keeps track of + // all of the remote templates being currently downloaded. If there are no + // templates currently downloading then the watcher will still fire anyway. + var deregisterWatch = $rootScope.$watch( + function () { + return $templateRequest.totalPendingRequests; + }, + function (val, oldVal) { + if (val !== 0) return; + deregisterWatch(); + + // Now that all templates have been downloaded, $animate will wait until + // the post digest queue is empty before enabling animations. By having two + // calls to $postDigest calls we can ensure that the flag is enabled at the + // very end of the post digest queue. Since all of the animations in $animate + // use $postDigest, it's important that the code below executes at the end. + // This basically means that the page is fully downloaded and compiled before + // any animations are triggered. + $rootScope.$$postDigest(function () { + $rootScope.$$postDigest(function () { + rootAnimateState.running = false; + }); + }); + } + ); + + var globalAnimationCounter = 0; + var classNameFilter = $animateProvider.classNameFilter(); + var isAnimatableClassName = !classNameFilter + ? function () { + return true; + } + : function (className) { + return classNameFilter.test(className); + }; + + function classBasedAnimationsBlocked(element, setter) { + var data = element.data(NG_ANIMATE_STATE) || {}; + if (setter) { + data.running = true; + data.structural = true; + element.data(NG_ANIMATE_STATE, data); + } + return data.disabled || (data.running && data.structural); + } + + function runAnimationPostDigest(fn) { + var cancelFn, defer = $$q.defer(); + defer.promise.$$cancelFn = function () { + cancelFn && cancelFn(); + }; + $rootScope.$$postDigest(function () { + cancelFn = fn(function () { + defer.resolve(); + }); + }); + return defer.promise; + } + + function parseAnimateOptions(options) { + // some plugin code may still be passing in the callback + // function as the last param for the $animate methods so + // it's best to only allow string or array values for now + if (isObject(options)) { + if (options.tempClasses && isString(options.tempClasses)) { + options.tempClasses = options.tempClasses.split(/\s+/); + } + return options; + } + } + + function resolveElementClasses(element, cache, runningAnimations) { + runningAnimations = runningAnimations || {}; + + var lookup = {}; + forEach(runningAnimations, function (data, selector) { + forEach(selector.split(' '), function (s) { + lookup[s] = data; + }); + }); + + var hasClasses = Object.create(null); + forEach((element.attr('class') || '').split(/\s+/), function (className) { + hasClasses[className] = true; + }); + + var toAdd = [], toRemove = []; + forEach(cache.classes, function (status, className) { + var hasClass = hasClasses[className]; + var matchingAnimation = lookup[className] || {}; + + // When addClass and removeClass is called then $animate will check to + // see if addClass and removeClass cancel each other out. When there are + // more calls to removeClass than addClass then the count falls below 0 + // and then the removeClass animation will be allowed. Otherwise if the + // count is above 0 then that means an addClass animation will commence. + // Once an animation is allowed then the code will also check to see if + // there exists any on-going animation that is already adding or remvoing + // the matching CSS class. + if (status === false) { + //does it have the class or will it have the class + if (hasClass || matchingAnimation.event == 'addClass') { + toRemove.push(className); + } + } else if (status === true) { + //is the class missing or will it be removed? + if (!hasClass || matchingAnimation.event == 'removeClass') { + toAdd.push(className); + } + } + }); + + return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')]; + } + + function lookup(name) { + if (name) { + var matches = [], + flagMap = {}, + classes = name.substr(1).split('.'); + + //the empty string value is the default animation + //operation which performs CSS transition and keyframe + //animations sniffing. This is always included for each + //element animation procedure if the browser supports + //transitions and/or keyframe animations. The default + //animation is added to the top of the list to prevent + //any previous animations from affecting the element styling + //prior to the element being animated. + if ($sniffer.transitions || $sniffer.animations) { + matches.push($injector.get(selectors[''])); + } + + for (var i = 0; i < classes.length; i++) { + var klass = classes[i], + selectorFactoryName = selectors[klass]; + if (selectorFactoryName && !flagMap[klass]) { + matches.push($injector.get(selectorFactoryName)); + flagMap[klass] = true; + } + } + return matches; + } + } + + function animationRunner(element, animationEvent, className, options) { + //transcluded directives may sometimes fire an animation using only comment nodes + //best to catch this early on to prevent any animation operations from occurring + var node = element[0]; + if (!node) { + return; + } + + if (options) { + options.to = options.to || {}; + options.from = options.from || {}; + } + + var classNameAdd; + var classNameRemove; + if (isArray(className)) { + classNameAdd = className[0]; + classNameRemove = className[1]; + if (!classNameAdd) { + className = classNameRemove; + animationEvent = 'removeClass'; + } else if (!classNameRemove) { + className = classNameAdd; + animationEvent = 'addClass'; + } else { + className = classNameAdd + ' ' + classNameRemove; + } + } + + var isSetClassOperation = animationEvent == 'setClass'; + var isClassBased = isSetClassOperation + || animationEvent == 'addClass' + || animationEvent == 'removeClass' + || animationEvent == 'animate'; + + var currentClassName = element.attr('class'); + var classes = currentClassName + ' ' + className; + if (!isAnimatableClassName(classes)) { + return; + } + + var beforeComplete = noop, + beforeCancel = [], + before = [], + afterComplete = noop, + afterCancel = [], + after = []; + + var animationLookup = (' ' + classes).replace(/\s+/g, '.'); + forEach(lookup(animationLookup), function (animationFactory) { + var created = registerAnimation(animationFactory, animationEvent); + if (!created && isSetClassOperation) { + registerAnimation(animationFactory, 'addClass'); + registerAnimation(animationFactory, 'removeClass'); + } + }); + + function registerAnimation(animationFactory, event) { + var afterFn = animationFactory[event]; + var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; + if (afterFn || beforeFn) { + if (event == 'leave') { + beforeFn = afterFn; + //when set as null then animation knows to skip this phase + afterFn = null; + } + after.push({ + event: event, fn: afterFn + }); + before.push({ + event: event, fn: beforeFn + }); + return true; + } + } + + function run(fns, cancellations, allCompleteFn) { + var animations = []; + forEach(fns, function (animation) { + animation.fn && animations.push(animation); + }); + + var count = 0; + + function afterAnimationComplete(index) { + if (cancellations) { + (cancellations[index] || noop)(); + if (++count < animations.length) return; + cancellations = null; + } + allCompleteFn(); + } + + //The code below adds directly to the array in order to work with + //both sync and async animations. Sync animations are when the done() + //operation is called right away. DO NOT REFACTOR! + forEach(animations, function (animation, index) { + var progress = function () { + afterAnimationComplete(index); + }; + switch (animation.event) { + case 'setClass': + cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options)); + break; + case 'animate': + cancellations.push(animation.fn(element, className, options.from, options.to, progress)); + break; + case 'addClass': + cancellations.push(animation.fn(element, classNameAdd || className, progress, options)); + break; + case 'removeClass': + cancellations.push(animation.fn(element, classNameRemove || className, progress, options)); + break; + default: + cancellations.push(animation.fn(element, progress, options)); + break; + } + }); + + if (cancellations && cancellations.length === 0) { + allCompleteFn(); + } + } + + return { + node: node, + event: animationEvent, + className: className, + isClassBased: isClassBased, + isSetClassOperation: isSetClassOperation, + applyStyles: function () { + if (options) { + element.css(angular.extend(options.from || {}, options.to || {})); + } + }, + before: function (allCompleteFn) { + beforeComplete = allCompleteFn; + run(before, beforeCancel, function () { + beforeComplete = noop; + allCompleteFn(); + }); + }, + after: function (allCompleteFn) { + afterComplete = allCompleteFn; + run(after, afterCancel, function () { + afterComplete = noop; + allCompleteFn(); + }); + }, + cancel: function () { + if (beforeCancel) { + forEach(beforeCancel, function (cancelFn) { + (cancelFn || noop)(true); + }); + beforeComplete(true); + } + if (afterCancel) { + forEach(afterCancel, function (cancelFn) { + (cancelFn || noop)(true); + }); + afterComplete(true); + } + } + }; + } + + /** + * @ngdoc service + * @name $animate + * @kind object + * + * @description + * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. + * When any of these operations are run, the $animate service + * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) + * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. + * + * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives + * will work out of the box without any extra configuration. + * + * Requires the {@link ngAnimate `ngAnimate`} module to be installed. + * + * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. + * ## Callback Promises + * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The + * promise itself is then resolved once the animation has completed itself, has been cancelled or has been + * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still + * call the resolve function of the animation.) + * + * ```js + * $animate.enter(element, container).then(function() { * //...this is called once the animation is complete... * }); - * ``` - * - * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope, - * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using - * `$scope.$apply(...)`; - * - * ```js - * $animate.leave(element).then(function() { + * ``` + * + * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope, + * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using + * `$scope.$apply(...)`; + * + * ```js + * $animate.leave(element).then(function() { * $scope.$apply(function() { * $location.path('/new-page'); * }); * }); - * ``` - * - * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided - * promise that was returned when the animation was started. - * - * ```js - * var promise = $animate.addClass(element, 'super-long-animation').then(function() { + * ``` + * + * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided + * promise that was returned when the animation was started. + * + * ```js + * var promise = $animate.addClass(element, 'super-long-animation').then(function() { * //this will still be called even if cancelled * }); - * - * element.on('click', function() { + * + * element.on('click', function() { * //tooo lazy to wait for the animation to end * $animate.cancel(promise); * }); - * ``` - * - * (Keep in mind that the promise cancellation is unique to `$animate` since promises in - * general cannot be cancelled.) - * - */ - return { - /** - * @ngdoc method - * @name $animate#animate - * @kind function - * - * @description - * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element. - * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation - * will take on the provided styles. For example, if a transition animation is set for the given className then the - * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is - * detected then the provided styles will be given in as function paramters. - * - * ```js - * ngModule.animation('.my-inline-animation', function() { + * ``` + * + * (Keep in mind that the promise cancellation is unique to `$animate` since promises in + * general cannot be cancelled.) + * + */ + return { + /** + * @ngdoc method + * @name $animate#animate + * @kind function + * + * @description + * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element. + * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation + * will take on the provided styles. For example, if a transition animation is set for the given className then the + * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is + * detected then the provided styles will be given in as function paramters. + * + * ```js + * ngModule.animation('.my-inline-animation', function() { * return { * animate : function(element, className, from, to, done) { * //styles * } * } * }); - * ``` - * - * Below is a breakdown of each step that occurs during the `animate` animation: - * - * | Animation Step | What the element class attribute looks like | - * |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| - * | 1. $animate.animate(...) is called | class="my-animation" | - * | 2. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | - * | 3. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | - * | 4. the className class value is added to the element | class="my-animation ng-animate className" | - * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate className" | - * | 6. $animate blocks all CSS transitions on the element to ensure the .className class styling is applied right away| class="my-animation ng-animate className" | - * | 7. $animate applies the provided collection of `from` CSS styles to the element | class="my-animation ng-animate className" | - * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate className" | - * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate className" | - * | 10. the className-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate className className-active" | - * | 11. $animate applies the collection of `to` CSS styles to the element which are then handled by the transition | class="my-animation ng-animate className className-active" | - * | 12. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate className className-active" | - * | 13. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 14. The returned promise is resolved. | class="my-animation" | - * - * @param {DOMElement} element the element that will be the focus of the enter animation - * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation - * @param {object} to a collection of CSS styles that the element will animate towards - * @param {string=} className an optional CSS class that will be added to the element for the duration of the animation (the default class is `ng-inline-animate`) - * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - animate : function(element, from, to, className, options) { - className = className || 'ng-inline-animate'; - options = parseAnimateOptions(options) || {}; - options.from = to ? from : null; - options.to = to ? to : from; - - return runAnimationPostDigest(function(done) { - return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done); - }); - }, - - /** - * @ngdoc method - * @name $animate#enter - * @kind function - * - * @description - * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once - * the animation is started, the following CSS classes will be present on the element for the duration of the animation: - * - * Below is a breakdown of each step that occurs during enter animation: - * - * | Animation Step | What the element class attribute looks like | - * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| - * | 1. $animate.enter(...) is called | class="my-animation" | - * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | - * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | - * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | - * | 5. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | - * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | - * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-enter class styling is applied right away | class="my-animation ng-animate ng-enter" | - * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter" | - * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter" | - * | 10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active" | - * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active" | - * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 13. The returned promise is resolved. | class="my-animation" | - * - * @param {DOMElement} element the element that will be the focus of the enter animation - * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation - * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation - * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - enter : function(element, parentElement, afterElement, options) { - options = parseAnimateOptions(options); - element = angular.element(element); - parentElement = prepareElement(parentElement); - afterElement = prepareElement(afterElement); - - classBasedAnimationsBlocked(element, true); - $delegate.enter(element, parentElement, afterElement); - return runAnimationPostDigest(function(done) { - return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done); - }); - }, - - /** - * @ngdoc method - * @name $animate#leave - * @kind function - * - * @description - * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once - * the animation is started, the following CSS classes will be added for the duration of the animation: - * - * Below is a breakdown of each step that occurs during leave animation: - * - * | Animation Step | What the element class attribute looks like | - * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| - * | 1. $animate.leave(...) is called | class="my-animation" | - * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | - * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | - * | 4. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | - * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | - * | 6. $animate blocks all CSS transitions on the element to ensure the .ng-leave class styling is applied right away | class="my-animation ng-animate ng-leave†| - * | 7. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-leave" | - * | 8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave†| - * | 9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active" | - * | 10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active" | - * | 11. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 12. The element is removed from the DOM | ... | - * | 13. The returned promise is resolved. | ... | - * - * @param {DOMElement} element the element that will be the focus of the leave animation - * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - leave : function(element, options) { - options = parseAnimateOptions(options); - element = angular.element(element); - - cancelChildAnimations(element); - classBasedAnimationsBlocked(element, true); - return runAnimationPostDigest(function(done) { - return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() { - $delegate.leave(element); - }, options, done); - }); - }, - - /** - * @ngdoc method - * @name $animate#move - * @kind function - * - * @description - * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or - * add the element directly after the afterElement element if present. Then the move animation will be run. Once - * the animation is started, the following CSS classes will be added for the duration of the animation: - * - * Below is a breakdown of each step that occurs during move animation: - * - * | Animation Step | What the element class attribute looks like | - * |------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------| - * | 1. $animate.move(...) is called | class="my-animation" | - * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | - * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | - * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | - * | 5. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | - * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | - * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-move class styling is applied right away | class="my-animation ng-animate ng-move†| - * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move" | - * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move†| - * | 10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active" | - * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active" | - * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 13. The returned promise is resolved. | class="my-animation" | - * - * @param {DOMElement} element the element that will be the focus of the move animation - * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation - * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation - * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - move : function(element, parentElement, afterElement, options) { - options = parseAnimateOptions(options); - element = angular.element(element); - parentElement = prepareElement(parentElement); - afterElement = prepareElement(afterElement); - - cancelChildAnimations(element); - classBasedAnimationsBlocked(element, true); - $delegate.move(element, parentElement, afterElement); - return runAnimationPostDigest(function(done) { - return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done); - }); - }, - - /** - * @ngdoc method - * @name $animate#addClass - * - * @description - * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. - * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide - * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions - * or keyframes are defined on the -add-active or base CSS class). - * - * Below is a breakdown of each step that occurs during addClass animation: - * - * | Animation Step | What the element class attribute looks like | - * |----------------------------------------------------------------------------------------------------|------------------------------------------------------------------| - * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | - * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | - * | 3. the .super-add class is added to the element | class="my-animation ng-animate super-add" | - * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate super-add" | - * | 5. the .super and .super-add-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate super super-add super-add-active" | - * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | - * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation super super-add super-add-active" | - * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | - * | 9. The super class is kept on the element | class="my-animation super" | - * | 10. The returned promise is resolved. | class="my-animation super" | - * - * @param {DOMElement} element the element that will be animated - * @param {string} className the CSS class that will be added to the element and then animated - * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - addClass : function(element, className, options) { - return this.setClass(element, className, [], options); - }, - - /** - * @ngdoc method - * @name $animate#removeClass - * - * @description - * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value - * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in - * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if - * no CSS transitions or keyframes are defined on the -remove or base CSS classes). - * - * Below is a breakdown of each step that occurs during removeClass animation: - * - * | Animation Step | What the element class attribute looks like | - * |------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------| - * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | - * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate" | - * | 3. the .super-remove class is added to the element | class="my-animation super ng-animate super-remove" | - * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove" | - * | 5. the .super-remove-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate super-remove super-remove-active" | - * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | - * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active" | - * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | - * | 9. The returned promise is resolved. | class="my-animation" | - * - * - * @param {DOMElement} element the element that will be animated - * @param {string} className the CSS class that will be animated and then removed from the element - * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - removeClass : function(element, className, options) { - return this.setClass(element, [], className, options); - }, - - /** - * - * @ngdoc method - * @name $animate#setClass - * - * @description Adds and/or removes the given CSS classes to and from the element. - * Once complete, the done() callback will be fired (if provided). - * - * | Animation Step | What the element class attribute looks like | - * |--------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------| - * | 1. $animate.removeClass(element, ‘on’, ‘off’) is called | class="my-animation super off†| - * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate off†| - * | 3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off†| - * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off†| - * | 5. the .on, .on-add-active and .off-remove-active classes are added and .off is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active†| - * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" | - * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" | - * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation on" | - * | 9. The returned promise is resolved. | class="my-animation on" | - * - * @param {DOMElement} element the element which will have its CSS classes changed - * removed from it - * @param {string} add the CSS classes which will be added to the element - * @param {string} remove the CSS class which will be removed from the element - * CSS classes have been set on the element - * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation - * @return {Promise} the animation callback promise - */ - setClass : function(element, add, remove, options) { - options = parseAnimateOptions(options); - - var STORAGE_KEY = '$$animateClasses'; - element = angular.element(element); - element = stripCommentsFromElement(element); - - if (classBasedAnimationsBlocked(element)) { - return $delegate.$$setClassImmediately(element, add, remove, options); - } - - // we're using a combined array for both the add and remove - // operations since the ORDER OF addClass and removeClass matters - var classes, cache = element.data(STORAGE_KEY); - var hasCache = !!cache; - if (!cache) { - cache = {}; - cache.classes = {}; - } - classes = cache.classes; - - add = isArray(add) ? add : add.split(' '); - forEach(add, function(c) { - if (c && c.length) { - classes[c] = true; - } - }); - - remove = isArray(remove) ? remove : remove.split(' '); - forEach(remove, function(c) { - if (c && c.length) { - classes[c] = false; - } - }); - - if (hasCache) { - if (options && cache.options) { - cache.options = angular.extend(cache.options || {}, options); - } - - //the digest cycle will combine all the animations into one function - return cache.promise; - } else { - element.data(STORAGE_KEY, cache = { - classes : classes, - options : options - }); - } - - return cache.promise = runAnimationPostDigest(function(done) { - var parentElement = element.parent(); - var elementNode = extractElementNode(element); - var parentNode = elementNode.parentNode; - // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed - if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) { - done(); - return; - } - - var cache = element.data(STORAGE_KEY); - element.removeData(STORAGE_KEY); - - var state = element.data(NG_ANIMATE_STATE) || {}; - var classes = resolveElementClasses(element, cache, state.active); - return !classes - ? done() - : performAnimation('setClass', classes, element, parentElement, null, function() { - if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]); - if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]); - }, cache.options, done); - }); - }, - - /** - * @ngdoc method - * @name $animate#cancel - * @kind function - * - * @param {Promise} animationPromise The animation promise that is returned when an animation is started. - * - * @description - * Cancels the provided animation. - */ - cancel : function(promise) { - promise.$$cancelFn(); - }, - - /** - * @ngdoc method - * @name $animate#enabled - * @kind function - * - * @param {boolean=} value If provided then set the animation on or off. - * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation - * @return {boolean} Current animation state. - * - * @description - * Globally enables/disables animations. - * - */ - enabled : function(value, element) { - switch(arguments.length) { - case 2: - if (value) { - cleanup(element); - } else { - var data = element.data(NG_ANIMATE_STATE) || {}; - data.disabled = true; - element.data(NG_ANIMATE_STATE, data); - } - break; - - case 1: - rootAnimateState.disabled = !value; - break; - - default: - value = !rootAnimateState.disabled; - break; - } - return !!value; - } - }; - - /* - all animations call this shared animation triggering function internally. - The animationEvent variable refers to the JavaScript animation event that will be triggered - and the className value is the name of the animation that will be applied within the - CSS code. Element, parentElement and afterElement are provided DOM elements for the animation - and the onComplete callback will be fired once the animation is fully complete. - */ - function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) { - var noopCancel = noop; - var runner = animationRunner(element, animationEvent, className, options); - if (!runner) { - fireDOMOperation(); - fireBeforeCallbackAsync(); - fireAfterCallbackAsync(); - closeAnimation(); - return noopCancel; - } - - animationEvent = runner.event; - className = runner.className; - var elementEvents = angular.element._data(runner.node); - elementEvents = elementEvents && elementEvents.events; - - if (!parentElement) { - parentElement = afterElement ? afterElement.parent() : element.parent(); - } - - //skip the animation if animations are disabled, a parent is already being animated, - //the element is not currently attached to the document body or then completely close - //the animation if any matching animations are not found at all. - //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. - if (animationsDisabled(element, parentElement)) { - fireDOMOperation(); - fireBeforeCallbackAsync(); - fireAfterCallbackAsync(); - closeAnimation(); - return noopCancel; - } - - var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; - var runningAnimations = ngAnimateState.active || {}; - var totalActiveAnimations = ngAnimateState.totalActive || 0; - var lastAnimation = ngAnimateState.last; - var skipAnimation = false; - - if (totalActiveAnimations > 0) { - var animationsToCancel = []; - if (!runner.isClassBased) { - if (animationEvent == 'leave' && runningAnimations['ng-leave']) { - skipAnimation = true; - } else { - //cancel all animations when a structural animation takes place - for(var klass in runningAnimations) { - animationsToCancel.push(runningAnimations[klass]); - } - ngAnimateState = {}; - cleanup(element, true); - } - } else if (lastAnimation.event == 'setClass') { - animationsToCancel.push(lastAnimation); - cleanup(element, className); - } - else if (runningAnimations[className]) { - var current = runningAnimations[className]; - if (current.event == animationEvent) { - skipAnimation = true; - } else { - animationsToCancel.push(current); - cleanup(element, className); - } - } - - if (animationsToCancel.length > 0) { - forEach(animationsToCancel, function(operation) { - operation.cancel(); - }); - } - } - - if (runner.isClassBased - && !runner.isSetClassOperation - && animationEvent != 'animate' - && !skipAnimation) { - skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR - } - - if (skipAnimation) { - fireDOMOperation(); - fireBeforeCallbackAsync(); - fireAfterCallbackAsync(); - fireDoneCallbackAsync(); - return noopCancel; - } - - runningAnimations = ngAnimateState.active || {}; - totalActiveAnimations = ngAnimateState.totalActive || 0; - - if (animationEvent == 'leave') { - //there's no need to ever remove the listener since the element - //will be removed (destroyed) after the leave animation ends or - //is cancelled midway - element.one('$destroy', function(e) { - var element = angular.element(this); - var state = element.data(NG_ANIMATE_STATE); - if (state) { - var activeLeaveAnimation = state.active['ng-leave']; - if (activeLeaveAnimation) { - activeLeaveAnimation.cancel(); - cleanup(element, 'ng-leave'); - } - } - }); - } - - //the ng-animate class does nothing, but it's here to allow for - //parent animations to find and cancel child animations when needed - element.addClass(NG_ANIMATE_CLASS_NAME); - if (options && options.tempClasses) { - forEach(options.tempClasses, function(className) { - element.addClass(className); - }); - } - - var localAnimationCount = globalAnimationCounter++; - totalActiveAnimations++; - runningAnimations[className] = runner; - - element.data(NG_ANIMATE_STATE, { - last : runner, - active : runningAnimations, - index : localAnimationCount, - totalActive : totalActiveAnimations - }); - - //first we run the before animations and when all of those are complete - //then we perform the DOM operation and run the next set of animations - fireBeforeCallbackAsync(); - runner.before(function(cancelled) { - var data = element.data(NG_ANIMATE_STATE); - cancelled = cancelled || - !data || !data.active[className] || - (runner.isClassBased && data.active[className].event != animationEvent); - - fireDOMOperation(); - if (cancelled === true) { - closeAnimation(); - } else { - fireAfterCallbackAsync(); - runner.after(closeAnimation); - } - }); - - return runner.cancel; - - function fireDOMCallback(animationPhase) { - var eventName = '$animate:' + animationPhase; - if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { - $$asyncCallback(function() { - element.triggerHandler(eventName, { - event : animationEvent, - className : className - }); - }); - } - } - - function fireBeforeCallbackAsync() { - fireDOMCallback('before'); - } - - function fireAfterCallbackAsync() { - fireDOMCallback('after'); - } - - function fireDoneCallbackAsync() { - fireDOMCallback('close'); - doneCallback(); - } - - //it is less complicated to use a flag than managing and canceling - //timeouts containing multiple callbacks. - function fireDOMOperation() { - if (!fireDOMOperation.hasBeenRun) { - fireDOMOperation.hasBeenRun = true; - domOperation(); - } - } - - function closeAnimation() { - if (!closeAnimation.hasBeenRun) { - if (runner) { //the runner doesn't exist if it fails to instantiate - runner.applyStyles(); - } - - closeAnimation.hasBeenRun = true; - if (options && options.tempClasses) { - forEach(options.tempClasses, function(className) { - element.removeClass(className); - }); - } - - var data = element.data(NG_ANIMATE_STATE); - if (data) { - - /* only structural animations wait for reflow before removing an - animation, but class-based animations don't. An example of this - failing would be when a parent HTML tag has a ng-class attribute - causing ALL directives below to skip animations during the digest */ - if (runner && runner.isClassBased) { - cleanup(element, className); - } else { - $$asyncCallback(function() { - var data = element.data(NG_ANIMATE_STATE) || {}; - if (localAnimationCount == data.index) { - cleanup(element, className, animationEvent); - } - }); - element.data(NG_ANIMATE_STATE, data); - } - } - fireDoneCallbackAsync(); - } - } - } - - function cancelChildAnimations(element) { - var node = extractElementNode(element); - if (node) { - var nodes = angular.isFunction(node.getElementsByClassName) ? - node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : - node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); - forEach(nodes, function(element) { - element = angular.element(element); - var data = element.data(NG_ANIMATE_STATE); - if (data && data.active) { - forEach(data.active, function(runner) { - runner.cancel(); - }); - } - }); - } - } - - function cleanup(element, className) { - if (isMatchingElement(element, $rootElement)) { - if (!rootAnimateState.disabled) { - rootAnimateState.running = false; - rootAnimateState.structural = false; - } - } else if (className) { - var data = element.data(NG_ANIMATE_STATE) || {}; - - var removeAnimations = className === true; - if (!removeAnimations && data.active && data.active[className]) { - data.totalActive--; - delete data.active[className]; - } - - if (removeAnimations || !data.totalActive) { - element.removeClass(NG_ANIMATE_CLASS_NAME); - element.removeData(NG_ANIMATE_STATE); - } - } - } - - function animationsDisabled(element, parentElement) { - if (rootAnimateState.disabled) { - return true; - } - - if (isMatchingElement(element, $rootElement)) { - return rootAnimateState.running; - } - - var allowChildAnimations, parentRunningAnimation, hasParent; - do { - //the element did not reach the root element which means that it - //is not apart of the DOM. Therefore there is no reason to do - //any animations on it - if (parentElement.length === 0) break; - - var isRoot = isMatchingElement(parentElement, $rootElement); - var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {}); - if (state.disabled) { - return true; - } - - //no matter what, for an animation to work it must reach the root element - //this implies that the element is attached to the DOM when the animation is run - if (isRoot) { - hasParent = true; - } - - //once a flag is found that is strictly false then everything before - //it will be discarded and all child animations will be restricted - if (allowChildAnimations !== false) { - var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN); - if (angular.isDefined(animateChildrenFlag)) { - allowChildAnimations = animateChildrenFlag; - } - } - - parentRunningAnimation = parentRunningAnimation || - state.running || - (state.last && !state.last.isClassBased); - } - while(parentElement = parentElement.parent()); - - return !hasParent || (!allowChildAnimations && parentRunningAnimation); - } - }]); - - $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', - function($window, $sniffer, $timeout, $$animateReflow) { - // Detect proper transitionend/animationend event names. - var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; - - // If unprefixed events are not supported but webkit-prefixed are, use the latter. - // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. - // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` - // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. - // Register both events in case `window.onanimationend` is not supported because of that, - // do the same for `transitionend` as Safari is likely to exhibit similar behavior. - // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit - // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition - if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { - CSS_PREFIX = '-webkit-'; - TRANSITION_PROP = 'WebkitTransition'; - TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; - } else { - TRANSITION_PROP = 'transition'; - TRANSITIONEND_EVENT = 'transitionend'; - } - - if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { - CSS_PREFIX = '-webkit-'; - ANIMATION_PROP = 'WebkitAnimation'; - ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; - } else { - ANIMATION_PROP = 'animation'; - ANIMATIONEND_EVENT = 'animationend'; - } - - var DURATION_KEY = 'Duration'; - var PROPERTY_KEY = 'Property'; - var DELAY_KEY = 'Delay'; - var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; - var ANIMATION_PLAYSTATE_KEY = 'PlayState'; - var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; - var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; - var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; - var CLOSING_TIME_BUFFER = 1.5; - var ONE_SECOND = 1000; - - var lookupCache = {}; - var parentCounter = 0; - var animationReflowQueue = []; - var cancelAnimationReflow; - function clearCacheAfterReflow() { - if (!cancelAnimationReflow) { - cancelAnimationReflow = $$animateReflow(function() { - animationReflowQueue = []; - cancelAnimationReflow = null; - lookupCache = {}; - }); - } - } - - function afterReflow(element, callback) { - if (cancelAnimationReflow) { - cancelAnimationReflow(); - } - animationReflowQueue.push(callback); - cancelAnimationReflow = $$animateReflow(function() { - forEach(animationReflowQueue, function(fn) { - fn(); - }); - - animationReflowQueue = []; - cancelAnimationReflow = null; - lookupCache = {}; - }); - } - - var closingTimer = null; - var closingTimestamp = 0; - var animationElementQueue = []; - function animationCloseHandler(element, totalTime) { - var node = extractElementNode(element); - element = angular.element(node); - - //this item will be garbage collected by the closing - //animation timeout - animationElementQueue.push(element); - - //but it may not need to cancel out the existing timeout - //if the timestamp is less than the previous one - var futureTimestamp = Date.now() + totalTime; - if (futureTimestamp <= closingTimestamp) { - return; - } - - $timeout.cancel(closingTimer); - - closingTimestamp = futureTimestamp; - closingTimer = $timeout(function() { - closeAllAnimations(animationElementQueue); - animationElementQueue = []; - }, totalTime, false); - } - - function closeAllAnimations(elements) { - forEach(elements, function(element) { - var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); - if (elementData) { - forEach(elementData.closeAnimationFns, function(fn) { - fn(); - }); - } - }); - } - - function getElementAnimationDetails(element, cacheKey) { - var data = cacheKey ? lookupCache[cacheKey] : null; - if (!data) { - var transitionDuration = 0; - var transitionDelay = 0; - var animationDuration = 0; - var animationDelay = 0; - - //we want all the styles defined before and after - forEach(element, function(element) { - if (element.nodeType == ELEMENT_NODE) { - var elementStyles = $window.getComputedStyle(element) || {}; - - var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; - transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); - - var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; - transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); - - var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; - animationDelay = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay); - - var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); - - if (aDuration > 0) { - aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; - } - animationDuration = Math.max(aDuration, animationDuration); - } - }); - data = { - total : 0, - transitionDelay: transitionDelay, - transitionDuration: transitionDuration, - animationDelay: animationDelay, - animationDuration: animationDuration - }; - if (cacheKey) { - lookupCache[cacheKey] = data; - } - } - return data; - } - - function parseMaxTime(str) { - var maxValue = 0; - var values = isString(str) ? - str.split(/\s*,\s*/) : - []; - forEach(values, function(value) { - maxValue = Math.max(parseFloat(value) || 0, maxValue); - }); - return maxValue; - } - - function getCacheKey(element) { - var parentElement = element.parent(); - var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); - if (!parentID) { - parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); - parentID = parentCounter; - } - return parentID + '-' + extractElementNode(element).getAttribute('class'); - } - - function animateSetup(animationEvent, element, className, styles) { - var structural = ['ng-enter','ng-leave','ng-move'].indexOf(className) >= 0; - - var cacheKey = getCacheKey(element); - var eventCacheKey = cacheKey + ' ' + className; - var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; - - var stagger = {}; - if (itemIndex > 0) { - var staggerClassName = className + '-stagger'; - var staggerCacheKey = cacheKey + ' ' + staggerClassName; - var applyClasses = !lookupCache[staggerCacheKey]; - - applyClasses && element.addClass(staggerClassName); - - stagger = getElementAnimationDetails(element, staggerCacheKey); - - applyClasses && element.removeClass(staggerClassName); - } - - element.addClass(className); - - var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; - var timings = getElementAnimationDetails(element, eventCacheKey); - var transitionDuration = timings.transitionDuration; - var animationDuration = timings.animationDuration; - - if (structural && transitionDuration === 0 && animationDuration === 0) { - element.removeClass(className); - return false; - } - - var blockTransition = styles || (structural && transitionDuration > 0); - var blockAnimation = animationDuration > 0 && - stagger.animationDelay > 0 && - stagger.animationDuration === 0; - - var closeAnimationFns = formerData.closeAnimationFns || []; - element.data(NG_ANIMATE_CSS_DATA_KEY, { - stagger : stagger, - cacheKey : eventCacheKey, - running : formerData.running || 0, - itemIndex : itemIndex, - blockTransition : blockTransition, - closeAnimationFns : closeAnimationFns - }); - - var node = extractElementNode(element); - - if (blockTransition) { - blockTransitions(node, true); - if (styles) { - element.css(styles); - } - } - - if (blockAnimation) { - blockAnimations(node, true); - } - - return true; - } - - function animateRun(animationEvent, element, className, activeAnimationComplete, styles) { - var node = extractElementNode(element); - var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); - if (node.getAttribute('class').indexOf(className) == -1 || !elementData) { - activeAnimationComplete(); - return; - } - - var activeClassName = ''; - var pendingClassName = ''; - forEach(className.split(' '), function(klass, i) { - var prefix = (i > 0 ? ' ' : '') + klass; - activeClassName += prefix + '-active'; - pendingClassName += prefix + '-pending'; - }); - - var style = ''; - var appliedStyles = []; - var itemIndex = elementData.itemIndex; - var stagger = elementData.stagger; - var staggerTime = 0; - if (itemIndex > 0) { - var transitionStaggerDelay = 0; - if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { - transitionStaggerDelay = stagger.transitionDelay * itemIndex; - } - - var animationStaggerDelay = 0; - if (stagger.animationDelay > 0 && stagger.animationDuration === 0) { - animationStaggerDelay = stagger.animationDelay * itemIndex; - appliedStyles.push(CSS_PREFIX + 'animation-play-state'); - } - - staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100; - } - - if (!staggerTime) { - element.addClass(activeClassName); - if (elementData.blockTransition) { - blockTransitions(node, false); - } - } - - var eventCacheKey = elementData.cacheKey + ' ' + activeClassName; - var timings = getElementAnimationDetails(element, eventCacheKey); - var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); - if (maxDuration === 0) { - element.removeClass(activeClassName); - animateClose(element, className); - activeAnimationComplete(); - return; - } - - if (!staggerTime && styles) { - if (!timings.transitionDuration) { - element.css('transition', timings.animationDuration + 's linear all'); - appliedStyles.push('transition'); - } - element.css(styles); - } - - var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); - var maxDelayTime = maxDelay * ONE_SECOND; - - if (appliedStyles.length > 0) { - //the element being animated may sometimes contain comment nodes in - //the jqLite object, so we're safe to use a single variable to house - //the styles since there is always only one element being animated - var oldStyle = node.getAttribute('style') || ''; - if (oldStyle.charAt(oldStyle.length-1) !== ';') { - oldStyle += ';'; - } - node.setAttribute('style', oldStyle + ' ' + style); - } - - var startTime = Date.now(); - var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; - var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; - var totalTime = (staggerTime + animationTime) * ONE_SECOND; - - var staggerTimeout; - if (staggerTime > 0) { - element.addClass(pendingClassName); - staggerTimeout = $timeout(function() { - staggerTimeout = null; - - if (timings.transitionDuration > 0) { - blockTransitions(node, false); - } - if (timings.animationDuration > 0) { - blockAnimations(node, false); - } - - element.addClass(activeClassName); - element.removeClass(pendingClassName); - - if (styles) { - if (timings.transitionDuration === 0) { - element.css('transition', timings.animationDuration + 's linear all'); - } - element.css(styles); - appliedStyles.push('transition'); - } - }, staggerTime * ONE_SECOND, false); - } - - element.on(css3AnimationEvents, onAnimationProgress); - elementData.closeAnimationFns.push(function() { - onEnd(); - activeAnimationComplete(); - }); - - elementData.running++; - animationCloseHandler(element, totalTime); - return onEnd; - - // This will automatically be called by $animate so - // there is no need to attach this internally to the - // timeout done method. - function onEnd() { - element.off(css3AnimationEvents, onAnimationProgress); - element.removeClass(activeClassName); - element.removeClass(pendingClassName); - if (staggerTimeout) { - $timeout.cancel(staggerTimeout); - } - animateClose(element, className); - var node = extractElementNode(element); - for (var i in appliedStyles) { - node.style.removeProperty(appliedStyles[i]); - } - } - - function onAnimationProgress(event) { - event.stopPropagation(); - var ev = event.originalEvent || event; - var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); - - /* Firefox (or possibly just Gecko) likes to not round values up - * when a ms measurement is used for the animation */ - var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); - - /* $manualTimeStamp is a mocked timeStamp value which is set - * within browserTrigger(). This is only here so that tests can - * mock animations properly. Real events fallback to event.timeStamp, - * or, if they don't, then a timeStamp is automatically created for them. - * We're checking to see if the timeStamp surpasses the expected delay, - * but we're using elapsedTime instead of the timeStamp on the 2nd - * pre-condition since animations sometimes close off early */ - if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { - activeAnimationComplete(); - } - } - } - - function blockTransitions(node, bool) { - node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : ''; - } - - function blockAnimations(node, bool) { - node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : ''; - } - - function animateBefore(animationEvent, element, className, styles) { - if (animateSetup(animationEvent, element, className, styles)) { - return function(cancelled) { - cancelled && animateClose(element, className); - }; - } - } - - function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) { - if (element.data(NG_ANIMATE_CSS_DATA_KEY)) { - return animateRun(animationEvent, element, className, afterAnimationComplete, styles); - } else { - animateClose(element, className); - afterAnimationComplete(); - } - } - - function animate(animationEvent, element, className, animationComplete, options) { - //If the animateSetup function doesn't bother returning a - //cancellation function then it means that there is no animation - //to perform at all - var preReflowCancellation = animateBefore(animationEvent, element, className, options.from); - if (!preReflowCancellation) { - clearCacheAfterReflow(); - animationComplete(); - return; - } - - //There are two cancellation functions: one is before the first - //reflow animation and the second is during the active state - //animation. The first function will take care of removing the - //data from the element which will not make the 2nd animation - //happen in the first place - var cancel = preReflowCancellation; - afterReflow(element, function() { - //once the reflow is complete then we point cancel to - //the new cancellation function which will remove all of the - //animation properties from the active animation - cancel = animateAfter(animationEvent, element, className, animationComplete, options.to); - }); - - return function(cancelled) { - (cancel || noop)(cancelled); - }; - } - - function animateClose(element, className) { - element.removeClass(className); - var data = element.data(NG_ANIMATE_CSS_DATA_KEY); - if (data) { - if (data.running) { - data.running--; - } - if (!data.running || data.running === 0) { - element.removeData(NG_ANIMATE_CSS_DATA_KEY); - } - } - } - - return { - animate : function(element, className, from, to, animationCompleted, options) { - options = options || {}; - options.from = from; - options.to = to; - return animate('animate', element, className, animationCompleted, options); - }, - - enter : function(element, animationCompleted, options) { - options = options || {}; - return animate('enter', element, 'ng-enter', animationCompleted, options); - }, - - leave : function(element, animationCompleted, options) { - options = options || {}; - return animate('leave', element, 'ng-leave', animationCompleted, options); - }, - - move : function(element, animationCompleted, options) { - options = options || {}; - return animate('move', element, 'ng-move', animationCompleted, options); - }, - - beforeSetClass : function(element, add, remove, animationCompleted, options) { - options = options || {}; - var className = suffixClasses(remove, '-remove') + ' ' + - suffixClasses(add, '-add'); - var cancellationMethod = animateBefore('setClass', element, className, options.from); - if (cancellationMethod) { - afterReflow(element, animationCompleted); - return cancellationMethod; - } - clearCacheAfterReflow(); - animationCompleted(); - }, - - beforeAddClass : function(element, className, animationCompleted, options) { - options = options || {}; - var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from); - if (cancellationMethod) { - afterReflow(element, animationCompleted); - return cancellationMethod; - } - clearCacheAfterReflow(); - animationCompleted(); - }, - - beforeRemoveClass : function(element, className, animationCompleted, options) { - options = options || {}; - var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from); - if (cancellationMethod) { - afterReflow(element, animationCompleted); - return cancellationMethod; - } - clearCacheAfterReflow(); - animationCompleted(); - }, - - setClass : function(element, add, remove, animationCompleted, options) { - options = options || {}; - remove = suffixClasses(remove, '-remove'); - add = suffixClasses(add, '-add'); - var className = remove + ' ' + add; - return animateAfter('setClass', element, className, animationCompleted, options.to); - }, - - addClass : function(element, className, animationCompleted, options) { - options = options || {}; - return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to); - }, - - removeClass : function(element, className, animationCompleted, options) { - options = options || {}; - return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to); - } - }; - - function suffixClasses(classes, suffix) { - var className = ''; - classes = isArray(classes) ? classes : classes.split(/\s+/); - forEach(classes, function(klass, i) { - if (klass && klass.length > 0) { - className += (i > 0 ? ' ' : '') + klass + suffix; - } - }); - return className; - } - }]); - }]); + * ``` + * + * Below is a breakdown of each step that occurs during the `animate` animation: + * + * | Animation Step | What the element class attribute looks like | + * |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------| + * | 1. $animate.animate(...) is called | class="my-animation" | + * | 2. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | + * | 3. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | + * | 4. the className class value is added to the element | class="my-animation ng-animate className" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate className" | + * | 6. $animate blocks all CSS transitions on the element to ensure the .className class styling is applied right away| class="my-animation ng-animate className" | + * | 7. $animate applies the provided collection of `from` CSS styles to the element | class="my-animation ng-animate className" | + * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate className" | + * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate className" | + * | 10. the className-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate className className-active" | + * | 11. $animate applies the collection of `to` CSS styles to the element which are then handled by the transition | class="my-animation ng-animate className className-active" | + * | 12. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate className className-active" | + * | 13. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 14. The returned promise is resolved. | class="my-animation" | + * + * @param {DOMElement} element the element that will be the focus of the enter animation + * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation + * @param {object} to a collection of CSS styles that the element will animate towards + * @param {string=} className an optional CSS class that will be added to the element for the duration of the animation (the default class is `ng-inline-animate`) + * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + animate: function (element, from, to, className, options) { + className = className || 'ng-inline-animate'; + options = parseAnimateOptions(options) || {}; + options.from = to ? from : null; + options.to = to ? to : from; + + return runAnimationPostDigest(function (done) { + return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done); + }); + }, + + /** + * @ngdoc method + * @name $animate#enter + * @kind function + * + * @description + * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once + * the animation is started, the following CSS classes will be present on the element for the duration of the animation: + * + * Below is a breakdown of each step that occurs during enter animation: + * + * | Animation Step | What the element class attribute looks like | + * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| + * | 1. $animate.enter(...) is called | class="my-animation" | + * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | + * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | + * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | + * | 5. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | + * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | + * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-enter class styling is applied right away | class="my-animation ng-animate ng-enter" | + * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter" | + * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter" | + * | 10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active" | + * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active" | + * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 13. The returned promise is resolved. | class="my-animation" | + * + * @param {DOMElement} element the element that will be the focus of the enter animation + * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation + * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation + * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + enter: function (element, parentElement, afterElement, options) { + options = parseAnimateOptions(options); + element = angular.element(element); + parentElement = prepareElement(parentElement); + afterElement = prepareElement(afterElement); + + classBasedAnimationsBlocked(element, true); + $delegate.enter(element, parentElement, afterElement); + return runAnimationPostDigest(function (done) { + return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done); + }); + }, + + /** + * @ngdoc method + * @name $animate#leave + * @kind function + * + * @description + * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during leave animation: + * + * | Animation Step | What the element class attribute looks like | + * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| + * | 1. $animate.leave(...) is called | class="my-animation" | + * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | + * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | + * | 4. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | + * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | + * | 6. $animate blocks all CSS transitions on the element to ensure the .ng-leave class styling is applied right away | class="my-animation ng-animate ng-leave†| + * | 7. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-leave" | + * | 8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave†| + * | 9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active" | + * | 10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active" | + * | 11. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 12. The element is removed from the DOM | ... | + * | 13. The returned promise is resolved. | ... | + * + * @param {DOMElement} element the element that will be the focus of the leave animation + * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + leave: function (element, options) { + options = parseAnimateOptions(options); + element = angular.element(element); + + cancelChildAnimations(element); + classBasedAnimationsBlocked(element, true); + return runAnimationPostDigest(function (done) { + return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function () { + $delegate.leave(element); + }, options, done); + }); + }, + + /** + * @ngdoc method + * @name $animate#move + * @kind function + * + * @description + * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or + * add the element directly after the afterElement element if present. Then the move animation will be run. Once + * the animation is started, the following CSS classes will be added for the duration of the animation: + * + * Below is a breakdown of each step that occurs during move animation: + * + * | Animation Step | What the element class attribute looks like | + * |------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------| + * | 1. $animate.move(...) is called | class="my-animation" | + * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | + * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" | + * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | + * | 5. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | + * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | + * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-move class styling is applied right away | class="my-animation ng-animate ng-move†| + * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move" | + * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move†| + * | 10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active" | + * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active" | + * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 13. The returned promise is resolved. | class="my-animation" | + * + * @param {DOMElement} element the element that will be the focus of the move animation + * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation + * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation + * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + move: function (element, parentElement, afterElement, options) { + options = parseAnimateOptions(options); + element = angular.element(element); + parentElement = prepareElement(parentElement); + afterElement = prepareElement(afterElement); + + cancelChildAnimations(element); + classBasedAnimationsBlocked(element, true); + $delegate.move(element, parentElement, afterElement); + return runAnimationPostDigest(function (done) { + return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done); + }); + }, + + /** + * @ngdoc method + * @name $animate#addClass + * + * @description + * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. + * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide + * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions + * or keyframes are defined on the -add-active or base CSS class). + * + * Below is a breakdown of each step that occurs during addClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |----------------------------------------------------------------------------------------------------|------------------------------------------------------------------| + * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | + * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" | + * | 3. the .super-add class is added to the element | class="my-animation ng-animate super-add" | + * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate super-add" | + * | 5. the .super and .super-add-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate super super-add super-add-active" | + * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | + * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation super super-add super-add-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | + * | 9. The super class is kept on the element | class="my-animation super" | + * | 10. The returned promise is resolved. | class="my-animation super" | + * + * @param {DOMElement} element the element that will be animated + * @param {string} className the CSS class that will be added to the element and then animated + * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + addClass: function (element, className, options) { + return this.setClass(element, className, [], options); + }, + + /** + * @ngdoc method + * @name $animate#removeClass + * + * @description + * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value + * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in + * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if + * no CSS transitions or keyframes are defined on the -remove or base CSS classes). + * + * Below is a breakdown of each step that occurs during removeClass animation: + * + * | Animation Step | What the element class attribute looks like | + * |------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------| + * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | + * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate" | + * | 3. the .super-remove class is added to the element | class="my-animation super ng-animate super-remove" | + * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove" | + * | 5. the .super-remove-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate super-remove super-remove-active" | + * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | + * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | + * | 9. The returned promise is resolved. | class="my-animation" | + * + * + * @param {DOMElement} element the element that will be animated + * @param {string} className the CSS class that will be animated and then removed from the element + * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + removeClass: function (element, className, options) { + return this.setClass(element, [], className, options); + }, + + /** + * + * @ngdoc method + * @name $animate#setClass + * + * @description Adds and/or removes the given CSS classes to and from the element. + * Once complete, the done() callback will be fired (if provided). + * + * | Animation Step | What the element class attribute looks like | + * |--------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------| + * | 1. $animate.removeClass(element, ‘on’, ‘off’) is called | class="my-animation super off†| + * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate off†| + * | 3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off†| + * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off†| + * | 5. the .on, .on-add-active and .off-remove-active classes are added and .off is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active†| + * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" | + * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" | + * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation on" | + * | 9. The returned promise is resolved. | class="my-animation on" | + * + * @param {DOMElement} element the element which will have its CSS classes changed + * removed from it + * @param {string} add the CSS classes which will be added to the element + * @param {string} remove the CSS class which will be removed from the element + * CSS classes have been set on the element + * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation + * @return {Promise} the animation callback promise + */ + setClass: function (element, add, remove, options) { + options = parseAnimateOptions(options); + + var STORAGE_KEY = '$$animateClasses'; + element = angular.element(element); + element = stripCommentsFromElement(element); + + if (classBasedAnimationsBlocked(element)) { + return $delegate.$$setClassImmediately(element, add, remove, options); + } + + // we're using a combined array for both the add and remove + // operations since the ORDER OF addClass and removeClass matters + var classes, cache = element.data(STORAGE_KEY); + var hasCache = !!cache; + if (!cache) { + cache = {}; + cache.classes = {}; + } + classes = cache.classes; + + add = isArray(add) ? add : add.split(' '); + forEach(add, function (c) { + if (c && c.length) { + classes[c] = true; + } + }); + + remove = isArray(remove) ? remove : remove.split(' '); + forEach(remove, function (c) { + if (c && c.length) { + classes[c] = false; + } + }); + + if (hasCache) { + if (options && cache.options) { + cache.options = angular.extend(cache.options || {}, options); + } + + //the digest cycle will combine all the animations into one function + return cache.promise; + } else { + element.data(STORAGE_KEY, cache = { + classes: classes, + options: options + }); + } + + return cache.promise = runAnimationPostDigest(function (done) { + var parentElement = element.parent(); + var elementNode = extractElementNode(element); + var parentNode = elementNode.parentNode; + // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed + if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) { + done(); + return; + } + + var cache = element.data(STORAGE_KEY); + element.removeData(STORAGE_KEY); + + var state = element.data(NG_ANIMATE_STATE) || {}; + var classes = resolveElementClasses(element, cache, state.active); + return !classes + ? done() + : performAnimation('setClass', classes, element, parentElement, null, function () { + if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]); + if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]); + }, cache.options, done); + }); + }, + + /** + * @ngdoc method + * @name $animate#cancel + * @kind function + * + * @param {Promise} animationPromise The animation promise that is returned when an animation is started. + * + * @description + * Cancels the provided animation. + */ + cancel: function (promise) { + promise.$$cancelFn(); + }, + + /** + * @ngdoc method + * @name $animate#enabled + * @kind function + * + * @param {boolean=} value If provided then set the animation on or off. + * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation + * @return {boolean} Current animation state. + * + * @description + * Globally enables/disables animations. + * + */ + enabled: function (value, element) { + switch (arguments.length) { + case 2: + if (value) { + cleanup(element); + } else { + var data = element.data(NG_ANIMATE_STATE) || {}; + data.disabled = true; + element.data(NG_ANIMATE_STATE, data); + } + break; + + case 1: + rootAnimateState.disabled = !value; + break; + + default: + value = !rootAnimateState.disabled; + break; + } + return !!value; + } + }; + + /* + all animations call this shared animation triggering function internally. + The animationEvent variable refers to the JavaScript animation event that will be triggered + and the className value is the name of the animation that will be applied within the + CSS code. Element, parentElement and afterElement are provided DOM elements for the animation + and the onComplete callback will be fired once the animation is fully complete. + */ + function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) { + var noopCancel = noop; + var runner = animationRunner(element, animationEvent, className, options); + if (!runner) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + closeAnimation(); + return noopCancel; + } + + animationEvent = runner.event; + className = runner.className; + var elementEvents = angular.element._data(runner.node); + elementEvents = elementEvents && elementEvents.events; + + if (!parentElement) { + parentElement = afterElement ? afterElement.parent() : element.parent(); + } + + //skip the animation if animations are disabled, a parent is already being animated, + //the element is not currently attached to the document body or then completely close + //the animation if any matching animations are not found at all. + //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. + if (animationsDisabled(element, parentElement)) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + closeAnimation(); + return noopCancel; + } + + var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; + var runningAnimations = ngAnimateState.active || {}; + var totalActiveAnimations = ngAnimateState.totalActive || 0; + var lastAnimation = ngAnimateState.last; + var skipAnimation = false; + + if (totalActiveAnimations > 0) { + var animationsToCancel = []; + if (!runner.isClassBased) { + if (animationEvent == 'leave' && runningAnimations['ng-leave']) { + skipAnimation = true; + } else { + //cancel all animations when a structural animation takes place + for (var klass in runningAnimations) { + animationsToCancel.push(runningAnimations[klass]); + } + ngAnimateState = {}; + cleanup(element, true); + } + } else if (lastAnimation.event == 'setClass') { + animationsToCancel.push(lastAnimation); + cleanup(element, className); + } + else if (runningAnimations[className]) { + var current = runningAnimations[className]; + if (current.event == animationEvent) { + skipAnimation = true; + } else { + animationsToCancel.push(current); + cleanup(element, className); + } + } + + if (animationsToCancel.length > 0) { + forEach(animationsToCancel, function (operation) { + operation.cancel(); + }); + } + } + + if (runner.isClassBased + && !runner.isSetClassOperation + && animationEvent != 'animate' + && !skipAnimation) { + skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR + } + + if (skipAnimation) { + fireDOMOperation(); + fireBeforeCallbackAsync(); + fireAfterCallbackAsync(); + fireDoneCallbackAsync(); + return noopCancel; + } + + runningAnimations = ngAnimateState.active || {}; + totalActiveAnimations = ngAnimateState.totalActive || 0; + + if (animationEvent == 'leave') { + //there's no need to ever remove the listener since the element + //will be removed (destroyed) after the leave animation ends or + //is cancelled midway + element.one('$destroy', function (e) { + var element = angular.element(this); + var state = element.data(NG_ANIMATE_STATE); + if (state) { + var activeLeaveAnimation = state.active['ng-leave']; + if (activeLeaveAnimation) { + activeLeaveAnimation.cancel(); + cleanup(element, 'ng-leave'); + } + } + }); + } + + //the ng-animate class does nothing, but it's here to allow for + //parent animations to find and cancel child animations when needed + element.addClass(NG_ANIMATE_CLASS_NAME); + if (options && options.tempClasses) { + forEach(options.tempClasses, function (className) { + element.addClass(className); + }); + } + + var localAnimationCount = globalAnimationCounter++; + totalActiveAnimations++; + runningAnimations[className] = runner; + + element.data(NG_ANIMATE_STATE, { + last: runner, + active: runningAnimations, + index: localAnimationCount, + totalActive: totalActiveAnimations + }); + + //first we run the before animations and when all of those are complete + //then we perform the DOM operation and run the next set of animations + fireBeforeCallbackAsync(); + runner.before(function (cancelled) { + var data = element.data(NG_ANIMATE_STATE); + cancelled = cancelled || !data || !data.active[className] || + (runner.isClassBased && data.active[className].event != animationEvent); + + fireDOMOperation(); + if (cancelled === true) { + closeAnimation(); + } else { + fireAfterCallbackAsync(); + runner.after(closeAnimation); + } + }); + + return runner.cancel; + + function fireDOMCallback(animationPhase) { + var eventName = '$animate:' + animationPhase; + if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { + $$asyncCallback(function () { + element.triggerHandler(eventName, { + event: animationEvent, + className: className + }); + }); + } + } + + function fireBeforeCallbackAsync() { + fireDOMCallback('before'); + } + + function fireAfterCallbackAsync() { + fireDOMCallback('after'); + } + + function fireDoneCallbackAsync() { + fireDOMCallback('close'); + doneCallback(); + } + + //it is less complicated to use a flag than managing and canceling + //timeouts containing multiple callbacks. + function fireDOMOperation() { + if (!fireDOMOperation.hasBeenRun) { + fireDOMOperation.hasBeenRun = true; + domOperation(); + } + } + + function closeAnimation() { + if (!closeAnimation.hasBeenRun) { + if (runner) { //the runner doesn't exist if it fails to instantiate + runner.applyStyles(); + } + + closeAnimation.hasBeenRun = true; + if (options && options.tempClasses) { + forEach(options.tempClasses, function (className) { + element.removeClass(className); + }); + } + + var data = element.data(NG_ANIMATE_STATE); + if (data) { + + /* only structural animations wait for reflow before removing an + animation, but class-based animations don't. An example of this + failing would be when a parent HTML tag has a ng-class attribute + causing ALL directives below to skip animations during the digest */ + if (runner && runner.isClassBased) { + cleanup(element, className); + } else { + $$asyncCallback(function () { + var data = element.data(NG_ANIMATE_STATE) || {}; + if (localAnimationCount == data.index) { + cleanup(element, className, animationEvent); + } + }); + element.data(NG_ANIMATE_STATE, data); + } + } + fireDoneCallbackAsync(); + } + } + } + + function cancelChildAnimations(element) { + var node = extractElementNode(element); + if (node) { + var nodes = angular.isFunction(node.getElementsByClassName) ? + node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : + node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); + forEach(nodes, function (element) { + element = angular.element(element); + var data = element.data(NG_ANIMATE_STATE); + if (data && data.active) { + forEach(data.active, function (runner) { + runner.cancel(); + }); + } + }); + } + } + + function cleanup(element, className) { + if (isMatchingElement(element, $rootElement)) { + if (!rootAnimateState.disabled) { + rootAnimateState.running = false; + rootAnimateState.structural = false; + } + } else if (className) { + var data = element.data(NG_ANIMATE_STATE) || {}; + + var removeAnimations = className === true; + if (!removeAnimations && data.active && data.active[className]) { + data.totalActive--; + delete data.active[className]; + } + + if (removeAnimations || !data.totalActive) { + element.removeClass(NG_ANIMATE_CLASS_NAME); + element.removeData(NG_ANIMATE_STATE); + } + } + } + + function animationsDisabled(element, parentElement) { + if (rootAnimateState.disabled) { + return true; + } + + if (isMatchingElement(element, $rootElement)) { + return rootAnimateState.running; + } + + var allowChildAnimations, parentRunningAnimation, hasParent; + do { + //the element did not reach the root element which means that it + //is not apart of the DOM. Therefore there is no reason to do + //any animations on it + if (parentElement.length === 0) break; + + var isRoot = isMatchingElement(parentElement, $rootElement); + var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {}); + if (state.disabled) { + return true; + } + + //no matter what, for an animation to work it must reach the root element + //this implies that the element is attached to the DOM when the animation is run + if (isRoot) { + hasParent = true; + } + + //once a flag is found that is strictly false then everything before + //it will be discarded and all child animations will be restricted + if (allowChildAnimations !== false) { + var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN); + if (angular.isDefined(animateChildrenFlag)) { + allowChildAnimations = animateChildrenFlag; + } + } + + parentRunningAnimation = parentRunningAnimation || + state.running || + (state.last && !state.last.isClassBased); + } + while (parentElement = parentElement.parent()); + + return !hasParent || (!allowChildAnimations && parentRunningAnimation); + } + }]); + + $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', + function ($window, $sniffer, $timeout, $$animateReflow) { + // Detect proper transitionend/animationend event names. + var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; + + // If unprefixed events are not supported but webkit-prefixed are, use the latter. + // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. + // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` + // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. + // Register both events in case `window.onanimationend` is not supported because of that, + // do the same for `transitionend` as Safari is likely to exhibit similar behavior. + // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit + // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition + if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { + CSS_PREFIX = '-webkit-'; + TRANSITION_PROP = 'WebkitTransition'; + TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; + } else { + TRANSITION_PROP = 'transition'; + TRANSITIONEND_EVENT = 'transitionend'; + } + + if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { + CSS_PREFIX = '-webkit-'; + ANIMATION_PROP = 'WebkitAnimation'; + ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; + } else { + ANIMATION_PROP = 'animation'; + ANIMATIONEND_EVENT = 'animationend'; + } + + var DURATION_KEY = 'Duration'; + var PROPERTY_KEY = 'Property'; + var DELAY_KEY = 'Delay'; + var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; + var ANIMATION_PLAYSTATE_KEY = 'PlayState'; + var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; + var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; + var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; + var CLOSING_TIME_BUFFER = 1.5; + var ONE_SECOND = 1000; + + var lookupCache = {}; + var parentCounter = 0; + var animationReflowQueue = []; + var cancelAnimationReflow; + + function clearCacheAfterReflow() { + if (!cancelAnimationReflow) { + cancelAnimationReflow = $$animateReflow(function () { + animationReflowQueue = []; + cancelAnimationReflow = null; + lookupCache = {}; + }); + } + } + + function afterReflow(element, callback) { + if (cancelAnimationReflow) { + cancelAnimationReflow(); + } + animationReflowQueue.push(callback); + cancelAnimationReflow = $$animateReflow(function () { + forEach(animationReflowQueue, function (fn) { + fn(); + }); + + animationReflowQueue = []; + cancelAnimationReflow = null; + lookupCache = {}; + }); + } + + var closingTimer = null; + var closingTimestamp = 0; + var animationElementQueue = []; + + function animationCloseHandler(element, totalTime) { + var node = extractElementNode(element); + element = angular.element(node); + + //this item will be garbage collected by the closing + //animation timeout + animationElementQueue.push(element); + + //but it may not need to cancel out the existing timeout + //if the timestamp is less than the previous one + var futureTimestamp = Date.now() + totalTime; + if (futureTimestamp <= closingTimestamp) { + return; + } + + $timeout.cancel(closingTimer); + + closingTimestamp = futureTimestamp; + closingTimer = $timeout(function () { + closeAllAnimations(animationElementQueue); + animationElementQueue = []; + }, totalTime, false); + } + + function closeAllAnimations(elements) { + forEach(elements, function (element) { + var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); + if (elementData) { + forEach(elementData.closeAnimationFns, function (fn) { + fn(); + }); + } + }); + } + + function getElementAnimationDetails(element, cacheKey) { + var data = cacheKey ? lookupCache[cacheKey] : null; + if (!data) { + var transitionDuration = 0; + var transitionDelay = 0; + var animationDuration = 0; + var animationDelay = 0; + + //we want all the styles defined before and after + forEach(element, function (element) { + if (element.nodeType == ELEMENT_NODE) { + var elementStyles = $window.getComputedStyle(element) || {}; + + var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; + transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); + + var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; + transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); + + var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; + animationDelay = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay); + + var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); + + if (aDuration > 0) { + aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; + } + animationDuration = Math.max(aDuration, animationDuration); + } + }); + data = { + total: 0, + transitionDelay: transitionDelay, + transitionDuration: transitionDuration, + animationDelay: animationDelay, + animationDuration: animationDuration + }; + if (cacheKey) { + lookupCache[cacheKey] = data; + } + } + return data; + } + + function parseMaxTime(str) { + var maxValue = 0; + var values = isString(str) ? + str.split(/\s*,\s*/) : + []; + forEach(values, function (value) { + maxValue = Math.max(parseFloat(value) || 0, maxValue); + }); + return maxValue; + } + + function getCacheKey(element) { + var parentElement = element.parent(); + var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); + if (!parentID) { + parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); + parentID = parentCounter; + } + return parentID + '-' + extractElementNode(element).getAttribute('class'); + } + + function animateSetup(animationEvent, element, className, styles) { + var structural = ['ng-enter', 'ng-leave', 'ng-move'].indexOf(className) >= 0; + + var cacheKey = getCacheKey(element); + var eventCacheKey = cacheKey + ' ' + className; + var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; + + var stagger = {}; + if (itemIndex > 0) { + var staggerClassName = className + '-stagger'; + var staggerCacheKey = cacheKey + ' ' + staggerClassName; + var applyClasses = !lookupCache[staggerCacheKey]; + + applyClasses && element.addClass(staggerClassName); + + stagger = getElementAnimationDetails(element, staggerCacheKey); + + applyClasses && element.removeClass(staggerClassName); + } + + element.addClass(className); + + var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; + var timings = getElementAnimationDetails(element, eventCacheKey); + var transitionDuration = timings.transitionDuration; + var animationDuration = timings.animationDuration; + + if (structural && transitionDuration === 0 && animationDuration === 0) { + element.removeClass(className); + return false; + } + + var blockTransition = styles || (structural && transitionDuration > 0); + var blockAnimation = animationDuration > 0 && + stagger.animationDelay > 0 && + stagger.animationDuration === 0; + + var closeAnimationFns = formerData.closeAnimationFns || []; + element.data(NG_ANIMATE_CSS_DATA_KEY, { + stagger: stagger, + cacheKey: eventCacheKey, + running: formerData.running || 0, + itemIndex: itemIndex, + blockTransition: blockTransition, + closeAnimationFns: closeAnimationFns + }); + + var node = extractElementNode(element); + + if (blockTransition) { + blockTransitions(node, true); + if (styles) { + element.css(styles); + } + } + + if (blockAnimation) { + blockAnimations(node, true); + } + + return true; + } + + function animateRun(animationEvent, element, className, activeAnimationComplete, styles) { + var node = extractElementNode(element); + var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); + if (node.getAttribute('class').indexOf(className) == -1 || !elementData) { + activeAnimationComplete(); + return; + } + + var activeClassName = ''; + var pendingClassName = ''; + forEach(className.split(' '), function (klass, i) { + var prefix = (i > 0 ? ' ' : '') + klass; + activeClassName += prefix + '-active'; + pendingClassName += prefix + '-pending'; + }); + + var style = ''; + var appliedStyles = []; + var itemIndex = elementData.itemIndex; + var stagger = elementData.stagger; + var staggerTime = 0; + if (itemIndex > 0) { + var transitionStaggerDelay = 0; + if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { + transitionStaggerDelay = stagger.transitionDelay * itemIndex; + } + + var animationStaggerDelay = 0; + if (stagger.animationDelay > 0 && stagger.animationDuration === 0) { + animationStaggerDelay = stagger.animationDelay * itemIndex; + appliedStyles.push(CSS_PREFIX + 'animation-play-state'); + } + + staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100; + } + + if (!staggerTime) { + element.addClass(activeClassName); + if (elementData.blockTransition) { + blockTransitions(node, false); + } + } + + var eventCacheKey = elementData.cacheKey + ' ' + activeClassName; + var timings = getElementAnimationDetails(element, eventCacheKey); + var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); + if (maxDuration === 0) { + element.removeClass(activeClassName); + animateClose(element, className); + activeAnimationComplete(); + return; + } + + if (!staggerTime && styles) { + if (!timings.transitionDuration) { + element.css('transition', timings.animationDuration + 's linear all'); + appliedStyles.push('transition'); + } + element.css(styles); + } + + var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); + var maxDelayTime = maxDelay * ONE_SECOND; + + if (appliedStyles.length > 0) { + //the element being animated may sometimes contain comment nodes in + //the jqLite object, so we're safe to use a single variable to house + //the styles since there is always only one element being animated + var oldStyle = node.getAttribute('style') || ''; + if (oldStyle.charAt(oldStyle.length - 1) !== ';') { + oldStyle += ';'; + } + node.setAttribute('style', oldStyle + ' ' + style); + } + + var startTime = Date.now(); + var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; + var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; + var totalTime = (staggerTime + animationTime) * ONE_SECOND; + + var staggerTimeout; + if (staggerTime > 0) { + element.addClass(pendingClassName); + staggerTimeout = $timeout(function () { + staggerTimeout = null; + + if (timings.transitionDuration > 0) { + blockTransitions(node, false); + } + if (timings.animationDuration > 0) { + blockAnimations(node, false); + } + + element.addClass(activeClassName); + element.removeClass(pendingClassName); + + if (styles) { + if (timings.transitionDuration === 0) { + element.css('transition', timings.animationDuration + 's linear all'); + } + element.css(styles); + appliedStyles.push('transition'); + } + }, staggerTime * ONE_SECOND, false); + } + + element.on(css3AnimationEvents, onAnimationProgress); + elementData.closeAnimationFns.push(function () { + onEnd(); + activeAnimationComplete(); + }); + + elementData.running++; + animationCloseHandler(element, totalTime); + return onEnd; + + // This will automatically be called by $animate so + // there is no need to attach this internally to the + // timeout done method. + function onEnd() { + element.off(css3AnimationEvents, onAnimationProgress); + element.removeClass(activeClassName); + element.removeClass(pendingClassName); + if (staggerTimeout) { + $timeout.cancel(staggerTimeout); + } + animateClose(element, className); + var node = extractElementNode(element); + for (var i in appliedStyles) { + node.style.removeProperty(appliedStyles[i]); + } + } + + function onAnimationProgress(event) { + event.stopPropagation(); + var ev = event.originalEvent || event; + var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); + + /* Firefox (or possibly just Gecko) likes to not round values up + * when a ms measurement is used for the animation */ + var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); + + /* $manualTimeStamp is a mocked timeStamp value which is set + * within browserTrigger(). This is only here so that tests can + * mock animations properly. Real events fallback to event.timeStamp, + * or, if they don't, then a timeStamp is automatically created for them. + * We're checking to see if the timeStamp surpasses the expected delay, + * but we're using elapsedTime instead of the timeStamp on the 2nd + * pre-condition since animations sometimes close off early */ + if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + activeAnimationComplete(); + } + } + } + + function blockTransitions(node, bool) { + node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : ''; + } + + function blockAnimations(node, bool) { + node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : ''; + } + + function animateBefore(animationEvent, element, className, styles) { + if (animateSetup(animationEvent, element, className, styles)) { + return function (cancelled) { + cancelled && animateClose(element, className); + }; + } + } + + function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) { + if (element.data(NG_ANIMATE_CSS_DATA_KEY)) { + return animateRun(animationEvent, element, className, afterAnimationComplete, styles); + } else { + animateClose(element, className); + afterAnimationComplete(); + } + } + + function animate(animationEvent, element, className, animationComplete, options) { + //If the animateSetup function doesn't bother returning a + //cancellation function then it means that there is no animation + //to perform at all + var preReflowCancellation = animateBefore(animationEvent, element, className, options.from); + if (!preReflowCancellation) { + clearCacheAfterReflow(); + animationComplete(); + return; + } + + //There are two cancellation functions: one is before the first + //reflow animation and the second is during the active state + //animation. The first function will take care of removing the + //data from the element which will not make the 2nd animation + //happen in the first place + var cancel = preReflowCancellation; + afterReflow(element, function () { + //once the reflow is complete then we point cancel to + //the new cancellation function which will remove all of the + //animation properties from the active animation + cancel = animateAfter(animationEvent, element, className, animationComplete, options.to); + }); + + return function (cancelled) { + (cancel || noop)(cancelled); + }; + } + + function animateClose(element, className) { + element.removeClass(className); + var data = element.data(NG_ANIMATE_CSS_DATA_KEY); + if (data) { + if (data.running) { + data.running--; + } + if (!data.running || data.running === 0) { + element.removeData(NG_ANIMATE_CSS_DATA_KEY); + } + } + } + + return { + animate: function (element, className, from, to, animationCompleted, options) { + options = options || {}; + options.from = from; + options.to = to; + return animate('animate', element, className, animationCompleted, options); + }, + + enter: function (element, animationCompleted, options) { + options = options || {}; + return animate('enter', element, 'ng-enter', animationCompleted, options); + }, + + leave: function (element, animationCompleted, options) { + options = options || {}; + return animate('leave', element, 'ng-leave', animationCompleted, options); + }, + + move: function (element, animationCompleted, options) { + options = options || {}; + return animate('move', element, 'ng-move', animationCompleted, options); + }, + + beforeSetClass: function (element, add, remove, animationCompleted, options) { + options = options || {}; + var className = suffixClasses(remove, '-remove') + ' ' + + suffixClasses(add, '-add'); + var cancellationMethod = animateBefore('setClass', element, className, options.from); + if (cancellationMethod) { + afterReflow(element, animationCompleted); + return cancellationMethod; + } + clearCacheAfterReflow(); + animationCompleted(); + }, + + beforeAddClass: function (element, className, animationCompleted, options) { + options = options || {}; + var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from); + if (cancellationMethod) { + afterReflow(element, animationCompleted); + return cancellationMethod; + } + clearCacheAfterReflow(); + animationCompleted(); + }, + + beforeRemoveClass: function (element, className, animationCompleted, options) { + options = options || {}; + var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from); + if (cancellationMethod) { + afterReflow(element, animationCompleted); + return cancellationMethod; + } + clearCacheAfterReflow(); + animationCompleted(); + }, + + setClass: function (element, add, remove, animationCompleted, options) { + options = options || {}; + remove = suffixClasses(remove, '-remove'); + add = suffixClasses(add, '-add'); + var className = remove + ' ' + add; + return animateAfter('setClass', element, className, animationCompleted, options.to); + }, + + addClass: function (element, className, animationCompleted, options) { + options = options || {}; + return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to); + }, + + removeClass: function (element, className, animationCompleted, options) { + options = options || {}; + return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to); + } + }; + + function suffixClasses(classes, suffix) { + var className = ''; + classes = isArray(classes) ? classes : classes.split(/\s+/); + forEach(classes, function (klass, i) { + if (klass && klass.length > 0) { + className += (i > 0 ? ' ' : '') + klass + suffix; + } + }); + return className; + } + }]); + }]); })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-cookies.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-cookies.js index 3a598e24..db8606a4 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-cookies.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-cookies.js @@ -3,148 +3,149 @@ * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; - -/** - * @ngdoc module - * @name ngCookies - * @description - * - * # ngCookies - * - * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. - * - * - *
              - * - * See {@link ngCookies.$cookies `$cookies`} and - * {@link ngCookies.$cookieStore `$cookieStore`} for usage. - */ - - -angular.module('ngCookies', ['ng']). - /** - * @ngdoc service - * @name $cookies - * - * @description - * Provides read/write access to browser's cookies. - * - * Only a simple Object is exposed and by adding or removing properties to/from this object, new - * cookies are created/deleted at the end of current $eval. - * The object's properties can only be strings. - * - * Requires the {@link ngCookies `ngCookies`} module to be installed. - * - * @example - * - * ```js - * angular.module('cookiesExample', ['ngCookies']) - * .controller('ExampleController', ['$cookies', function($cookies) { +(function (window, angular, undefined) { + 'use strict'; + + /** + * @ngdoc module + * @name ngCookies + * @description + * + * # ngCookies + * + * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. + * + * + *
              + * + * See {@link ngCookies.$cookies `$cookies`} and + * {@link ngCookies.$cookieStore `$cookieStore`} for usage. + */ + + + angular.module('ngCookies', ['ng']). + /** + * @ngdoc service + * @name $cookies + * + * @description + * Provides read/write access to browser's cookies. + * + * Only a simple Object is exposed and by adding or removing properties to/from this object, new + * cookies are created/deleted at the end of current $eval. + * The object's properties can only be strings. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * + * @example + * + * ```js + * angular.module('cookiesExample', ['ngCookies']) + * .controller('ExampleController', ['$cookies', function($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * }]); - * ``` - */ - factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { - var cookies = {}, - lastCookies = {}, - lastBrowserCookies, - runEval = false, - copy = angular.copy, - isUndefined = angular.isUndefined; - - //creates a poller fn that copies all cookies from the $browser to service & inits the service - $browser.addPollFn(function() { - var currentCookies = $browser.cookies(); - if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl - lastBrowserCookies = currentCookies; - copy(currentCookies, lastCookies); - copy(currentCookies, cookies); - if (runEval) $rootScope.$apply(); - } - })(); - - runEval = true; - - //at the end of each eval, push cookies - //TODO: this should happen before the "delayed" watches fire, because if some cookies are not - // strings or browser refuses to store some cookies, we update the model in the push fn. - $rootScope.$watch(push); - - return cookies; - - - /** - * Pushes all the cookies from the service to the browser and verifies if all cookies were - * stored. - */ - function push() { - var name, - value, - browserCookies, - updated; - - //delete any cookies deleted in $cookies - for (name in lastCookies) { - if (isUndefined(cookies[name])) { - $browser.cookies(name, undefined); - } - } - - //update all cookies updated in $cookies - for(name in cookies) { - value = cookies[name]; - if (!angular.isString(value)) { - value = '' + value; - cookies[name] = value; - } - if (value !== lastCookies[name]) { - $browser.cookies(name, value); - updated = true; - } - } - - //verify what was actually stored - if (updated){ - updated = false; - browserCookies = $browser.cookies(); - - for (name in cookies) { - if (cookies[name] !== browserCookies[name]) { - //delete or reset all cookies that the browser dropped from $cookies - if (isUndefined(browserCookies[name])) { - delete cookies[name]; - } else { - cookies[name] = browserCookies[name]; - } - updated = true; + * ``` + */ + factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { + var cookies = {}, + lastCookies = {}, + lastBrowserCookies, + runEval = false, + copy = angular.copy, + isUndefined = angular.isUndefined; + + //creates a poller fn that copies all cookies from the $browser to service & inits the service + $browser.addPollFn(function () { + var currentCookies = $browser.cookies(); + if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl + lastBrowserCookies = currentCookies; + copy(currentCookies, lastCookies); + copy(currentCookies, cookies); + if (runEval) $rootScope.$apply(); + } + })(); + + runEval = true; + + //at the end of each eval, push cookies + //TODO: this should happen before the "delayed" watches fire, because if some cookies are not + // strings or browser refuses to store some cookies, we update the model in the push fn. + $rootScope.$watch(push); + + return cookies; + + + /** + * Pushes all the cookies from the service to the browser and verifies if all cookies were + * stored. + */ + function push() { + var name, + value, + browserCookies, + updated; + + //delete any cookies deleted in $cookies + for (name in lastCookies) { + if (isUndefined(cookies[name])) { + $browser.cookies(name, undefined); + } + } + + //update all cookies updated in $cookies + for (name in cookies) { + value = cookies[name]; + if (!angular.isString(value)) { + value = '' + value; + cookies[name] = value; + } + if (value !== lastCookies[name]) { + $browser.cookies(name, value); + updated = true; + } + } + + //verify what was actually stored + if (updated) { + updated = false; + browserCookies = $browser.cookies(); + + for (name in cookies) { + if (cookies[name] !== browserCookies[name]) { + //delete or reset all cookies that the browser dropped from $cookies + if (isUndefined(browserCookies[name])) { + delete cookies[name]; + } else { + cookies[name] = browserCookies[name]; + } + updated = true; + } + } + } } - } - } - } - }]). - - - /** - * @ngdoc service - * @name $cookieStore - * @requires $cookies - * - * @description - * Provides a key-value (string-object) storage, that is backed by session cookies. - * Objects put or retrieved from this storage are automatically serialized or - * deserialized by angular's toJson/fromJson. - * - * Requires the {@link ngCookies `ngCookies`} module to be installed. - * - * @example - * - * ```js - * angular.module('cookieStoreExample', ['ngCookies']) - * .controller('ExampleController', ['$cookieStore', function($cookieStore) { + }]). + + + /** + * @ngdoc service + * @name $cookieStore + * @requires $cookies + * + * @description + * Provides a key-value (string-object) storage, that is backed by session cookies. + * Objects put or retrieved from this storage are automatically serialized or + * deserialized by angular's toJson/fromJson. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * + * @example + * + * ```js + * angular.module('cookieStoreExample', ['ngCookies']) + * .controller('ExampleController', ['$cookieStore', function($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie @@ -152,55 +153,55 @@ angular.module('ngCookies', ['ng']). * // Removing a cookie * $cookieStore.remove('myFavorite'); * }]); - * ``` - */ - factory('$cookieStore', ['$cookies', function($cookies) { - - return { - /** - * @ngdoc method - * @name $cookieStore#get - * - * @description - * Returns the value of given cookie key - * - * @param {string} key Id to use for lookup. - * @returns {Object} Deserialized cookie value. - */ - get: function(key) { - var value = $cookies[key]; - return value ? angular.fromJson(value) : value; - }, - - /** - * @ngdoc method - * @name $cookieStore#put - * - * @description - * Sets a value for given cookie key - * - * @param {string} key Id for the `value`. - * @param {Object} value Value to be stored. - */ - put: function(key, value) { - $cookies[key] = angular.toJson(value); - }, - - /** - * @ngdoc method - * @name $cookieStore#remove - * - * @description - * Remove given cookie - * - * @param {string} key Id of the key-value pair to delete. - */ - remove: function(key) { - delete $cookies[key]; - } - }; - - }]); + * ``` + */ + factory('$cookieStore', ['$cookies', function ($cookies) { + + return { + /** + * @ngdoc method + * @name $cookieStore#get + * + * @description + * Returns the value of given cookie key + * + * @param {string} key Id to use for lookup. + * @returns {Object} Deserialized cookie value. + */ + get: function (key) { + var value = $cookies[key]; + return value ? angular.fromJson(value) : value; + }, + + /** + * @ngdoc method + * @name $cookieStore#put + * + * @description + * Sets a value for given cookie key + * + * @param {string} key Id for the `value`. + * @param {Object} value Value to be stored. + */ + put: function (key, value) { + $cookies[key] = angular.toJson(value); + }, + + /** + * @ngdoc method + * @name $cookieStore#remove + * + * @description + * Remove given cookie + * + * @param {string} key Id of the key-value pair to delete. + */ + remove: function (key) { + delete $cookies[key]; + } + }; + + }]); })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-input-match.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-input-match.js index f65ffc81..b28384c0 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-input-match.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-input-match.js @@ -5,45 +5,46 @@ * @link https://github.com/TheSharpieOne/angular-input-match * @license MIT License, http://www.opensource.org/licenses/MIT */ -(function(window, angular, undefined){ - -'use strict'; - -angular.module('validation.match', []); - -angular.module('validation.match').directive('match', match); - -function match ($parse) { - return { - require: '?ngModel', - restrict: 'A', - link: function(scope, elem, attrs, ctrl) { - if(!ctrl) { - if(console && console.warn){ - console.warn('Match validation requires ngModel to be on the element'); +(function (window, angular, undefined) { + + 'use strict'; + + angular.module('validation.match', []); + + angular.module('validation.match').directive('match', match); + + function match($parse) { + return { + require: '?ngModel', + restrict: 'A', + link: function (scope, elem, attrs, ctrl) { + if (!ctrl) { + if (console && console.warn) { + console.warn('Match validation requires ngModel to be on the element'); + } + return; } - return; - } - var matchGetter = $parse(attrs.match); + var matchGetter = $parse(attrs.match); - scope.$watch(getMatchValue, function(){ - ctrl.$validate(); - }); + scope.$watch(getMatchValue, function () { + ctrl.$validate(); + }); - ctrl.$validators.match = function(){ - return ctrl.$viewValue === getMatchValue(); - }; + ctrl.$validators.match = function () { + return ctrl.$viewValue === getMatchValue(); + }; - function getMatchValue(){ - var match = matchGetter(scope); - if(angular.isObject(match) && match.hasOwnProperty('$viewValue')){ - match = match.$viewValue; + function getMatchValue() { + var match = matchGetter(scope); + if (angular.isObject(match) && match.hasOwnProperty('$viewValue')) { + match = match.$viewValue; + } + return match; } - return match; } - } - }; -} -match.$inject = ["$parse"]; + }; + } + + match.$inject = ["$parse"]; })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-route.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-route.js index b69f0be4..863ce5b5 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-route.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-route.js @@ -3,327 +3,329 @@ * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; - -/** - * @ngdoc module - * @name ngRoute - * @description - * - * # ngRoute - * - * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. - * - * ## Example - * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. - * - * - *
              - */ - /* global -ngRouteModule */ -var ngRouteModule = angular.module('ngRoute', ['ng']). - provider('$route', $RouteProvider); - -/** - * @ngdoc provider - * @name $routeProvider - * @kind function - * - * @description - * - * Used for configuring routes. - * - * ## Example - * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. - * - * ## Dependencies - * Requires the {@link ngRoute `ngRoute`} module to be installed. - */ -function $RouteProvider(){ - function inherit(parent, extra) { - return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); - } - - var routes = {}; - - /** - * @ngdoc method - * @name $routeProvider#when - * - * @param {string} path Route path (matched against `$location.path`). If `$location.path` - * contains redundant trailing slash or is missing one, the route will still match and the - * `$location.path` will be updated to add or drop the trailing slash to exactly match the - * route definition. - * - * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up - * to the next slash are matched and stored in `$routeParams` under the given `name` - * when the route matches. - * * `path` can contain named groups starting with a colon and ending with a star: - * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` - * when the route matches. - * * `path` can contain optional named groups with a question mark: e.g.`:name?`. - * - * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match - * `/color/brown/largecode/code/with/slashes/edit` and extract: - * - * * `color: brown` - * * `largecode: code/with/slashes`. - * - * - * @param {Object} route Mapping information to be assigned to `$route.current` on route - * match. - * - * Object properties: - * - * - `controller` – `{(string|function()=}` – Controller fn that should be associated with - * newly created scope or the name of a {@link angular.Module#controller registered - * controller} if passed as a string. - * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be - * published to scope under the `controllerAs` name. - * - `template` – `{string=|function()=}` – html template as a string or a function that - * returns an html template as a string which should be used by {@link - * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. - * This property takes precedence over `templateUrl`. - * - * If `template` is a function, it will be called with the following parameters: - * - * - `{Array.}` - route parameters extracted from the current - * `$location.path()` by applying the current route - * - * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html - * template that should be used by {@link ngRoute.directive:ngView ngView}. - * - * If `templateUrl` is a function, it will be called with the following parameters: - * - * - `{Array.}` - route parameters extracted from the current - * `$location.path()` by applying the current route - * - * - `resolve` - `{Object.=}` - An optional map of dependencies which should - * be injected into the controller. If any of these dependencies are promises, the router - * will wait for them all to be resolved or one to be rejected before the controller is - * instantiated. - * If all the promises are resolved successfully, the values of the resolved promises are - * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is - * fired. If any of the promises are rejected the - * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object - * is: - * - * - `key` – `{string}`: a name of a dependency to be injected into the controller. - * - `factory` - `{string|function}`: If `string` then it is an alias for a service. - * Otherwise if function, then it is {@link auto.$injector#invoke injected} - * and the return value is treated as the dependency. If the result is a promise, it is - * resolved before its value is injected into the controller. Be aware that - * `ngRoute.$routeParams` will still refer to the previous route within these resolve - * functions. Use `$route.current.params` to access the new route parameters, instead. - * - * - `redirectTo` – {(string|function())=} – value to update - * {@link ng.$location $location} path with and trigger route redirection. - * - * If `redirectTo` is a function, it will be called with the following parameters: - * - * - `{Object.}` - route parameters extracted from the current - * `$location.path()` by applying the current route templateUrl. - * - `{string}` - current `$location.path()` - * - `{Object}` - current `$location.search()` - * - * The custom `redirectTo` function is expected to return a string which will be used - * to update `$location.path()` and `$location.search()`. - * - * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` - * or `$location.hash()` changes. - * - * If the option is set to `false` and url in the browser changes, then - * `$routeUpdate` event is broadcasted on the root scope. - * - * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive - * - * If the option is set to `true`, then the particular route can be matched without being - * case sensitive - * - * @returns {Object} self - * - * @description - * Adds a new route definition to the `$route` service. - */ - this.when = function(path, route) { - routes[path] = angular.extend( - {reloadOnSearch: true}, - route, - path && pathRegExp(path, route) - ); - - // create redirection for trailing slashes - if (path) { - var redirectPath = (path[path.length-1] == '/') - ? path.substr(0, path.length-1) - : path +'/'; - - routes[redirectPath] = angular.extend( - {redirectTo: path}, - pathRegExp(redirectPath, route) - ); - } - - return this; - }; - - /** - * @param path {string} path - * @param opts {Object} options - * @return {?Object} - * - * @description - * Normalizes the given path, returning a regular expression - * and the original path. - * - * Inspired by pathRexp in visionmedia/express/lib/utils.js. - */ - function pathRegExp(path, opts) { - var insensitive = opts.caseInsensitiveMatch, - ret = { - originalPath: path, - regexp: path - }, - keys = ret.keys = []; - - path = path - .replace(/([().])/g, '\\$1') - .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ - var optional = option === '?' ? option : null; - var star = option === '*' ? option : null; - keys.push({ name: key, optional: !!optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (star && '(.+?)' || '([^/]+)') - + (optional || '') - + ')' - + (optional || ''); - }) - .replace(/([\/$\*])/g, '\\$1'); - - ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); - return ret; - } - - /** - * @ngdoc method - * @name $routeProvider#otherwise - * - * @description - * Sets route definition that will be used on route change when no other route definition - * is matched. - * - * @param {Object} params Mapping information to be assigned to `$route.current`. - * @returns {Object} self - */ - this.otherwise = function(params) { - this.when(null, params); - return this; - }; - - - this.$get = ['$rootScope', - '$location', - '$routeParams', - '$q', - '$injector', - '$http', - '$templateCache', - '$sce', - function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { +(function (window, angular, undefined) { + 'use strict'; /** - * @ngdoc service - * @name $route - * @requires $location - * @requires $routeParams - * - * @property {Object} current Reference to the current route definition. - * The route definition contains: - * - * - `controller`: The controller constructor as define in route definition. - * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for - * controller instantiation. The `locals` contain - * the resolved values of the `resolve` map. Additionally the `locals` also contain: - * - * - `$scope` - The current route scope. - * - `$template` - The current route template HTML. - * - * @property {Object} routes Object with all route configuration Objects as its properties. - * + * @ngdoc module + * @name ngRoute * @description - * `$route` is used for deep-linking URLs to controllers and views (HTML partials). - * It watches `$location.url()` and tries to map the path to an existing route definition. * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. + * # ngRoute * - * The `$route` service is typically used in conjunction with the - * {@link ngRoute.directive:ngView `ngView`} directive and the - * {@link ngRoute.$routeParams `$routeParams`} service. - * - * @example - * This example shows how changing the URL hash causes the `$route` to match a route against the - * URL, and the `ngView` pulls in the partial. + * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * - * - * - *
              - * Choose: - * Moby | - * Moby: Ch1 | - * Gatsby | - * Gatsby: Ch4 | - * Scarlet Letter
              + * ## Example + * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * - *
              * - *
              - * - *
              $location.path() = {{$location.path()}}
              - *
              $route.current.templateUrl = {{$route.current.templateUrl}}
              - *
              $route.current.params = {{$route.current.params}}
              - *
              $route.current.scope.name = {{$route.current.scope.name}}
              - *
              $routeParams = {{$routeParams}}
              - *
              - *
              + *
              + */ + /* global -ngRouteModule */ + var ngRouteModule = angular.module('ngRoute', ['ng']). + provider('$route', $RouteProvider); + + /** + * @ngdoc provider + * @name $routeProvider + * @kind function * - * - * controller: {{name}}
              - * Book Id: {{params.bookId}}
              - *
              + * @description * - * - * controller: {{name}}
              - * Book Id: {{params.bookId}}
              - * Chapter Id: {{params.chapterId}} - *
              + * Used for configuring routes. * - * - * angular.module('ngRouteExample', ['ngRoute']) + * ## Example + * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * - * .controller('MainController', function($scope, $route, $routeParams, $location) { + * ## Dependencies + * Requires the {@link ngRoute `ngRoute`} module to be installed. + */ + function $RouteProvider() { + function inherit(parent, extra) { + return angular.extend(new (angular.extend(function () { + }, {prototype: parent}))(), extra); + } + + var routes = {}; + + /** + * @ngdoc method + * @name $routeProvider#when + * + * @param {string} path Route path (matched against `$location.path`). If `$location.path` + * contains redundant trailing slash or is missing one, the route will still match and the + * `$location.path` will be updated to add or drop the trailing slash to exactly match the + * route definition. + * + * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up + * to the next slash are matched and stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain named groups starting with a colon and ending with a star: + * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain optional named groups with a question mark: e.g.`:name?`. + * + * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match + * `/color/brown/largecode/code/with/slashes/edit` and extract: + * + * * `color: brown` + * * `largecode: code/with/slashes`. + * + * + * @param {Object} route Mapping information to be assigned to `$route.current` on route + * match. + * + * Object properties: + * + * - `controller` – `{(string|function()=}` – Controller fn that should be associated with + * newly created scope or the name of a {@link angular.Module#controller registered + * controller} if passed as a string. + * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be + * published to scope under the `controllerAs` name. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used by {@link + * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. + * This property takes precedence over `templateUrl`. + * + * If `template` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used by {@link ngRoute.directive:ngView ngView}. + * + * If `templateUrl` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `resolve` - `{Object.=}` - An optional map of dependencies which should + * be injected into the controller. If any of these dependencies are promises, the router + * will wait for them all to be resolved or one to be rejected before the controller is + * instantiated. + * If all the promises are resolved successfully, the values of the resolved promises are + * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is + * fired. If any of the promises are rejected the + * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object + * is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|function}`: If `string` then it is an alias for a service. + * Otherwise if function, then it is {@link auto.$injector#invoke injected} + * and the return value is treated as the dependency. If the result is a promise, it is + * resolved before its value is injected into the controller. Be aware that + * `ngRoute.$routeParams` will still refer to the previous route within these resolve + * functions. Use `$route.current.params` to access the new route parameters, instead. + * + * - `redirectTo` – {(string|function())=} – value to update + * {@link ng.$location $location} path with and trigger route redirection. + * + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current + * `$location.path()` by applying the current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used + * to update `$location.path()` and `$location.search()`. + * + * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` + * or `$location.hash()` changes. + * + * If the option is set to `false` and url in the browser changes, then + * `$routeUpdate` event is broadcasted on the root scope. + * + * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive + * + * If the option is set to `true`, then the particular route can be matched without being + * case sensitive + * + * @returns {Object} self + * + * @description + * Adds a new route definition to the `$route` service. + */ + this.when = function (path, route) { + routes[path] = angular.extend( + {reloadOnSearch: true}, + route, + path && pathRegExp(path, route) + ); + + // create redirection for trailing slashes + if (path) { + var redirectPath = (path[path.length - 1] == '/') + ? path.substr(0, path.length - 1) + : path + '/'; + + routes[redirectPath] = angular.extend( + {redirectTo: path}, + pathRegExp(redirectPath, route) + ); + } + + return this; + }; + + /** + * @param path {string} path + * @param opts {Object} options + * @return {?Object} + * + * @description + * Normalizes the given path, returning a regular expression + * and the original path. + * + * Inspired by pathRexp in visionmedia/express/lib/utils.js. + */ + function pathRegExp(path, opts) { + var insensitive = opts.caseInsensitiveMatch, + ret = { + originalPath: path, + regexp: path + }, + keys = ret.keys = []; + + path = path + .replace(/([().])/g, '\\$1') + .replace(/(\/)?:(\w+)([\?\*])?/g, function (_, slash, key, option) { + var optional = option === '?' ? option : null; + var star = option === '*' ? option : null; + keys.push({name: key, optional: !!optional}); + slash = slash || ''; + return '' + + (optional ? '' : slash) + + '(?:' + + (optional ? slash : '') + + (star && '(.+?)' || '([^/]+)') + + (optional || '') + + ')' + + (optional || ''); + }) + .replace(/([\/$\*])/g, '\\$1'); + + ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); + return ret; + } + + /** + * @ngdoc method + * @name $routeProvider#otherwise + * + * @description + * Sets route definition that will be used on route change when no other route definition + * is matched. + * + * @param {Object} params Mapping information to be assigned to `$route.current`. + * @returns {Object} self + */ + this.otherwise = function (params) { + this.when(null, params); + return this; + }; + + + this.$get = ['$rootScope', + '$location', + '$routeParams', + '$q', + '$injector', + '$http', + '$templateCache', + '$sce', + function ($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { + + /** + * @ngdoc service + * @name $route + * @requires $location + * @requires $routeParams + * + * @property {Object} current Reference to the current route definition. + * The route definition contains: + * + * - `controller`: The controller constructor as define in route definition. + * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for + * controller instantiation. The `locals` contain + * the resolved values of the `resolve` map. Additionally the `locals` also contain: + * + * - `$scope` - The current route scope. + * - `$template` - The current route template HTML. + * + * @property {Object} routes Object with all route configuration Objects as its properties. + * + * @description + * `$route` is used for deep-linking URLs to controllers and views (HTML partials). + * It watches `$location.url()` and tries to map the path to an existing route definition. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. + * + * The `$route` service is typically used in conjunction with the + * {@link ngRoute.directive:ngView `ngView`} directive and the + * {@link ngRoute.$routeParams `$routeParams`} service. + * + * @example + * This example shows how changing the URL hash causes the `$route` to match a route against the + * URL, and the `ngView` pulls in the partial. + * + * + * + *
              + * Choose: + * Moby | + * Moby: Ch1 | + * Gatsby | + * Gatsby: Ch4 | + * Scarlet Letter
              + * + *
              + * + *
              + * + *
              $location.path() = {{$location.path()}}
              + *
              $route.current.templateUrl = {{$route.current.templateUrl}}
              + *
              $route.current.params = {{$route.current.params}}
              + *
              $route.current.scope.name = {{$route.current.scope.name}}
              + *
              $routeParams = {{$routeParams}}
              + *
              + *
              + * + * + * controller: {{name}}
              + * Book Id: {{params.bookId}}
              + *
              + * + * + * controller: {{name}}
              + * Book Id: {{params.bookId}}
              + * Chapter Id: {{params.chapterId}} + *
              + * + * + * angular.module('ngRouteExample', ['ngRoute']) + * + * .controller('MainController', function($scope, $route, $routeParams, $location) { * $scope.$route = $route; * $scope.$location = $location; * $scope.$routeParams = $routeParams; * }) - * - * .controller('BookController', function($scope, $routeParams) { + * + * .controller('BookController', function($scope, $routeParams) { * $scope.name = "BookController"; * $scope.params = $routeParams; * }) - * - * .controller('ChapterController', function($scope, $routeParams) { + * + * .controller('ChapterController', function($scope, $routeParams) { * $scope.name = "ChapterController"; * $scope.params = $routeParams; * }) - * - * .config(function($routeProvider, $locationProvider) { + * + * .config(function($routeProvider, $locationProvider) { * $routeProvider * .when('/Book/:bookId', { * templateUrl: 'book.html', @@ -345,11 +347,11 @@ function $RouteProvider(){ * // configure html5 to get links working on jsfiddle * $locationProvider.html5Mode(true); * }); - * - * - * - * - * it('should load and compile correct template', function() { + * + * + * + * + * it('should load and compile correct template', function() { * element(by.linkText('Moby: Ch1')).click(); * var content = element(by.css('[ng-view]')).getText(); * expect(content).toMatch(/controller\: ChapterController/); @@ -362,356 +364,361 @@ function $RouteProvider(){ * expect(content).toMatch(/controller\: BookController/); * expect(content).toMatch(/Book Id\: Scarlet/); * }); - * - *
              - */ - - /** - * @ngdoc event - * @name $route#$routeChangeStart - * @eventType broadcast on root scope - * @description - * Broadcasted before a route change. At this point the route services starts - * resolving all of the dependencies needed for the route change to occur. - * Typically this involves fetching the view template as well as any dependencies - * defined in `resolve` route property. Once all of the dependencies are resolved - * `$routeChangeSuccess` is fired. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} next Future route information. - * @param {Route} current Current route information. - */ - - /** - * @ngdoc event - * @name $route#$routeChangeSuccess - * @eventType broadcast on root scope - * @description - * Broadcasted after a route dependencies are resolved. - * {@link ngRoute.directive:ngView ngView} listens for the directive - * to instantiate the controller and render the view. - * - * @param {Object} angularEvent Synthetic event object. - * @param {Route} current Current route information. - * @param {Route|Undefined} previous Previous route information, or undefined if current is - * first route entered. - */ + * + * + */ + + /** + * @ngdoc event + * @name $route#$routeChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a route change. At this point the route services starts + * resolving all of the dependencies needed for the route change to occur. + * Typically this involves fetching the view template as well as any dependencies + * defined in `resolve` route property. Once all of the dependencies are resolved + * `$routeChangeSuccess` is fired. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} next Future route information. + * @param {Route} current Current route information. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a route dependencies are resolved. + * {@link ngRoute.directive:ngView ngView} listens for the directive + * to instantiate the controller and render the view. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} current Current route information. + * @param {Route|Undefined} previous Previous route information, or undefined if current is + * first route entered. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeError + * @eventType broadcast on root scope + * @description + * Broadcasted if any of the resolve promises are rejected. + * + * @param {Object} angularEvent Synthetic event object + * @param {Route} current Current route information. + * @param {Route} previous Previous route information. + * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. + */ + + /** + * @ngdoc event + * @name $route#$routeUpdate + * @eventType broadcast on root scope + * @description + * + * The `reloadOnSearch` property has been set to false, and we are reusing the same + * instance of the Controller. + */ + + var forceReload = false, + $route = { + routes: routes, + + /** + * @ngdoc method + * @name $route#reload + * + * @description + * Causes `$route` service to reload the current route even if + * {@link ng.$location $location} hasn't changed. + * + * As a result of that, {@link ngRoute.directive:ngView ngView} + * creates new scope, reinstantiates the controller. + */ + reload: function () { + forceReload = true; + $rootScope.$evalAsync(updateRoute); + } + }; + + $rootScope.$on('$locationChangeSuccess', updateRoute); + + return $route; + + ///////////////////////////////////////////////////// + + /** + * @param on {string} current url + * @param route {Object} route regexp to match the url against + * @return {?Object} + * + * @description + * Check if the route matches the current url. + * + * Inspired by match in + * visionmedia/express/lib/router/router.js. + */ + function switchRouteMatcher(on, route) { + var keys = route.keys, + params = {}; + + if (!route.regexp) return null; + + var m = route.regexp.exec(on); + if (!m) return null; + + for (var i = 1, len = m.length; i < len; ++i) { + var key = keys[i - 1]; + + var val = m[i]; + + if (key && val) { + params[key.name] = val; + } + } + return params; + } - /** - * @ngdoc event - * @name $route#$routeChangeError - * @eventType broadcast on root scope - * @description - * Broadcasted if any of the resolve promises are rejected. - * - * @param {Object} angularEvent Synthetic event object - * @param {Route} current Current route information. - * @param {Route} previous Previous route information. - * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. - */ + function updateRoute() { + var next = parseRoute(), + last = $route.current; + + if (next && last && next.$$route === last.$$route + && angular.equals(next.pathParams, last.pathParams) + && !next.reloadOnSearch && !forceReload) { + last.params = next.params; + angular.copy(last.params, $routeParams); + $rootScope.$broadcast('$routeUpdate', last); + } else if (next || last) { + forceReload = false; + $rootScope.$broadcast('$routeChangeStart', next, last); + $route.current = next; + if (next) { + if (next.redirectTo) { + if (angular.isString(next.redirectTo)) { + $location.path(interpolate(next.redirectTo, next.params)).search(next.params) + .replace(); + } else { + $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) + .replace(); + } + } + } + + $q.when(next). + then(function () { + if (next) { + var locals = angular.extend({}, next.resolve), + template, templateUrl; + + angular.forEach(locals, function (value, key) { + locals[key] = angular.isString(value) ? + $injector.get(value) : $injector.invoke(value); + }); + + if (angular.isDefined(template = next.template)) { + if (angular.isFunction(template)) { + template = template(next.params); + } + } else if (angular.isDefined(templateUrl = next.templateUrl)) { + if (angular.isFunction(templateUrl)) { + templateUrl = templateUrl(next.params); + } + templateUrl = $sce.getTrustedResourceUrl(templateUrl); + if (angular.isDefined(templateUrl)) { + next.loadedTemplateUrl = templateUrl; + template = $http.get(templateUrl, {cache: $templateCache}). + then(function (response) { + return response.data; + }); + } + } + if (angular.isDefined(template)) { + locals['$template'] = template; + } + return $q.all(locals); + } + }). + // after route change + then(function (locals) { + if (next == $route.current) { + if (next) { + next.locals = locals; + angular.copy(next.params, $routeParams); + } + $rootScope.$broadcast('$routeChangeSuccess', next, last); + } + }, function (error) { + if (next == $route.current) { + $rootScope.$broadcast('$routeChangeError', next, last, error); + } + }); + } + } - /** - * @ngdoc event - * @name $route#$routeUpdate - * @eventType broadcast on root scope - * @description - * - * The `reloadOnSearch` property has been set to false, and we are reusing the same - * instance of the Controller. - */ - var forceReload = false, - $route = { - routes: routes, - - /** - * @ngdoc method - * @name $route#reload - * - * @description - * Causes `$route` service to reload the current route even if - * {@link ng.$location $location} hasn't changed. - * - * As a result of that, {@link ngRoute.directive:ngView ngView} - * creates new scope, reinstantiates the controller. - */ - reload: function() { - forceReload = true; - $rootScope.$evalAsync(updateRoute); - } - }; + /** + * @returns {Object} the current active route, by matching it against the URL + */ + function parseRoute() { + // Match a route + var params, match; + angular.forEach(routes, function (route, path) { + if (!match && (params = switchRouteMatcher($location.path(), route))) { + match = inherit(route, { + params: angular.extend({}, $location.search(), params), + pathParams: params + }); + match.$$route = route; + } + }); + // No route matched; fallback to "otherwise" route + return match || routes[null] && inherit(routes[null], {params: {}, pathParams: {}}); + } - $rootScope.$on('$locationChangeSuccess', updateRoute); + /** + * @returns {string} interpolation of the redirect path with the parameters + */ + function interpolate(string, params) { + var result = []; + angular.forEach((string || '').split(':'), function (segment, i) { + if (i === 0) { + result.push(segment); + } else { + var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); + var key = segmentMatch[1]; + result.push(params[key]); + result.push(segmentMatch[2] || ''); + delete params[key]; + } + }); + return result.join(''); + } + }]; + } - return $route; + ngRouteModule.provider('$routeParams', $RouteParamsProvider); - ///////////////////////////////////////////////////// /** - * @param on {string} current url - * @param route {Object} route regexp to match the url against - * @return {?Object} + * @ngdoc service + * @name $routeParams + * @requires $route * * @description - * Check if the route matches the current url. + * The `$routeParams` service allows you to retrieve the current set of route parameters. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * The route parameters are a combination of {@link ng.$location `$location`}'s + * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. + * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * - * Inspired by match in - * visionmedia/express/lib/router/router.js. + * In case of parameter name collision, `path` params take precedence over `search` params. + * + * The service guarantees that the identity of the `$routeParams` object will remain unchanged + * (but its properties will likely change) even when a route change occurs. + * + * Note that the `$routeParams` are only updated *after* a route change completes successfully. + * This means that you cannot rely on `$routeParams` being correct in route resolve functions. + * Instead you can use `$route.current.params` to access the new route's parameters. + * + * @example + * ```js + * // Given: + * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby + * // Route: /Chapter/:chapterId/Section/:sectionId + * // + * // Then + * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} + * ``` */ - function switchRouteMatcher(on, route) { - var keys = route.keys, - params = {}; - - if (!route.regexp) return null; - - var m = route.regexp.exec(on); - if (!m) return null; - - for (var i = 1, len = m.length; i < len; ++i) { - var key = keys[i - 1]; - - var val = m[i]; - - if (key && val) { - params[key.name] = val; - } - } - return params; - } - - function updateRoute() { - var next = parseRoute(), - last = $route.current; - - if (next && last && next.$$route === last.$$route - && angular.equals(next.pathParams, last.pathParams) - && !next.reloadOnSearch && !forceReload) { - last.params = next.params; - angular.copy(last.params, $routeParams); - $rootScope.$broadcast('$routeUpdate', last); - } else if (next || last) { - forceReload = false; - $rootScope.$broadcast('$routeChangeStart', next, last); - $route.current = next; - if (next) { - if (next.redirectTo) { - if (angular.isString(next.redirectTo)) { - $location.path(interpolate(next.redirectTo, next.params)).search(next.params) - .replace(); - } else { - $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) - .replace(); - } - } - } - - $q.when(next). - then(function() { - if (next) { - var locals = angular.extend({}, next.resolve), - template, templateUrl; - - angular.forEach(locals, function(value, key) { - locals[key] = angular.isString(value) ? - $injector.get(value) : $injector.invoke(value); - }); - - if (angular.isDefined(template = next.template)) { - if (angular.isFunction(template)) { - template = template(next.params); - } - } else if (angular.isDefined(templateUrl = next.templateUrl)) { - if (angular.isFunction(templateUrl)) { - templateUrl = templateUrl(next.params); - } - templateUrl = $sce.getTrustedResourceUrl(templateUrl); - if (angular.isDefined(templateUrl)) { - next.loadedTemplateUrl = templateUrl; - template = $http.get(templateUrl, {cache: $templateCache}). - then(function(response) { return response.data; }); - } - } - if (angular.isDefined(template)) { - locals['$template'] = template; - } - return $q.all(locals); - } - }). - // after route change - then(function(locals) { - if (next == $route.current) { - if (next) { - next.locals = locals; - angular.copy(next.params, $routeParams); - } - $rootScope.$broadcast('$routeChangeSuccess', next, last); - } - }, function(error) { - if (next == $route.current) { - $rootScope.$broadcast('$routeChangeError', next, last, error); - } - }); - } + function $RouteParamsProvider() { + this.$get = function () { + return {}; + }; } + ngRouteModule.directive('ngView', ngViewFactory); + ngRouteModule.directive('ngView', ngViewFillContentFactory); - /** - * @returns {Object} the current active route, by matching it against the URL - */ - function parseRoute() { - // Match a route - var params, match; - angular.forEach(routes, function(route, path) { - if (!match && (params = switchRouteMatcher($location.path(), route))) { - match = inherit(route, { - params: angular.extend({}, $location.search(), params), - pathParams: params}); - match.$$route = route; - } - }); - // No route matched; fallback to "otherwise" route - return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); - } /** - * @returns {string} interpolation of the redirect path with the parameters - */ - function interpolate(string, params) { - var result = []; - angular.forEach((string||'').split(':'), function(segment, i) { - if (i === 0) { - result.push(segment); - } else { - var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); - var key = segmentMatch[1]; - result.push(params[key]); - result.push(segmentMatch[2] || ''); - delete params[key]; - } - }); - return result.join(''); - } - }]; -} - -ngRouteModule.provider('$routeParams', $RouteParamsProvider); - - -/** - * @ngdoc service - * @name $routeParams - * @requires $route - * - * @description - * The `$routeParams` service allows you to retrieve the current set of route parameters. - * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * The route parameters are a combination of {@link ng.$location `$location`}'s - * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. - * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. - * - * In case of parameter name collision, `path` params take precedence over `search` params. - * - * The service guarantees that the identity of the `$routeParams` object will remain unchanged - * (but its properties will likely change) even when a route change occurs. - * - * Note that the `$routeParams` are only updated *after* a route change completes successfully. - * This means that you cannot rely on `$routeParams` being correct in route resolve functions. - * Instead you can use `$route.current.params` to access the new route's parameters. - * - * @example - * ```js - * // Given: - * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby - * // Route: /Chapter/:chapterId/Section/:sectionId - * // - * // Then - * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} - * ``` - */ -function $RouteParamsProvider() { - this.$get = function() { return {}; }; -} - -ngRouteModule.directive('ngView', ngViewFactory); -ngRouteModule.directive('ngView', ngViewFillContentFactory); - - -/** - * @ngdoc directive - * @name ngView - * @restrict ECA - * - * @description - * # Overview - * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by - * including the rendered template of the current route into the main layout (`index.html`) file. - * Every time the current route changes, the included view changes with it according to the - * configuration of the `$route` service. - * - * Requires the {@link ngRoute `ngRoute`} module to be installed. - * - * @animations - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. - * - * The enter and leave animation occur concurrently. - * - * @scope - * @priority 400 - * @param {string=} onload Expression to evaluate whenever the view updates. - * - * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll + * @ngdoc directive + * @name ngView + * @restrict ECA + * + * @description + * # Overview + * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by + * including the rendered template of the current route into the main layout (`index.html`) file. + * Every time the current route changes, the included view changes with it according to the + * configuration of the `$route` service. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * @priority 400 + * @param {string=} onload Expression to evaluate whenever the view updates. + * + * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. - * - * - If the attribute is not set, disable scrolling. - * - If the attribute is set without value, enable scrolling. - * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated - * as an expression yields a truthy value. - * @example - - -
              - Choose: - Moby | - Moby: Ch1 | - Gatsby | - Gatsby: Ch4 | - Scarlet Letter
              - -
              -
              -
              -
              - -
              $location.path() = {{main.$location.path()}}
              -
              $route.current.templateUrl = {{main.$route.current.templateUrl}}
              -
              $route.current.params = {{main.$route.current.params}}
              -
              $route.current.scope.name = {{main.$route.current.scope.name}}
              -
              $routeParams = {{main.$routeParams}}
              -
              -
              - - -
              - controller: {{book.name}}
              - Book Id: {{book.params.bookId}}
              -
              -
              - - -
              - controller: {{chapter.name}}
              - Book Id: {{chapter.params.bookId}}
              - Chapter Id: {{chapter.params.chapterId}} -
              -
              - - - .view-animate-container { + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated + * as an expression yields a truthy value. + * @example + + +
              + Choose: + Moby | + Moby: Ch1 | + Gatsby | + Gatsby: Ch4 | + Scarlet Letter
              + +
              +
              +
              +
              + +
              $location.path() = {{main.$location.path()}}
              +
              $route.current.templateUrl = {{main.$route.current.templateUrl}}
              +
              $route.current.params = {{main.$route.current.params}}
              +
              $route.current.scope.name = {{main.$route.current.scope.name}}
              +
              $routeParams = {{main.$routeParams}}
              +
              +
              + + +
              + controller: {{book.name}}
              + Book Id: {{book.params.bookId}}
              +
              +
              + + +
              + controller: {{chapter.name}}
              + Book Id: {{chapter.params.bookId}}
              + Chapter Id: {{chapter.params.chapterId}} +
              +
              + + + .view-animate-container { position:relative; height:100px!important; position:relative; @@ -721,11 +728,11 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); overflow:hidden; } - .view-animate { + .view-animate { padding:10px; } - .view-animate.ng-enter, .view-animate.ng-leave { + .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; @@ -741,21 +748,21 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); padding:10px; } - .view-animate.ng-enter { + .view-animate.ng-enter { left:100%; } - .view-animate.ng-enter.ng-enter-active { + .view-animate.ng-enter.ng-enter-active { left:0; } - .view-animate.ng-leave.ng-leave-active { + .view-animate.ng-leave.ng-leave-active { left:-100%; } - +
              - - angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) - .config(['$routeProvider', '$locationProvider', - function($routeProvider, $locationProvider) { + + angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) + .config(['$routeProvider', '$locationProvider', + function($routeProvider, $locationProvider) { $routeProvider .when('/Book/:bookId', { templateUrl: 'book.html', @@ -770,25 +777,25 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); $locationProvider.html5Mode(true); }]) - .controller('MainCtrl', ['$route', '$routeParams', '$location', - function($route, $routeParams, $location) { + .controller('MainCtrl', ['$route', '$routeParams', '$location', + function($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; }]) - .controller('BookCtrl', ['$routeParams', function($routeParams) { + .controller('BookCtrl', ['$routeParams', function($routeParams) { this.name = "BookCtrl"; this.params = $routeParams; }]) - .controller('ChapterCtrl', ['$routeParams', function($routeParams) { + .controller('ChapterCtrl', ['$routeParams', function($routeParams) { this.name = "ChapterCtrl"; this.params = $routeParams; }]); - + - - it('should load and compile correct template', function() { + + it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCtrl/); @@ -801,121 +808,121 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); expect(content).toMatch(/controller\: BookCtrl/); expect(content).toMatch(/Book Id\: Scarlet/); }); - -
              - */ + + + */ -/** - * @ngdoc event - * @name ngView#$viewContentLoaded - * @eventType emit on the current ngView scope - * @description - * Emitted every time the ngView content is reloaded. - */ -ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; -function ngViewFactory( $route, $anchorScroll, $animate) { - return { - restrict: 'ECA', - terminal: true, - priority: 400, - transclude: 'element', - link: function(scope, $element, attr, ctrl, $transclude) { - var currentScope, - currentElement, - previousElement, - autoScrollExp = attr.autoscroll, - onloadExp = attr.onload || ''; - - scope.$on('$routeChangeSuccess', update); - update(); - - function cleanupLastView() { - if(previousElement) { - previousElement.remove(); - previousElement = null; - } - if(currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if(currentElement) { - $animate.leave(currentElement, function() { - previousElement = null; - }); - previousElement = currentElement; - currentElement = null; - } - } + /** + * @ngdoc event + * @name ngView#$viewContentLoaded + * @eventType emit on the current ngView scope + * @description + * Emitted every time the ngView content is reloaded. + */ + ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; + function ngViewFactory($route, $anchorScroll, $animate) { + return { + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + link: function (scope, $element, attr, ctrl, $transclude) { + var currentScope, + currentElement, + previousElement, + autoScrollExp = attr.autoscroll, + onloadExp = attr.onload || ''; + + scope.$on('$routeChangeSuccess', update); + update(); + + function cleanupLastView() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement, function () { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + } - function update() { - var locals = $route.current && $route.current.locals, - template = locals && locals.$template; - - if (angular.isDefined(template)) { - var newScope = scope.$new(); - var current = $route.current; - - // Note: This will also link all children of ng-view that were contained in the original - // html. If that content contains controllers, ... they could pollute/change the scope. - // However, using ng-view on an element with additional content does not make sense... - // Note: We can't remove them in the cloneAttchFn of $transclude as that - // function is called before linking the content, which would apply child - // directives to non existing elements. - var clone = $transclude(newScope, function(clone) { - $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { - if (angular.isDefined(autoScrollExp) - && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); + function update() { + var locals = $route.current && $route.current.locals, + template = locals && locals.$template; + + if (angular.isDefined(template)) { + var newScope = scope.$new(); + var current = $route.current; + + // Note: This will also link all children of ng-view that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-view on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function (clone) { + $animate.enter(clone, null, currentElement || $element, function onNgViewEnter() { + if (angular.isDefined(autoScrollExp) + && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }); + cleanupLastView(); + }); + + currentElement = clone; + currentScope = current.scope = newScope; + currentScope.$emit('$viewContentLoaded'); + currentScope.$eval(onloadExp); + } else { + cleanupLastView(); + } } - }); - cleanupLastView(); - }); - - currentElement = clone; - currentScope = current.scope = newScope; - currentScope.$emit('$viewContentLoaded'); - currentScope.$eval(onloadExp); - } else { - cleanupLastView(); - } - } + } + }; } - }; -} // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. -ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; -function ngViewFillContentFactory($compile, $controller, $route) { - return { - restrict: 'ECA', - priority: -400, - link: function(scope, $element) { - var current = $route.current, - locals = current.locals; - - $element.html(locals.$template); - - var link = $compile($element.contents()); - - if (current.controller) { - locals.$scope = scope; - var controller = $controller(current.controller, locals); - if (current.controllerAs) { - scope[current.controllerAs] = controller; - } - $element.data('$ngControllerController', controller); - $element.children().data('$ngControllerController', controller); - } + ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; + function ngViewFillContentFactory($compile, $controller, $route) { + return { + restrict: 'ECA', + priority: -400, + link: function (scope, $element) { + var current = $route.current, + locals = current.locals; + + $element.html(locals.$template); + + var link = $compile($element.contents()); + + if (current.controller) { + locals.$scope = scope; + var controller = $controller(current.controller, locals); + if (current.controllerAs) { + scope[current.controllerAs] = controller; + } + $element.data('$ngControllerController', controller); + $element.children().data('$ngControllerController', controller); + } - link(scope); + link(scope); + } + }; } - }; -} })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-sanitize.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-sanitize.js index 806e92d7..4e0902ed 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-sanitize.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-sanitize.js @@ -3,64 +3,65 @@ * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; - -var $sanitizeMinErr = angular.$$minErr('$sanitize'); - -/** - * @ngdoc module - * @name ngSanitize - * @description - * - * # ngSanitize - * - * The `ngSanitize` module provides functionality to sanitize HTML. - * - * - *
              - * - * See {@link ngSanitize.$sanitize `$sanitize`} for usage. - */ - -/* - * HTML Parser By Misko Hevery (misko@hevery.com) - * based on: HTML Parser By John Resig (ejohn.org) - * Original code by Erik Arvidsson, Mozilla Public License - * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js - * - * // Use like so: - * htmlParser(htmlString, { - * start: function(tag, attrs, unary) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * }); - * - */ - - -/** - * @ngdoc service - * @name $sanitize - * @function - * - * @description - * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are - * then serialized back to properly escaped html string. This means that no unsafe input can make - * it into the returned string, however, since our parser is more strict than a typical browser - * parser, it's possible that some obscure input, which would be recognized as valid HTML by a - * browser, won't make it through the sanitizer. - * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and - * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. - * - * @param {string} html Html input. - * @returns {string} Sanitized html. - * - * @example - - +(function (window, angular, undefined) { + 'use strict'; + + var $sanitizeMinErr = angular.$$minErr('$sanitize'); + + /** + * @ngdoc module + * @name ngSanitize + * @description + * + * # ngSanitize + * + * The `ngSanitize` module provides functionality to sanitize HTML. + * + * + *
              + * + * See {@link ngSanitize.$sanitize `$sanitize`} for usage. + */ + + /* + * HTML Parser By Misko Hevery (misko@hevery.com) + * based on: HTML Parser By John Resig (ejohn.org) + * Original code by Erik Arvidsson, Mozilla Public License + * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js + * + * // Use like so: + * htmlParser(htmlString, { + * start: function(tag, attrs, unary) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * }); + * + */ + + + /** + * @ngdoc service + * @name $sanitize + * @function + * + * @description + * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are + * then serialized back to properly escaped html string. This means that no unsafe input can make + * it into the returned string, however, since our parser is more strict than a typical browser + * parser, it's possible that some obscure input, which would be recognized as valid HTML by a + * browser, won't make it through the sanitizer. + * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and + * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. + * + * @param {string} html Html input. + * @returns {string} Sanitized html. + * + * @example + +
              - Snippet: -
          - - - - - - - - - - - - - - - - - - - - - - - - -
          DirectiveHowSourceRendered
          ng-bind-htmlAutomatically uses $sanitize
          <div ng-bind-html="snippet">
          </div>
          ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value -
          <div ng-bind-html="deliberatelyTrustDangerousSnippet()">
          -</div>
          -
          ng-bindAutomatically escapes
          <div ng-bind="snippet">
          </div>
          - - - + Snippet: + + + + + + + + + + + + + + + + + + + + + + + + + +
          DirectiveHowSourceRendered
          ng-bind-htmlAutomatically uses $sanitize
          <div ng-bind-html="snippet">
          </div>
          ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value +
          <div ng-bind-html="deliberatelyTrustDangerousSnippet()">
          +     </div>
          +
          ng-bindAutomatically escapes
          <div ng-bind="snippet">
          </div>
          + +
          + it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('

          an html\nclick here\nsnippet

          '); @@ -133,41 +134,41 @@ var $sanitizeMinErr = angular.$$minErr('$sanitize'); expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( "new <b onclick=\"alert(1)\">text</b>"); }); -
          - - */ -function $SanitizeProvider() { - this.$get = ['$$sanitizeUri', function($$sanitizeUri) { - return function(html) { - var buf = []; - htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { - return !/^unsafe/.test($$sanitizeUri(uri, isImage)); - })); - return buf.join(''); - }; - }]; -} - -function sanitizeText(chars) { - var buf = []; - var writer = htmlSanitizeWriter(buf, angular.noop); - writer.chars(chars); - return buf.join(''); -} + + + */ + function $SanitizeProvider() { + this.$get = ['$$sanitizeUri', function ($$sanitizeUri) { + return function (html) { + var buf = []; + htmlParser(html, htmlSanitizeWriter(buf, function (uri, isImage) { + return !/^unsafe/.test($$sanitizeUri(uri, isImage)); + })); + return buf.join(''); + }; + }]; + } + + function sanitizeText(chars) { + var buf = []; + var writer = htmlSanitizeWriter(buf, angular.noop); + writer.chars(chars); + return buf.join(''); + } // Regular Expressions for parsing tags and attributes -var START_TAG_REGEXP = - /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, - END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, - ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, - BEGIN_TAG_REGEXP = /^/g, - DOCTYPE_REGEXP = /]*?)>/i, - CDATA_REGEXP = //g, - // Match everything outside of normal chars and " (quote character) - NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; + var START_TAG_REGEXP = + /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, + END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, + ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, + BEGIN_TAG_REGEXP = /^/g, + DOCTYPE_REGEXP = /]*?)>/i, + CDATA_REGEXP = //g, + // Match everything outside of normal chars and " (quote character) + NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes @@ -176,326 +177,331 @@ var START_TAG_REGEXP = // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements -var voidElements = makeMap("area,br,col,hr,img,wbr"); + var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags -var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), - optionalEndTagInlineElements = makeMap("rp,rt"), - optionalEndTagElements = angular.extend({}, - optionalEndTagInlineElements, - optionalEndTagBlockElements); + var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), + optionalEndTagInlineElements = makeMap("rp,rt"), + optionalEndTagElements = angular.extend({}, + optionalEndTagInlineElements, + optionalEndTagBlockElements); // Safe Block Elements - HTML5 -var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + + var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 -var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + + var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) -var specialElements = makeMap("script,style"); + var specialElements = makeMap("script,style"); -var validElements = angular.extend({}, - voidElements, - blockElements, - inlineElements, - optionalEndTagElements); + var validElements = angular.extend({}, + voidElements, + blockElements, + inlineElements, + optionalEndTagElements); //Attributes that have href and hence need to be sanitized -var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); -var validAttrs = angular.extend({}, uriAttrs, makeMap( - 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ - 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ - 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ - 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ - 'valign,value,vspace,width')); - -function makeMap(str) { - var obj = {}, items = str.split(','), i; - for (i = 0; i < items.length; i++) obj[items[i]] = true; - return obj; -} + var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); + var validAttrs = angular.extend({}, uriAttrs, makeMap( + 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + + 'scope,scrolling,shape,size,span,start,summary,target,title,type,' + + 'valign,value,vspace,width')); + + function makeMap(str) { + var obj = {}, items = str.split(','), i; + for (i = 0; i < items.length; i++) obj[items[i]] = true; + return obj; + } -/** - * @example - * htmlParser(htmlString, { + /** + * @example + * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); - * - * @param {string} html string - * @param {object} handler - */ -function htmlParser( html, handler ) { - var index, chars, match, stack = [], last = html; - stack.last = function() { return stack[ stack.length - 1 ]; }; - - while ( html ) { - chars = true; - - // Make sure we're not in a script or style element - if ( !stack.last() || !specialElements[ stack.last() ] ) { - - // Comment - if ( html.indexOf("", index) === index) { - if (handler.comment) handler.comment( html.substring( 4, index ) ); - html = html.substring( index + 3 ); - chars = false; - } - // DOCTYPE - } else if ( DOCTYPE_REGEXP.test(html) ) { - match = html.match( DOCTYPE_REGEXP ); - - if ( match ) { - html = html.replace( match[0], ''); - chars = false; - } - // end tag - } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { - match = html.match( END_TAG_REGEXP ); - - if ( match ) { - html = html.substring( match[0].length ); - match[0].replace( END_TAG_REGEXP, parseEndTag ); - chars = false; + * + * @param {string} html string + * @param {object} handler + */ + function htmlParser(html, handler) { + var index, chars, match, stack = [], last = html; + stack.last = function () { + return stack[stack.length - 1]; + }; + + while (html) { + chars = true; + + // Make sure we're not in a script or style element + if (!stack.last() || !specialElements[stack.last()]) { + + // Comment + if (html.indexOf("", index) === index) { + if (handler.comment) handler.comment(html.substring(4, index)); + html = html.substring(index + 3); + chars = false; + } + // DOCTYPE + } else if (DOCTYPE_REGEXP.test(html)) { + match = html.match(DOCTYPE_REGEXP); + + if (match) { + html = html.replace(match[0], ''); + chars = false; + } + // end tag + } else if (BEGING_END_TAGE_REGEXP.test(html)) { + match = html.match(END_TAG_REGEXP); + + if (match) { + html = html.substring(match[0].length); + match[0].replace(END_TAG_REGEXP, parseEndTag); + chars = false; + } + + // start tag + } else if (BEGIN_TAG_REGEXP.test(html)) { + match = html.match(START_TAG_REGEXP); + + if (match) { + html = html.substring(match[0].length); + match[0].replace(START_TAG_REGEXP, parseStartTag); + chars = false; + } + } + + if (chars) { + index = html.indexOf("<"); + + var text = index < 0 ? html : html.substring(0, index); + html = index < 0 ? "" : html.substring(index); + + if (handler.chars) handler.chars(decodeEntities(text)); + } + + } else { + html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), + function (all, text) { + text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); + + if (handler.chars) handler.chars(decodeEntities(text)); + + return ""; + }); + + parseEndTag("", stack.last()); + } + + if (html == last) { + throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + + "of html: {0}", html); + } + last = html; } - // start tag - } else if ( BEGIN_TAG_REGEXP.test(html) ) { - match = html.match( START_TAG_REGEXP ); + // Clean up any remaining tags + parseEndTag(); - if ( match ) { - html = html.substring( match[0].length ); - match[0].replace( START_TAG_REGEXP, parseStartTag ); - chars = false; - } - } + function parseStartTag(tag, tagName, rest, unary) { + tagName = angular.lowercase(tagName); + if (blockElements[tagName]) { + while (stack.last() && inlineElements[stack.last()]) { + parseEndTag("", stack.last()); + } + } - if ( chars ) { - index = html.indexOf("<"); + if (optionalEndTagElements[tagName] && stack.last() == tagName) { + parseEndTag("", tagName); + } - var text = index < 0 ? html : html.substring( 0, index ); - html = index < 0 ? "" : html.substring( index ); + unary = voidElements[tagName] || !!unary; - if (handler.chars) handler.chars( decodeEntities(text) ); - } + if (!unary) + stack.push(tagName); - } else { - html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), - function(all, text){ - text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); + var attrs = {}; - if (handler.chars) handler.chars( decodeEntities(text) ); + rest.replace(ATTR_REGEXP, + function (match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { + var value = doubleQuotedValue + || singleQuotedValue + || unquotedValue + || ''; - return ""; - }); + attrs[name] = decodeEntities(value); + }); + if (handler.start) handler.start(tagName, attrs, unary); + } - parseEndTag( "", stack.last() ); + function parseEndTag(tag, tagName) { + var pos = 0, i; + tagName = angular.lowercase(tagName); + if (tagName) + // Find the closest opened tag of the same type + for (pos = stack.length - 1; pos >= 0; pos--) + if (stack[pos] == tagName) + break; + + if (pos >= 0) { + // Close all the open elements, up the stack + for (i = stack.length - 1; i >= pos; i--) + if (handler.end) handler.end(stack[i]); + + // Remove the open elements from the stack + stack.length = pos; + } + } } - if ( html == last ) { - throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + - "of html: {0}", html); - } - last = html; - } - - // Clean up any remaining tags - parseEndTag(); - - function parseStartTag( tag, tagName, rest, unary ) { - tagName = angular.lowercase(tagName); - if ( blockElements[ tagName ] ) { - while ( stack.last() && inlineElements[ stack.last() ] ) { - parseEndTag( "", stack.last() ); - } - } + var hiddenPre = document.createElement("pre"); + var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; + + /** + * decodes all entities into regular string + * @param value + * @returns {string} A string with decoded entities. + */ + function decodeEntities(value) { + if (!value) { + return ''; + } - if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { - parseEndTag( "", tagName ); + // Note: IE8 does not preserve spaces at the start/end of innerHTML + // so we must capture them and reattach them afterward + var parts = spaceRe.exec(value); + var spaceBefore = parts[1]; + var spaceAfter = parts[3]; + var content = parts[2]; + if (content) { + hiddenPre.innerHTML = content.replace(/= 0; pos-- ) - if ( stack[ pos ] == tagName ) - break; - - if ( pos >= 0 ) { - // Close all the open elements, up the stack - for ( i = stack.length - 1; i >= pos; i-- ) - if (handler.end) handler.end( stack[ i ] ); - - // Remove the open elements from the stack - stack.length = pos; + /** + * Escapes all potentially dangerous characters, so that the + * resulting string can be safely inserted into attribute or + * element text. + * @param value + * @returns {string} escaped text + */ + function encodeEntities(value) { + return value. + replace(/&/g, '&'). + replace(NON_ALPHANUMERIC_REGEXP, function (value) { + return '&#' + value.charCodeAt(0) + ';'; + }). + replace(//g, '>'); } - } -} -var hiddenPre=document.createElement("pre"); -var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; -/** - * decodes all entities into regular string - * @param value - * @returns {string} A string with decoded entities. - */ -function decodeEntities(value) { - if (!value) { return ''; } - - // Note: IE8 does not preserve spaces at the start/end of innerHTML - // so we must capture them and reattach them afterward - var parts = spaceRe.exec(value); - var spaceBefore = parts[1]; - var spaceAfter = parts[3]; - var content = parts[2]; - if (content) { - hiddenPre.innerHTML=content.replace(//g, '>'); -} - -/** - * create an HTML/XML writer which writes to buffer - * @param {Array} buf use buf.jain('') to get out sanitized html string - * @returns {object} in the form of { + /** + * create an HTML/XML writer which writes to buffer + * @param {Array} buf use buf.jain('') to get out sanitized html string + * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } - */ -function htmlSanitizeWriter(buf, uriValidator){ - var ignore = false; - var out = angular.bind(buf, buf.push); - return { - start: function(tag, attrs, unary){ - tag = angular.lowercase(tag); - if (!ignore && specialElements[tag]) { - ignore = tag; - } - if (!ignore && validElements[tag] === true) { - out('<'); - out(tag); - angular.forEach(attrs, function(value, key){ - var lkey=angular.lowercase(key); - var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); - if (validAttrs[lkey] === true && - (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { - out(' '); - out(key); - out('="'); - out(encodeEntities(value)); - out('"'); - } - }); - out(unary ? '/>' : '>'); - } - }, - end: function(tag){ - tag = angular.lowercase(tag); - if (!ignore && validElements[tag] === true) { - out(''); - } - if (tag == ignore) { - ignore = false; - } - }, - chars: function(chars){ - if (!ignore) { - out(encodeEntities(chars)); - } - } - }; -} + */ + function htmlSanitizeWriter(buf, uriValidator) { + var ignore = false; + var out = angular.bind(buf, buf.push); + return { + start: function (tag, attrs, unary) { + tag = angular.lowercase(tag); + if (!ignore && specialElements[tag]) { + ignore = tag; + } + if (!ignore && validElements[tag] === true) { + out('<'); + out(tag); + angular.forEach(attrs, function (value, key) { + var lkey = angular.lowercase(key); + var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); + if (validAttrs[lkey] === true && + (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { + out(' '); + out(key); + out('="'); + out(encodeEntities(value)); + out('"'); + } + }); + out(unary ? '/>' : '>'); + } + }, + end: function (tag) { + tag = angular.lowercase(tag); + if (!ignore && validElements[tag] === true) { + out(''); + } + if (tag == ignore) { + ignore = false; + } + }, + chars: function (chars) { + if (!ignore) { + out(encodeEntities(chars)); + } + } + }; + } // define ngSanitize module and register $sanitize service -angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); - -/* global sanitizeText: false */ - -/** - * @ngdoc filter - * @name linky - * @function - * - * @description - * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and - * plain email address links. - * - * Requires the {@link ngSanitize `ngSanitize`} module to be installed. - * - * @param {string} text Input text. - * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. - * @returns {string} Html-linkified text. - * - * @usage - - * - * @example - + angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); + + /* global sanitizeText: false */ + + /** + * @ngdoc filter + * @name linky + * @function + * + * @description + * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and + * plain email address links. + * + * Requires the {@link ngSanitize `ngSanitize`} module to be installed. + * + * @param {string} text Input text. + * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. + * @returns {string} Html-linkified text. + * + * @usage + + * + * @example + - -
          - Snippet: - - - - - - - - - - - - - - - - - - - - - -
          FilterSourceRendered
          linky filter -
          <div ng-bind-html="snippet | linky">
          </div>
          -
          -
          -
          linky target -
          <div ng-bind-html="snippetWithTarget | linky:'_blank'">
          </div>
          -
          -
          -
          no filter
          <div ng-bind="snippet">
          </div>
          + +
          + Snippet: + + + + + + + + + + + + + + + + + + + + + +
          FilterSourceRendered
          linky filter +
          <div ng-bind-html="snippet | linky">
          </div>
          +
          +
          +
          linky target +
          <div ng-bind-html="snippetWithTarget | linky:'_blank'">
          </div>
          +
          +
          +
          no filter
          <div ng-bind="snippet">
          </div>
          - it('should linkify the snippet with urls', function() { + it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); - it('should not linkify snippet without the linky filter', function() { + it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); - it('should update', function() { + it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). @@ -563,62 +569,62 @@ angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); .toBe('new http://link.'); }); - it('should work with the target property', function() { + it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); - - */ -angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { - var LINKY_URL_REGEXP = - /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, - MAILTO_REGEXP = /^mailto:/; - - return function(text, target) { - if (!text) return text; - var match; - var raw = text; - var html = []; - var url; - var i; - while ((match = raw.match(LINKY_URL_REGEXP))) { - // We can not end in these as they are sometimes found at the end of the sentence - url = match[0]; - // if we did not match ftp/http/mailto then assume mailto - if (match[2] == match[3]) url = 'mailto:' + url; - i = match.index; - addText(raw.substr(0, i)); - addLink(url, match[0].replace(MAILTO_REGEXP, '')); - raw = raw.substring(i + match[0].length); - } - addText(raw); - return $sanitize(html.join('')); - - function addText(text) { - if (!text) { - return; - } - html.push(sanitizeText(text)); - } - - function addLink(url, text) { - html.push(''); - addText(text); - html.push(''); - } - }; -}]); + + */ + angular.module('ngSanitize').filter('linky', ['$sanitize', function ($sanitize) { + var LINKY_URL_REGEXP = + /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/, + MAILTO_REGEXP = /^mailto:/; + + return function (text, target) { + if (!text) return text; + var match; + var raw = text; + var html = []; + var url; + var i; + while ((match = raw.match(LINKY_URL_REGEXP))) { + // We can not end in these as they are sometimes found at the end of the sentence + url = match[0]; + // if we did not match ftp/http/mailto then assume mailto + if (match[2] == match[3]) url = 'mailto:' + url; + i = match.index; + addText(raw.substr(0, i)); + addLink(url, match[0].replace(MAILTO_REGEXP, '')); + raw = raw.substring(i + match[0].length); + } + addText(raw); + return $sanitize(html.join('')); + + function addText(text) { + if (!text) { + return; + } + html.push(sanitizeText(text)); + } + + function addLink(url, text) { + html.push(''); + addText(text); + html.push(''); + } + }; + }]); })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.js index 5971d883..c9c9480b 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.js @@ -5,2309 +5,2381 @@ * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ -(function(window, document, undefined) { -'use strict'; +(function (window, document, undefined) { + 'use strict'; // Source: module.js -angular.module('mgcrea.ngStrap', [ - 'mgcrea.ngStrap.modal', - 'mgcrea.ngStrap.aside', - 'mgcrea.ngStrap.alert', - 'mgcrea.ngStrap.button', - 'mgcrea.ngStrap.select', - 'mgcrea.ngStrap.datepicker', - 'mgcrea.ngStrap.timepicker', - 'mgcrea.ngStrap.navbar', - 'mgcrea.ngStrap.tooltip', - 'mgcrea.ngStrap.popover', - 'mgcrea.ngStrap.dropdown', - 'mgcrea.ngStrap.typeahead', - 'mgcrea.ngStrap.scrollspy', - 'mgcrea.ngStrap.affix', - 'mgcrea.ngStrap.tab', - 'mgcrea.ngStrap.collapse' -]); + angular.module('mgcrea.ngStrap', [ + 'mgcrea.ngStrap.modal', + 'mgcrea.ngStrap.aside', + 'mgcrea.ngStrap.alert', + 'mgcrea.ngStrap.button', + 'mgcrea.ngStrap.select', + 'mgcrea.ngStrap.datepicker', + 'mgcrea.ngStrap.timepicker', + 'mgcrea.ngStrap.navbar', + 'mgcrea.ngStrap.tooltip', + 'mgcrea.ngStrap.popover', + 'mgcrea.ngStrap.dropdown', + 'mgcrea.ngStrap.typeahead', + 'mgcrea.ngStrap.scrollspy', + 'mgcrea.ngStrap.affix', + 'mgcrea.ngStrap.tab', + 'mgcrea.ngStrap.collapse' + ]); // Source: affix.js -angular.module('mgcrea.ngStrap.affix', ['mgcrea.ngStrap.helpers.dimensions', 'mgcrea.ngStrap.helpers.debounce']) + angular.module('mgcrea.ngStrap.affix', ['mgcrea.ngStrap.helpers.dimensions', 'mgcrea.ngStrap.helpers.debounce']) - .provider('$affix', function() { + .provider('$affix', function () { - var defaults = this.defaults = { - offsetTop: 'auto' - }; - - this.$get = ["$window", "debounce", "dimensions", function($window, debounce, dimensions) { - - var bodyEl = angular.element($window.document.body); - var windowEl = angular.element($window); - - function AffixFactory(element, config) { - - var $affix = {}; + var defaults = this.defaults = { + offsetTop: 'auto' + }; - // Common vars - var options = angular.extend({}, defaults, config); - var targetEl = options.target; + this.$get = ["$window", "debounce", "dimensions", function ($window, debounce, dimensions) { + + var bodyEl = angular.element($window.document.body); + var windowEl = angular.element($window); + + function AffixFactory(element, config) { + + var $affix = {}; + + // Common vars + var options = angular.extend({}, defaults, config); + var targetEl = options.target; + + // Initial private vars + var reset = 'affix affix-top affix-bottom', + setWidth = false, + initialAffixTop = 0, + initialOffsetTop = 0, + offsetTop = 0, + offsetBottom = 0, + affixed = null, + unpin = null; + + var parent = element.parent(); + // Options: custom parent + if (options.offsetParent) { + if (options.offsetParent.match(/^\d+$/)) { + for (var i = 0; i < (options.offsetParent * 1) - 1; i++) { + parent = parent.parent(); + } + } + else { + parent = angular.element(options.offsetParent); + } + } + + $affix.init = function () { + + this.$parseOffsets(); + initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop; + setWidth = !element[0].style.width; + + // Bind events + targetEl.on('scroll', this.checkPosition); + targetEl.on('click', this.checkPositionWithEventLoop); + windowEl.on('resize', this.$debouncedOnResize); + + // Both of these checkPosition() calls are necessary for the case where + // the user hits refresh after scrolling to the bottom of the page. + this.checkPosition(); + this.checkPositionWithEventLoop(); + + }; + + $affix.destroy = function () { + + // Unbind events + targetEl.off('scroll', this.checkPosition); + targetEl.off('click', this.checkPositionWithEventLoop); + windowEl.off('resize', this.$debouncedOnResize); + + }; + + $affix.checkPositionWithEventLoop = function () { + + // IE 9 throws an error if we use 'this' instead of '$affix' + // in this setTimeout call + setTimeout($affix.checkPosition, 1); + + }; + + $affix.checkPosition = function () { + // if (!this.$element.is(':visible')) return + + var scrollTop = getScrollTop(); + var position = dimensions.offset(element[0]); + var elementHeight = dimensions.height(element[0]); + + // Get required affix class according to position + var affix = getRequiredAffixClass(unpin, position, elementHeight); + + // Did affix status changed this last check? + if (affixed === affix) return; + affixed = affix; + + // Add proper affix class + element.removeClass(reset).addClass('affix' + ((affix !== 'middle') ? '-' + affix : '')); + + if (affix === 'top') { + unpin = null; + element.css('position', (options.offsetParent) ? '' : 'relative'); + if (setWidth) { + element.css('width', ''); + } + element.css('top', ''); + } else if (affix === 'bottom') { + if (options.offsetUnpin) { + unpin = -(options.offsetUnpin * 1); + } + else { + // Calculate unpin threshold when affixed to bottom. + // Hopefully the browser scrolls pixel by pixel. + unpin = position.top - scrollTop; + } + if (setWidth) { + element.css('width', ''); + } + element.css('position', (options.offsetParent) ? '' : 'relative'); + element.css('top', (options.offsetParent) ? '' : ((bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop) + 'px')); + } else { // affix === 'middle' + unpin = null; + if (setWidth) { + element.css('width', element[0].offsetWidth + 'px'); + } + element.css('position', 'fixed'); + element.css('top', initialAffixTop + 'px'); + } + + }; + + $affix.$onResize = function () { + $affix.$parseOffsets(); + $affix.checkPosition(); + }; + $affix.$debouncedOnResize = debounce($affix.$onResize, 50); + + $affix.$parseOffsets = function () { + var initialPosition = element.css('position'); + // Reset position to calculate correct offsetTop + element.css('position', (options.offsetParent) ? '' : 'relative'); + + if (options.offsetTop) { + if (options.offsetTop === 'auto') { + options.offsetTop = '+0'; + } + if (options.offsetTop.match(/^[-+]\d+$/)) { + initialAffixTop = -options.offsetTop * 1; + if (options.offsetParent) { + offsetTop = dimensions.offset(parent[0]).top + (options.offsetTop * 1); + } + else { + offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + (options.offsetTop * 1); + } + } + else { + offsetTop = options.offsetTop * 1; + } + } + + if (options.offsetBottom) { + if (options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) { + // add 1 pixel due to rounding problems... + offsetBottom = getScrollHeight() - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + (options.offsetBottom * 1) + 1; + } + else { + offsetBottom = options.offsetBottom * 1; + } + } + + // Bring back the element's position after calculations + element.css('position', initialPosition); + }; + + // Private methods + + function getRequiredAffixClass(unpin, position, elementHeight) { + + var scrollTop = getScrollTop(); + var scrollHeight = getScrollHeight(); + + if (scrollTop <= offsetTop) { + return 'top'; + } else if (unpin !== null && (scrollTop + unpin <= position.top)) { + return 'middle'; + } else if (offsetBottom !== null && (position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom)) { + return 'bottom'; + } else { + return 'middle'; + } + + } + + function getScrollTop() { + return targetEl[0] === $window ? $window.pageYOffset : targetEl[0].scrollTop; + } + + function getScrollHeight() { + return targetEl[0] === $window ? $window.document.body.scrollHeight : targetEl[0].scrollHeight; + } + + $affix.init(); + return $affix; - // Initial private vars - var reset = 'affix affix-top affix-bottom', - setWidth = false, - initialAffixTop = 0, - initialOffsetTop = 0, - offsetTop = 0, - offsetBottom = 0, - affixed = null, - unpin = null; + } - var parent = element.parent(); - // Options: custom parent - if (options.offsetParent) { - if (options.offsetParent.match(/^\d+$/)) { - for (var i = 0; i < (options.offsetParent * 1) - 1; i++) { - parent = parent.parent(); - } - } - else { - parent = angular.element(options.offsetParent); - } - } + return AffixFactory; - $affix.init = function() { + }]; - this.$parseOffsets(); - initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop; - setWidth = !element[0].style.width; + }) - // Bind events - targetEl.on('scroll', this.checkPosition); - targetEl.on('click', this.checkPositionWithEventLoop); - windowEl.on('resize', this.$debouncedOnResize); + .directive('bsAffix', ["$affix", "$window", function ($affix, $window) { - // Both of these checkPosition() calls are necessary for the case where - // the user hits refresh after scrolling to the bottom of the page. - this.checkPosition(); - this.checkPositionWithEventLoop(); + return { + restrict: 'EAC', + require: '^?bsAffixTarget', + link: function postLink(scope, element, attr, affixTarget) { - }; + var options = {scope: scope, offsetTop: 'auto', target: affixTarget ? affixTarget.$element : angular.element($window)}; + angular.forEach(['offsetTop', 'offsetBottom', 'offsetParent', 'offsetUnpin'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - $affix.destroy = function() { + var affix = $affix(element, options); + scope.$on('$destroy', function () { + affix && affix.destroy(); + options = null; + affix = null; + }); - // Unbind events - targetEl.off('scroll', this.checkPosition); - targetEl.off('click', this.checkPositionWithEventLoop); - windowEl.off('resize', this.$debouncedOnResize); + } + }; - }; + }]) - $affix.checkPositionWithEventLoop = function() { + .directive('bsAffixTarget', function () { + return { + controller: ["$element", function ($element) { + this.$element = $element; + }] + }; + }); - // IE 9 throws an error if we use 'this' instead of '$affix' - // in this setTimeout call - setTimeout($affix.checkPosition, 1); +// Source: alert.js +// @BUG: following snippet won't compile correctly +// @TODO: submit issue to core +// ' ' + - }; + angular.module('mgcrea.ngStrap.alert', ['mgcrea.ngStrap.modal']) + + .provider('$alert', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'alert', + prefixEvent: 'alert', + placement: null, + template: 'alert/alert.tpl.html', + container: false, + element: null, + backdrop: false, + keyboard: true, + show: true, + // Specific options + duration: false, + type: false, + dismissable: true + }; - $affix.checkPosition = function() { - // if (!this.$element.is(':visible')) return + this.$get = ["$modal", "$timeout", function ($modal, $timeout) { - var scrollTop = getScrollTop(); - var position = dimensions.offset(element[0]); - var elementHeight = dimensions.height(element[0]); + function AlertFactory(config) { - // Get required affix class according to position - var affix = getRequiredAffixClass(unpin, position, elementHeight); + var $alert = {}; - // Did affix status changed this last check? - if(affixed === affix) return; - affixed = affix; + // Common vars + var options = angular.extend({}, defaults, config); - // Add proper affix class - element.removeClass(reset).addClass('affix' + ((affix !== 'middle') ? '-' + affix : '')); + $alert = $modal(options); - if(affix === 'top') { - unpin = null; - element.css('position', (options.offsetParent) ? '' : 'relative'); - if(setWidth) { - element.css('width', ''); - } - element.css('top', ''); - } else if(affix === 'bottom') { - if (options.offsetUnpin) { - unpin = -(options.offsetUnpin * 1); - } - else { - // Calculate unpin threshold when affixed to bottom. - // Hopefully the browser scrolls pixel by pixel. - unpin = position.top - scrollTop; - } - if(setWidth) { - element.css('width', ''); - } - element.css('position', (options.offsetParent) ? '' : 'relative'); - element.css('top', (options.offsetParent) ? '' : ((bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop) + 'px')); - } else { // affix === 'middle' - unpin = null; - if(setWidth) { - element.css('width', element[0].offsetWidth + 'px'); - } - element.css('position', 'fixed'); - element.css('top', initialAffixTop + 'px'); - } - - }; - - $affix.$onResize = function() { - $affix.$parseOffsets(); - $affix.checkPosition(); - }; - $affix.$debouncedOnResize = debounce($affix.$onResize, 50); - - $affix.$parseOffsets = function() { - var initialPosition = element.css('position'); - // Reset position to calculate correct offsetTop - element.css('position', (options.offsetParent) ? '' : 'relative'); - - if(options.offsetTop) { - if(options.offsetTop === 'auto') { - options.offsetTop = '+0'; - } - if(options.offsetTop.match(/^[-+]\d+$/)) { - initialAffixTop = - options.offsetTop * 1; - if(options.offsetParent) { - offsetTop = dimensions.offset(parent[0]).top + (options.offsetTop * 1); - } - else { - offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + (options.offsetTop * 1); - } - } - else { - offsetTop = options.offsetTop * 1; - } - } + // Support scope as string options [/*title, content, */ type, dismissable] + $alert.$scope.dismissable = !!options.dismissable; + if (options.type) { + $alert.$scope.type = options.type; + } - if(options.offsetBottom) { - if(options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) { - // add 1 pixel due to rounding problems... - offsetBottom = getScrollHeight() - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + (options.offsetBottom * 1) + 1; - } - else { - offsetBottom = options.offsetBottom * 1; - } - } + // Support auto-close duration + var show = $alert.show; + if (options.duration) { + $alert.show = function () { + show(); + $timeout(function () { + $alert.hide(); + }, options.duration * 1000); + }; + } - // Bring back the element's position after calculations - element.css('position', initialPosition); - }; + return $alert; - // Private methods + } - function getRequiredAffixClass(unpin, position, elementHeight) { + return AlertFactory; - var scrollTop = getScrollTop(); - var scrollHeight = getScrollHeight(); + }]; - if(scrollTop <= offsetTop) { - return 'top'; - } else if(unpin !== null && (scrollTop + unpin <= position.top)) { - return 'middle'; - } else if(offsetBottom !== null && (position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom)) { - return 'bottom'; - } else { - return 'middle'; - } + }) - } + .directive('bsAlert', ["$window", "$sce", "$alert", function ($window, $sce, $alert) { - function getScrollTop() { - return targetEl[0] === $window ? $window.pageYOffset : targetEl[0].scrollTop; - } + var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; - function getScrollHeight() { - return targetEl[0] === $window ? $window.document.body.scrollHeight : targetEl[0].scrollHeight; - } + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr, transclusion) { - $affix.init(); - return $affix; + // Directive options + var options = {scope: scope, element: element, show: false}; + angular.forEach(['template', 'placement', 'keyboard', 'html', 'container', 'animation', 'duration', 'dismissable'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - } + // Support scope as data-attrs + angular.forEach(['title', 'content', 'type'], function (key) { + attr[key] && attr.$observe(key, function (newValue, oldValue) { + scope[key] = $sce.trustAsHtml(newValue); + }); + }); - return AffixFactory; + // Support scope as an object + attr.bsAlert && scope.$watch(attr.bsAlert, function (newValue, oldValue) { + if (angular.isObject(newValue)) { + angular.extend(scope, newValue); + } else { + scope.content = newValue; + } + }, true); - }]; + // Initialize alert + var alert = $alert(options); - }) + // Trigger + element.on(attr.trigger || 'click', alert.toggle); - .directive('bsAffix', ["$affix", "$window", function($affix, $window) { + // Garbage collection + scope.$on('$destroy', function () { + if (alert) alert.destroy(); + options = null; + alert = null; + }); - return { - restrict: 'EAC', - require: '^?bsAffixTarget', - link: function postLink(scope, element, attr, affixTarget) { + } + }; - var options = {scope: scope, offsetTop: 'auto', target: affixTarget ? affixTarget.$element : angular.element($window)}; - angular.forEach(['offsetTop', 'offsetBottom', 'offsetParent', 'offsetUnpin'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + }]); - var affix = $affix(element, options); - scope.$on('$destroy', function() { - affix && affix.destroy(); - options = null; - affix = null; - }); +// Source: aside.js + angular.module('mgcrea.ngStrap.aside', ['mgcrea.ngStrap.modal']) + + .provider('$aside', function () { + + var defaults = this.defaults = { + animation: 'am-fade-and-slide-right', + prefixClass: 'aside', + prefixEvent: 'aside', + placement: 'right', + template: 'aside/aside.tpl.html', + contentTemplate: false, + container: false, + element: null, + backdrop: true, + keyboard: true, + html: false, + show: true + }; - } - }; + this.$get = ["$modal", function ($modal) { - }]) + function AsideFactory(config) { - .directive('bsAffixTarget', function() { - return { - controller: ["$element", function($element) { - this.$element = $element; - }] - }; - }); + var $aside = {}; -// Source: alert.js -// @BUG: following snippet won't compile correctly -// @TODO: submit issue to core -// ' ' + + // Common vars + var options = angular.extend({}, defaults, config); -angular.module('mgcrea.ngStrap.alert', ['mgcrea.ngStrap.modal']) + $aside = $modal(options); - .provider('$alert', function() { + return $aside; - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'alert', - prefixEvent: 'alert', - placement: null, - template: 'alert/alert.tpl.html', - container: false, - element: null, - backdrop: false, - keyboard: true, - show: true, - // Specific options - duration: false, - type: false, - dismissable: true - }; + } - this.$get = ["$modal", "$timeout", function($modal, $timeout) { + return AsideFactory; - function AlertFactory(config) { + }]; - var $alert = {}; + }) - // Common vars - var options = angular.extend({}, defaults, config); + .directive('bsAside', ["$window", "$sce", "$aside", function ($window, $sce, $aside) { - $alert = $modal(options); + var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; - // Support scope as string options [/*title, content, */ type, dismissable] - $alert.$scope.dismissable = !!options.dismissable; - if(options.type) { - $alert.$scope.type = options.type; - } + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr, transclusion) { + // Directive options + var options = {scope: scope, element: element, show: false}; + angular.forEach(['template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - // Support auto-close duration - var show = $alert.show; - if(options.duration) { - $alert.show = function() { - show(); - $timeout(function() { - $alert.hide(); - }, options.duration * 1000); - }; - } + // Support scope as data-attrs + angular.forEach(['title', 'content'], function (key) { + attr[key] && attr.$observe(key, function (newValue, oldValue) { + scope[key] = $sce.trustAsHtml(newValue); + }); + }); - return $alert; + // Support scope as an object + attr.bsAside && scope.$watch(attr.bsAside, function (newValue, oldValue) { + if (angular.isObject(newValue)) { + angular.extend(scope, newValue); + } else { + scope.content = newValue; + } + }, true); - } + // Initialize aside + var aside = $aside(options); - return AlertFactory; + // Trigger + element.on(attr.trigger || 'click', aside.toggle); - }]; + // Garbage collection + scope.$on('$destroy', function () { + if (aside) aside.destroy(); + options = null; + aside = null; + }); - }) + } + }; - .directive('bsAlert', ["$window", "$sce", "$alert", function($window, $sce, $alert) { + }]); - var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; +// Source: button.js + angular.module('mgcrea.ngStrap.button', []) - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr, transclusion) { + .provider('$button', function () { - // Directive options - var options = {scope: scope, element: element, show: false}; - angular.forEach(['template', 'placement', 'keyboard', 'html', 'container', 'animation', 'duration', 'dismissable'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + var defaults = this.defaults = { + activeClass: 'active', + toggleEvent: 'click' + }; - // Support scope as data-attrs - angular.forEach(['title', 'content', 'type'], function(key) { - attr[key] && attr.$observe(key, function(newValue, oldValue) { - scope[key] = $sce.trustAsHtml(newValue); - }); - }); + this.$get = function () { + return {defaults: defaults}; + }; - // Support scope as an object - attr.bsAlert && scope.$watch(attr.bsAlert, function(newValue, oldValue) { - if(angular.isObject(newValue)) { - angular.extend(scope, newValue); - } else { - scope.content = newValue; - } - }, true); - - // Initialize alert - var alert = $alert(options); - - // Trigger - element.on(attr.trigger || 'click', alert.toggle); - - // Garbage collection - scope.$on('$destroy', function() { - if (alert) alert.destroy(); - options = null; - alert = null; - }); + }) + + .directive('bsCheckboxGroup', function () { + + return { + restrict: 'A', + require: 'ngModel', + compile: function postLink(element, attr) { + element.attr('data-toggle', 'buttons'); + element.removeAttr('ng-model'); + var children = element[0].querySelectorAll('input[type="checkbox"]'); + angular.forEach(children, function (child) { + var childEl = angular.element(child); + childEl.attr('bs-checkbox', ''); + childEl.attr('ng-model', attr.ngModel + '.' + childEl.attr('value')); + }); + } - } - }; + }; - }]); + }) + + .directive('bsCheckbox', ["$button", "$$rAF", function ($button, $$rAF) { + + var defaults = $button.defaults; + var constantValueRegExp = /^(true|false|\d+)$/; + + return { + restrict: 'A', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { + + var options = defaults; + + // Support label > input[type="checkbox"] + var isInput = element[0].nodeName === 'INPUT'; + var activeElement = isInput ? element.parent() : element; + + var trueValue = angular.isDefined(attr.trueValue) ? attr.trueValue : true; + if (constantValueRegExp.test(attr.trueValue)) { + trueValue = scope.$eval(attr.trueValue); + } + var falseValue = angular.isDefined(attr.falseValue) ? attr.falseValue : false; + if (constantValueRegExp.test(attr.falseValue)) { + falseValue = scope.$eval(attr.falseValue); + } + + // Parse exotic values + var hasExoticValues = typeof trueValue !== 'boolean' || typeof falseValue !== 'boolean'; + if (hasExoticValues) { + controller.$parsers.push(function (viewValue) { + // console.warn('$parser', element.attr('ng-model'), 'viewValue', viewValue); + return viewValue ? trueValue : falseValue; + }); + // modelValue -> $formatters -> viewValue + controller.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + return angular.equals(modelValue, trueValue); + }); + // Fix rendering for exotic values + scope.$watch(attr.ngModel, function (newValue, oldValue) { + controller.$render(); + }); + } + + // model -> view + controller.$render = function () { + // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); + var isActive = angular.equals(controller.$modelValue, trueValue); + $$rAF(function () { + if (isInput) element[0].checked = isActive; + activeElement.toggleClass(options.activeClass, isActive); + }); + }; + + // view -> model + element.bind(options.toggleEvent, function () { + scope.$apply(function () { + // console.warn('!click', element.attr('ng-model'), 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue, 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue); + if (!isInput) { + controller.$setViewValue(!activeElement.hasClass('active')); + } + if (!hasExoticValues) { + controller.$render(); + } + }); + }); -// Source: aside.js -angular.module('mgcrea.ngStrap.aside', ['mgcrea.ngStrap.modal']) + } - .provider('$aside', function() { + }; - var defaults = this.defaults = { - animation: 'am-fade-and-slide-right', - prefixClass: 'aside', - prefixEvent: 'aside', - placement: 'right', - template: 'aside/aside.tpl.html', - contentTemplate: false, - container: false, - element: null, - backdrop: true, - keyboard: true, - html: false, - show: true - }; + }]) + + .directive('bsRadioGroup', function () { + + return { + restrict: 'A', + require: 'ngModel', + compile: function postLink(element, attr) { + element.attr('data-toggle', 'buttons'); + element.removeAttr('ng-model'); + var children = element[0].querySelectorAll('input[type="radio"]'); + angular.forEach(children, function (child) { + angular.element(child).attr('bs-radio', ''); + angular.element(child).attr('ng-model', attr.ngModel); + }); + } - this.$get = ["$modal", function($modal) { + }; - function AsideFactory(config) { + }) - var $aside = {}; + .directive('bsRadio', ["$button", "$$rAF", function ($button, $$rAF) { - // Common vars - var options = angular.extend({}, defaults, config); + var defaults = $button.defaults; + var constantValueRegExp = /^(true|false|\d+)$/; - $aside = $modal(options); + return { + restrict: 'A', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { - return $aside; + var options = defaults; - } + // Support `label > input[type="radio"]` markup + var isInput = element[0].nodeName === 'INPUT'; + var activeElement = isInput ? element.parent() : element; - return AsideFactory; + var value = constantValueRegExp.test(attr.value) ? scope.$eval(attr.value) : attr.value; - }]; + // model -> view + controller.$render = function () { + // console.warn('$render', element.attr('value'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); + var isActive = angular.equals(controller.$modelValue, value); + $$rAF(function () { + if (isInput) element[0].checked = isActive; + activeElement.toggleClass(options.activeClass, isActive); + }); + }; - }) + // view -> model + element.bind(options.toggleEvent, function () { + scope.$apply(function () { + // console.warn('!click', element.attr('value'), 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue, 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue); + controller.$setViewValue(value); + controller.$render(); + }); + }); - .directive('bsAside', ["$window", "$sce", "$aside", function($window, $sce, $aside) { + } - var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; + }; - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr, transclusion) { - // Directive options - var options = {scope: scope, element: element, show: false}; - angular.forEach(['template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + }]); - // Support scope as data-attrs - angular.forEach(['title', 'content'], function(key) { - attr[key] && attr.$observe(key, function(newValue, oldValue) { - scope[key] = $sce.trustAsHtml(newValue); - }); - }); +// Source: collapse.js + angular.module('mgcrea.ngStrap.collapse', []) - // Support scope as an object - attr.bsAside && scope.$watch(attr.bsAside, function(newValue, oldValue) { - if(angular.isObject(newValue)) { - angular.extend(scope, newValue); - } else { - scope.content = newValue; - } - }, true); - - // Initialize aside - var aside = $aside(options); - - // Trigger - element.on(attr.trigger || 'click', aside.toggle); - - // Garbage collection - scope.$on('$destroy', function() { - if (aside) aside.destroy(); - options = null; - aside = null; - }); + .provider('$collapse', function () { - } - }; + var defaults = this.defaults = { + animation: 'am-collapse', + disallowToggle: false, + activeClass: 'in', + startCollapsed: false, + allowMultiple: false + }; - }]); + var controller = this.controller = function ($scope, $element, $attrs) { + var self = this; + + // Attributes options + self.$options = angular.copy(defaults); + angular.forEach(['animation', 'disallowToggle', 'activeClass', 'startCollapsed', 'allowMultiple'], function (key) { + if (angular.isDefined($attrs[key])) self.$options[key] = $attrs[key]; + }); + + self.$toggles = []; + self.$targets = []; + + self.$viewChangeListeners = []; + + self.$registerToggle = function (element) { + self.$toggles.push(element); + }; + self.$registerTarget = function (element) { + self.$targets.push(element); + }; + + self.$unregisterToggle = function (element) { + var index = self.$toggles.indexOf(element); + // remove toggle from $toggles array + self.$toggles.splice(index, 1); + }; + self.$unregisterTarget = function (element) { + var index = self.$targets.indexOf(element); + + // remove element from $targets array + self.$targets.splice(index, 1); + + if (self.$options.allowMultiple) { + // remove target index from $active array values + deactivateItem(element); + } + + // fix active item indexes + fixActiveItemIndexes(index); + + self.$viewChangeListeners.forEach(function (fn) { + fn(); + }); + }; + + // use array to store all the currently open panels + self.$targets.$active = !self.$options.startCollapsed ? [0] : []; + self.$setActive = $scope.$setActive = function (value) { + if (angular.isArray(value)) { + self.$targets.$active = angular.copy(value); + } + else if (!self.$options.disallowToggle) { + // toogle element active status + isActive(value) ? deactivateItem(value) : activateItem(value); + } else { + activateItem(value); + } + + self.$viewChangeListeners.forEach(function (fn) { + fn(); + }); + }; + + self.$activeIndexes = function () { + return self.$options.allowMultiple ? self.$targets.$active : + self.$targets.$active.length === 1 ? self.$targets.$active[0] : -1; + }; + + function fixActiveItemIndexes(index) { + // item with index was removed, so we + // need to adjust other items index values + var activeIndexes = self.$targets.$active; + for (var i = 0; i < activeIndexes.length; i++) { + if (index < activeIndexes[i]) { + activeIndexes[i] = activeIndexes[i] - 1; + } + + // the last item is active, so we need to + // adjust its index + if (activeIndexes[i] === self.$targets.length) { + activeIndexes[i] = self.$targets.length - 1; + } + } + } -// Source: button.js -angular.module('mgcrea.ngStrap.button', []) - - .provider('$button', function() { - - var defaults = this.defaults = { - activeClass:'active', - toggleEvent:'click' - }; - - this.$get = function() { - return {defaults: defaults}; - }; - - }) - - .directive('bsCheckboxGroup', function() { - - return { - restrict: 'A', - require: 'ngModel', - compile: function postLink(element, attr) { - element.attr('data-toggle', 'buttons'); - element.removeAttr('ng-model'); - var children = element[0].querySelectorAll('input[type="checkbox"]'); - angular.forEach(children, function(child) { - var childEl = angular.element(child); - childEl.attr('bs-checkbox', ''); - childEl.attr('ng-model', attr.ngModel + '.' + childEl.attr('value')); - }); - } - - }; - - }) - - .directive('bsCheckbox', ["$button", "$$rAF", function($button, $$rAF) { - - var defaults = $button.defaults; - var constantValueRegExp = /^(true|false|\d+)$/; - - return { - restrict: 'A', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { - - var options = defaults; - - // Support label > input[type="checkbox"] - var isInput = element[0].nodeName === 'INPUT'; - var activeElement = isInput ? element.parent() : element; - - var trueValue = angular.isDefined(attr.trueValue) ? attr.trueValue : true; - if(constantValueRegExp.test(attr.trueValue)) { - trueValue = scope.$eval(attr.trueValue); - } - var falseValue = angular.isDefined(attr.falseValue) ? attr.falseValue : false; - if(constantValueRegExp.test(attr.falseValue)) { - falseValue = scope.$eval(attr.falseValue); - } - - // Parse exotic values - var hasExoticValues = typeof trueValue !== 'boolean' || typeof falseValue !== 'boolean'; - if(hasExoticValues) { - controller.$parsers.push(function(viewValue) { - // console.warn('$parser', element.attr('ng-model'), 'viewValue', viewValue); - return viewValue ? trueValue : falseValue; - }); - // modelValue -> $formatters -> viewValue - controller.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - return angular.equals(modelValue, trueValue); - }); - // Fix rendering for exotic values - scope.$watch(attr.ngModel, function(newValue, oldValue) { - controller.$render(); - }); - } - - // model -> view - controller.$render = function () { - // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); - var isActive = angular.equals(controller.$modelValue, trueValue); - $$rAF(function() { - if(isInput) element[0].checked = isActive; - activeElement.toggleClass(options.activeClass, isActive); - }); - }; - - // view -> model - element.bind(options.toggleEvent, function() { - scope.$apply(function () { - // console.warn('!click', element.attr('ng-model'), 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue, 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue); - if(!isInput) { - controller.$setViewValue(!activeElement.hasClass('active')); - } - if(!hasExoticValues) { - controller.$render(); - } - }); - }); + function isActive(value) { + var activeItems = self.$targets.$active; + return activeItems.indexOf(value) === -1 ? false : true; + } - } + function deactivateItem(value) { + var index = self.$targets.$active.indexOf(value); + if (index !== -1) { + self.$targets.$active.splice(index, 1); + } + } - }; + function activateItem(value) { + if (!self.$options.allowMultiple) { + // remove current selected item + self.$targets.$active.splice(0, 1); + } - }]) + if (self.$targets.$active.indexOf(value) === -1) { + self.$targets.$active.push(value); + } + } - .directive('bsRadioGroup', function() { + }; - return { - restrict: 'A', - require: 'ngModel', - compile: function postLink(element, attr) { - element.attr('data-toggle', 'buttons'); - element.removeAttr('ng-model'); - var children = element[0].querySelectorAll('input[type="radio"]'); - angular.forEach(children, function(child) { - angular.element(child).attr('bs-radio', ''); - angular.element(child).attr('ng-model', attr.ngModel); - }); - } + this.$get = function () { + var $collapse = {}; + $collapse.defaults = defaults; + $collapse.controller = controller; + return $collapse; + }; - }; + }) + + .directive('bsCollapse', ["$window", "$animate", "$collapse", function ($window, $animate, $collapse) { + + var defaults = $collapse.defaults; + + return { + require: ['?ngModel', 'bsCollapse'], + controller: ['$scope', '$element', '$attrs', $collapse.controller], + link: function postLink(scope, element, attrs, controllers) { + + var ngModelCtrl = controllers[0]; + var bsCollapseCtrl = controllers[1]; + + if (ngModelCtrl) { + + // Update the modelValue following + bsCollapseCtrl.$viewChangeListeners.push(function () { + ngModelCtrl.$setViewValue(bsCollapseCtrl.$activeIndexes()); + }); + + // modelValue -> $formatters -> viewValue + ngModelCtrl.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + if (angular.isArray(modelValue)) { + // model value is an array, so just replace + // the active items directly + bsCollapseCtrl.$setActive(modelValue); + } + else { + var activeIndexes = bsCollapseCtrl.$activeIndexes(); + + if (angular.isArray(activeIndexes)) { + // we have an array of selected indexes + if (activeIndexes.indexOf(modelValue * 1) === -1) { + // item with modelValue index is not active + bsCollapseCtrl.$setActive(modelValue * 1); + } + } + else if (activeIndexes !== modelValue * 1) { + bsCollapseCtrl.$setActive(modelValue * 1); + } + } + return modelValue; + }); + + } - }) + } + }; - .directive('bsRadio', ["$button", "$$rAF", function($button, $$rAF) { + }]) - var defaults = $button.defaults; - var constantValueRegExp = /^(true|false|\d+)$/; + .directive('bsCollapseToggle', function () { - return { - restrict: 'A', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { + return { + require: ['^?ngModel', '^bsCollapse'], + link: function postLink(scope, element, attrs, controllers) { - var options = defaults; + var ngModelCtrl = controllers[0]; + var bsCollapseCtrl = controllers[1]; - // Support `label > input[type="radio"]` markup - var isInput = element[0].nodeName === 'INPUT'; - var activeElement = isInput ? element.parent() : element; + // Add base attr + element.attr('data-toggle', 'collapse'); - var value = constantValueRegExp.test(attr.value) ? scope.$eval(attr.value) : attr.value; + // Push pane to parent bsCollapse controller + bsCollapseCtrl.$registerToggle(element); - // model -> view - controller.$render = function () { - // console.warn('$render', element.attr('value'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); - var isActive = angular.equals(controller.$modelValue, value); - $$rAF(function() { - if(isInput) element[0].checked = isActive; - activeElement.toggleClass(options.activeClass, isActive); - }); - }; + // remove toggle from collapse controller when toggle is destroyed + scope.$on('$destroy', function () { + bsCollapseCtrl.$unregisterToggle(element); + }); - // view -> model - element.bind(options.toggleEvent, function() { - scope.$apply(function () { - // console.warn('!click', element.attr('value'), 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue, 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue); - controller.$setViewValue(value); - controller.$render(); - }); - }); + element.on('click', function () { + var index = attrs.bsCollapseToggle || bsCollapseCtrl.$toggles.indexOf(element); + bsCollapseCtrl.$setActive(index * 1); + scope.$apply(); + }); - } + } + }; - }; + }) - }]); + .directive('bsCollapseTarget', ["$animate", function ($animate) { -// Source: collapse.js -angular.module('mgcrea.ngStrap.collapse', []) - - .provider('$collapse', function() { - - var defaults = this.defaults = { - animation: 'am-collapse', - disallowToggle: false, - activeClass: 'in', - startCollapsed: false, - allowMultiple: false - }; - - var controller = this.controller = function($scope, $element, $attrs) { - var self = this; - - // Attributes options - self.$options = angular.copy(defaults); - angular.forEach(['animation', 'disallowToggle', 'activeClass', 'startCollapsed', 'allowMultiple'], function (key) { - if(angular.isDefined($attrs[key])) self.$options[key] = $attrs[key]; - }); - - self.$toggles = []; - self.$targets = []; - - self.$viewChangeListeners = []; - - self.$registerToggle = function(element) { - self.$toggles.push(element); - }; - self.$registerTarget = function(element) { - self.$targets.push(element); - }; - - self.$unregisterToggle = function(element) { - var index = self.$toggles.indexOf(element); - // remove toggle from $toggles array - self.$toggles.splice(index, 1); - }; - self.$unregisterTarget = function(element) { - var index = self.$targets.indexOf(element); - - // remove element from $targets array - self.$targets.splice(index, 1); - - if (self.$options.allowMultiple) { - // remove target index from $active array values - deactivateItem(element); - } - - // fix active item indexes - fixActiveItemIndexes(index); - - self.$viewChangeListeners.forEach(function(fn) { - fn(); - }); - }; - - // use array to store all the currently open panels - self.$targets.$active = !self.$options.startCollapsed ? [0] : []; - self.$setActive = $scope.$setActive = function(value) { - if(angular.isArray(value)) { - self.$targets.$active = angular.copy(value); - } - else if(!self.$options.disallowToggle) { - // toogle element active status - isActive(value) ? deactivateItem(value) : activateItem(value); - } else { - activateItem(value); - } - - self.$viewChangeListeners.forEach(function(fn) { - fn(); - }); - }; - - self.$activeIndexes = function() { - return self.$options.allowMultiple ? self.$targets.$active : - self.$targets.$active.length === 1 ? self.$targets.$active[0] : -1; - }; - - function fixActiveItemIndexes(index) { - // item with index was removed, so we - // need to adjust other items index values - var activeIndexes = self.$targets.$active; - for(var i = 0; i < activeIndexes.length; i++) { - if (index < activeIndexes[i]) { - activeIndexes[i] = activeIndexes[i] - 1; - } - - // the last item is active, so we need to - // adjust its index - if (activeIndexes[i] === self.$targets.length) { - activeIndexes[i] = self.$targets.length - 1; - } - } - } - - function isActive(value) { - var activeItems = self.$targets.$active; - return activeItems.indexOf(value) === -1 ? false : true; - } - - function deactivateItem(value) { - var index = self.$targets.$active.indexOf(value); - if (index !== -1) { - self.$targets.$active.splice(index, 1); - } - } - - function activateItem(value) { - if (!self.$options.allowMultiple) { - // remove current selected item - self.$targets.$active.splice(0, 1); - } - - if (self.$targets.$active.indexOf(value) === -1) { - self.$targets.$active.push(value); - } - } - - }; - - this.$get = function() { - var $collapse = {}; - $collapse.defaults = defaults; - $collapse.controller = controller; - return $collapse; - }; - - }) - - .directive('bsCollapse', ["$window", "$animate", "$collapse", function($window, $animate, $collapse) { - - var defaults = $collapse.defaults; - - return { - require: ['?ngModel', 'bsCollapse'], - controller: ['$scope', '$element', '$attrs', $collapse.controller], - link: function postLink(scope, element, attrs, controllers) { - - var ngModelCtrl = controllers[0]; - var bsCollapseCtrl = controllers[1]; - - if(ngModelCtrl) { - - // Update the modelValue following - bsCollapseCtrl.$viewChangeListeners.push(function() { - ngModelCtrl.$setViewValue(bsCollapseCtrl.$activeIndexes()); - }); - - // modelValue -> $formatters -> viewValue - ngModelCtrl.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - if (angular.isArray(modelValue)) { - // model value is an array, so just replace - // the active items directly - bsCollapseCtrl.$setActive(modelValue); - } - else { - var activeIndexes = bsCollapseCtrl.$activeIndexes(); - - if (angular.isArray(activeIndexes)) { - // we have an array of selected indexes - if (activeIndexes.indexOf(modelValue * 1) === -1) { - // item with modelValue index is not active - bsCollapseCtrl.$setActive(modelValue * 1); - } - } - else if (activeIndexes !== modelValue * 1) { - bsCollapseCtrl.$setActive(modelValue * 1); - } - } - return modelValue; - }); + return { + require: ['^?ngModel', '^bsCollapse'], + // scope: true, + link: function postLink(scope, element, attrs, controllers) { - } + var ngModelCtrl = controllers[0]; + var bsCollapseCtrl = controllers[1]; - } - }; + // Add base class + element.addClass('collapse'); - }]) + // Add animation class + if (bsCollapseCtrl.$options.animation) { + element.addClass(bsCollapseCtrl.$options.animation); + } - .directive('bsCollapseToggle', function() { + // Push pane to parent bsCollapse controller + bsCollapseCtrl.$registerTarget(element); - return { - require: ['^?ngModel', '^bsCollapse'], - link: function postLink(scope, element, attrs, controllers) { + // remove pane target from collapse controller when target is destroyed + scope.$on('$destroy', function () { + bsCollapseCtrl.$unregisterTarget(element); + }); - var ngModelCtrl = controllers[0]; - var bsCollapseCtrl = controllers[1]; + function render() { + var index = bsCollapseCtrl.$targets.indexOf(element); + var active = bsCollapseCtrl.$activeIndexes(); + var action = 'removeClass'; + if (angular.isArray(active)) { + if (active.indexOf(index) !== -1) { + action = 'addClass'; + } + } + else if (index === active) { + action = 'addClass'; + } - // Add base attr - element.attr('data-toggle', 'collapse'); + $animate[action](element, bsCollapseCtrl.$options.activeClass); + } - // Push pane to parent bsCollapse controller - bsCollapseCtrl.$registerToggle(element); + bsCollapseCtrl.$viewChangeListeners.push(function () { + render(); + }); + render(); - // remove toggle from collapse controller when toggle is destroyed - scope.$on('$destroy', function() { - bsCollapseCtrl.$unregisterToggle(element); - }); + } + }; - element.on('click', function() { - var index = attrs.bsCollapseToggle || bsCollapseCtrl.$toggles.indexOf(element); - bsCollapseCtrl.$setActive(index * 1); - scope.$apply(); - }); + }]); - } - }; +// Source: datepicker.js + angular.module('mgcrea.ngStrap.datepicker', [ + 'mgcrea.ngStrap.helpers.dateParser', + 'mgcrea.ngStrap.helpers.dateFormatter', + 'mgcrea.ngStrap.tooltip']) + + .provider('$datepicker', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'datepicker', + placement: 'bottom-left', + template: 'datepicker/datepicker.tpl.html', + trigger: 'focus', + container: false, + keyboard: true, + html: false, + delay: 0, + // lang: $locale.id, + useNative: false, + dateType: 'date', + dateFormat: 'shortDate', + modelDateFormat: null, + dayFormat: 'dd', + monthFormat: 'MMM', + yearFormat: 'yyyy', + monthTitleFormat: 'MMMM yyyy', + yearTitleFormat: 'yyyy', + strictFormat: false, + autoclose: false, + minDate: -Infinity, + maxDate: +Infinity, + startView: 0, + minView: 0, + startWeek: 0, + daysOfWeekDisabled: '', + iconLeft: 'glyphicon glyphicon-chevron-left', + iconRight: 'glyphicon glyphicon-chevron-right' + }; - }) + this.$get = ["$window", "$document", "$rootScope", "$sce", "$dateFormatter", "datepickerViews", "$tooltip", "$timeout", function ($window, $document, $rootScope, $sce, $dateFormatter, datepickerViews, $tooltip, $timeout) { + + var bodyEl = angular.element($window.document.body); + var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + var isTouch = ('createTouch' in $window.document) && isNative; + if (!defaults.lang) defaults.lang = $dateFormatter.getDefaultLocale(); + + function DatepickerFactory(element, controller, config) { + + var $datepicker = $tooltip(element, angular.extend({}, defaults, config)); + var parentScope = config.scope; + var options = $datepicker.$options; + var scope = $datepicker.$scope; + if (options.startView) options.startView -= options.minView; + + // View vars + + var pickerViews = datepickerViews($datepicker); + $datepicker.$views = pickerViews.views; + var viewDate = pickerViews.viewDate; + scope.$mode = options.startView; + scope.$iconLeft = options.iconLeft; + scope.$iconRight = options.iconRight; + var $picker = $datepicker.$views[scope.$mode]; + + // Scope methods + + scope.$select = function (date) { + $datepicker.select(date); + }; + scope.$selectPane = function (value) { + $datepicker.$selectPane(value); + }; + scope.$toggleMode = function () { + $datepicker.setMode((scope.$mode + 1) % $datepicker.$views.length); + }; + + // Public methods + + $datepicker.update = function (date) { + // console.warn('$datepicker.update() newValue=%o', date); + if (angular.isDate(date) && !isNaN(date.getTime())) { + $datepicker.$date = date; + $picker.update.call($picker, date); + } + // Build only if pristine + $datepicker.$build(true); + }; + + $datepicker.updateDisabledDates = function (dateRanges) { + options.disabledDateRanges = dateRanges; + for (var i = 0, l = scope.rows.length; i < l; i++) { + angular.forEach(scope.rows[i], $datepicker.$setDisabledEl); + } + }; + + $datepicker.select = function (date, keep) { + // console.warn('$datepicker.select', date, scope.$mode); + if (!angular.isDate(controller.$dateValue)) controller.$dateValue = new Date(date); + if (!scope.$mode || keep) { + controller.$setViewValue(angular.copy(date)); + controller.$render(); + if (options.autoclose && !keep) { + $timeout(function () { + $datepicker.hide(true); + }); + } + } else { + angular.extend(viewDate, {year: date.getFullYear(), month: date.getMonth(), date: date.getDate()}); + $datepicker.setMode(scope.$mode - 1); + $datepicker.$build(); + } + }; + + $datepicker.setMode = function (mode) { + // console.warn('$datepicker.setMode', mode); + scope.$mode = mode; + $picker = $datepicker.$views[scope.$mode]; + $datepicker.$build(); + }; + + // Protected methods + + $datepicker.$build = function (pristine) { + // console.warn('$datepicker.$build() viewDate=%o', viewDate); + if (pristine === true && $picker.built) return; + if (pristine === false && !$picker.built) return; + $picker.build.call($picker); + }; + + $datepicker.$updateSelected = function () { + for (var i = 0, l = scope.rows.length; i < l; i++) { + angular.forEach(scope.rows[i], updateSelected); + } + }; + + $datepicker.$isSelected = function (date) { + return $picker.isSelected(date); + }; + + $datepicker.$setDisabledEl = function (el) { + el.disabled = $picker.isDisabled(el.date); + }; + + $datepicker.$selectPane = function (value) { + var steps = $picker.steps; + // set targetDate to first day of month to avoid problems with + // date values rollover. This assumes the viewDate does not + // depend on the day of the month + var targetDate = new Date(Date.UTC(viewDate.year + ((steps.year || 0) * value), viewDate.month + ((steps.month || 0) * value), 1)); + angular.extend(viewDate, { + year: targetDate.getUTCFullYear(), + month: targetDate.getUTCMonth(), + date: targetDate.getUTCDate() + }); + $datepicker.$build(); + }; + + $datepicker.$onMouseDown = function (evt) { + // Prevent blur on mousedown on .dropdown-menu + evt.preventDefault(); + evt.stopPropagation(); + // Emulate click for mobile devices + if (isTouch) { + var targetEl = angular.element(evt.target); + if (targetEl[0].nodeName.toLowerCase() !== 'button') { + targetEl = targetEl.parent(); + } + targetEl.triggerHandler('click'); + } + }; + + $datepicker.$onKeyDown = function (evt) { + if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; + evt.preventDefault(); + evt.stopPropagation(); + + if (evt.keyCode === 13) { + if (!scope.$mode) { + return $datepicker.hide(true); + } else { + return scope.$apply(function () { + $datepicker.setMode(scope.$mode - 1); + }); + } + } + + // Navigate with keyboard + $picker.onKeyDown(evt); + parentScope.$digest(); + }; + + // Private + + function updateSelected(el) { + el.selected = $datepicker.$isSelected(el.date); + } + + function focusElement() { + element[0].focus(); + } + + // Overrides + + var _init = $datepicker.init; + $datepicker.init = function () { + if (isNative && options.useNative) { + element.prop('type', 'date'); + element.css('-webkit-appearance', 'textfield'); + return; + } else if (isTouch) { + element.prop('type', 'text'); + element.attr('readonly', 'true'); + element.on('click', focusElement); + } + _init(); + }; + + var _destroy = $datepicker.destroy; + $datepicker.destroy = function () { + if (isNative && options.useNative) { + element.off('click', focusElement); + } + _destroy(); + }; + + var _show = $datepicker.show; + $datepicker.show = function () { + _show(); + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + // if $datepicker is no longer showing, don't setup events + if (!$datepicker.$isShown) return; + $datepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $datepicker.$onMouseDown); + if (options.keyboard) { + element.on('keydown', $datepicker.$onKeyDown); + } + }, 0, false); + }; + + var _hide = $datepicker.hide; + $datepicker.hide = function (blur) { + if (!$datepicker.$isShown) return; + $datepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $datepicker.$onMouseDown); + if (options.keyboard) { + element.off('keydown', $datepicker.$onKeyDown); + } + _hide(blur); + }; + + return $datepicker; - .directive('bsCollapseTarget', ["$animate", function($animate) { + } - return { - require: ['^?ngModel', '^bsCollapse'], - // scope: true, - link: function postLink(scope, element, attrs, controllers) { + DatepickerFactory.defaults = defaults; + return DatepickerFactory; + + }]; + + }) + + .directive('bsDatepicker', ["$window", "$parse", "$q", "$dateFormatter", "$dateParser", "$datepicker", function ($window, $parse, $q, $dateFormatter, $dateParser, $datepicker) { + + var defaults = $datepicker.defaults; + var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + + return { + restrict: 'EAC', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { + + // Directive options + var options = {scope: scope, controller: controller}; + angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'dateType', 'dateFormat', 'modelDateFormat', 'dayFormat', 'strictFormat', 'startWeek', 'startDate', 'useNative', 'lang', 'startView', 'minView', 'iconLeft', 'iconRight', 'daysOfWeekDisabled', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // Visibility binding support + attr.bsShow && scope.$watch(attr.bsShow, function (newValue, oldValue) { + if (!datepicker || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(datepicker),?/i); + newValue === true ? datepicker.show() : datepicker.hide(); + }); + + // Initialize datepicker + var datepicker = $datepicker(element, controller, options); + options = datepicker.$options; + // Set expected iOS format + if (isNative && options.useNative) options.dateFormat = 'yyyy-MM-dd'; + + var lang = options.lang; + + var formatDate = function (date, format) { + return $dateFormatter.formatDate(date, format, lang); + }; + + var dateParser = $dateParser({format: options.dateFormat, lang: lang, strict: options.strictFormat}); + + // Observe attributes for changes + angular.forEach(['minDate', 'maxDate'], function (key) { + // console.warn('attr.$observe(%s)', key, attr[key]); + angular.isDefined(attr[key]) && attr.$observe(key, function (newValue) { + // console.warn('attr.$observe(%s)=%o', key, newValue); + datepicker.$options[key] = dateParser.getDateForAttribute(key, newValue); + // Build only if dirty + !isNaN(datepicker.$options[key]) && datepicker.$build(false); + validateAgainstMinMaxDate(controller.$dateValue); + }); + }); + + // Watch model for changes + scope.$watch(attr.ngModel, function (newValue, oldValue) { + datepicker.update(controller.$dateValue); + }, true); + + // Normalize undefined/null/empty array, + // so that we don't treat changing from undefined->null as a change. + function normalizeDateRanges(ranges) { + if (!ranges || !ranges.length) return null; + return ranges; + } + + if (angular.isDefined(attr.disabledDates)) { + scope.$watch(attr.disabledDates, function (disabledRanges, previousValue) { + disabledRanges = normalizeDateRanges(disabledRanges); + previousValue = normalizeDateRanges(previousValue); + + if (disabledRanges) { + datepicker.updateDisabledDates(disabledRanges); + } + }); + } + + function validateAgainstMinMaxDate(parsedDate) { + if (!angular.isDate(parsedDate)) return; + var isMinValid = isNaN(datepicker.$options.minDate) || parsedDate.getTime() >= datepicker.$options.minDate; + var isMaxValid = isNaN(datepicker.$options.maxDate) || parsedDate.getTime() <= datepicker.$options.maxDate; + var isValid = isMinValid && isMaxValid; + controller.$setValidity('date', isValid); + controller.$setValidity('min', isMinValid); + controller.$setValidity('max', isMaxValid); + // Only update the model when we have a valid date + if (isValid) controller.$dateValue = parsedDate; + } + + // viewValue -> $parsers -> modelValue + controller.$parsers.unshift(function (viewValue) { + // console.warn('$parser("%s"): viewValue=%o', element.attr('ng-model'), viewValue); + // Null values should correctly reset the model value & validity + if (!viewValue) { + controller.$setValidity('date', true); + // BREAKING CHANGE: + // return null (not undefined) when input value is empty, so angularjs 1.3 + // ngModelController can go ahead and run validators, like ngRequired + return null; + } + var parsedDate = dateParser.parse(viewValue, controller.$dateValue); + if (!parsedDate || isNaN(parsedDate.getTime())) { + controller.$setValidity('date', false); + // return undefined, causes ngModelController to + // invalidate model value + return; + } else { + validateAgainstMinMaxDate(parsedDate); + } + if (options.dateType === 'string') { + return formatDate(parsedDate, options.modelDateFormat || options.dateFormat); + } else if (options.dateType === 'number') { + return controller.$dateValue.getTime(); + } else if (options.dateType === 'unix') { + return controller.$dateValue.getTime() / 1000; + } else if (options.dateType === 'iso') { + return controller.$dateValue.toISOString(); + } else { + return new Date(controller.$dateValue); + } + }); + + // modelValue -> $formatters -> viewValue + controller.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + var date; + if (angular.isUndefined(modelValue) || modelValue === null) { + date = NaN; + } else if (angular.isDate(modelValue)) { + date = modelValue; + } else if (options.dateType === 'string') { + date = dateParser.parse(modelValue, null, options.modelDateFormat); + } else if (options.dateType === 'unix') { + date = new Date(modelValue * 1000); + } else { + date = new Date(modelValue); + } + // Setup default value? + // if(isNaN(date.getTime())) { + // var today = new Date(); + // date = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0); + // } + controller.$dateValue = date; + return getDateFormattedString(); + }); + + // viewValue -> element + controller.$render = function () { + // console.warn('$render("%s"): viewValue=%o', element.attr('ng-model'), controller.$viewValue); + element.val(getDateFormattedString()); + }; + + function getDateFormattedString() { + return !controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : formatDate(controller.$dateValue, options.dateFormat); + } + + // Garbage collection + scope.$on('$destroy', function () { + if (datepicker) datepicker.destroy(); + options = null; + datepicker = null; + }); - var ngModelCtrl = controllers[0]; - var bsCollapseCtrl = controllers[1]; + } + }; - // Add base class - element.addClass('collapse'); + }]) - // Add animation class - if(bsCollapseCtrl.$options.animation) { - element.addClass(bsCollapseCtrl.$options.animation); - } + .provider('datepickerViews', function () { - // Push pane to parent bsCollapse controller - bsCollapseCtrl.$registerTarget(element); + var defaults = this.defaults = { + dayFormat: 'dd', + daySplit: 7 + }; - // remove pane target from collapse controller when target is destroyed - scope.$on('$destroy', function() { - bsCollapseCtrl.$unregisterTarget(element); - }); + // Split array into smaller arrays + function split(arr, size) { + var arrays = []; + while (arr.length > 0) { + arrays.push(arr.splice(0, size)); + } + return arrays; + } - function render() { - var index = bsCollapseCtrl.$targets.indexOf(element); - var active = bsCollapseCtrl.$activeIndexes(); - var action = 'removeClass'; - if (angular.isArray(active)) { - if (active.indexOf(index) !== -1) { - action = 'addClass'; + // Modulus operator + function mod(n, m) { + return ((n % m) + m) % m; } - } - else if (index === active) { - action = 'addClass'; - } - $animate[action](element, bsCollapseCtrl.$options.activeClass); - } + this.$get = ["$dateFormatter", "$dateParser", "$sce", function ($dateFormatter, $dateParser, $sce) { + + return function (picker) { + + var scope = picker.$scope; + var options = picker.$options; + + var lang = options.lang; + var formatDate = function (date, format) { + return $dateFormatter.formatDate(date, format, lang); + }; + var dateParser = $dateParser({format: options.dateFormat, lang: lang, strict: options.strictFormat}); + + var weekDaysMin = $dateFormatter.weekdaysShort(lang); + var weekDaysLabels = weekDaysMin.slice(options.startWeek).concat(weekDaysMin.slice(0, options.startWeek)); + var weekDaysLabelsHtml = $sce.trustAsHtml('' + weekDaysLabels.join('') + ''); + + var startDate = picker.$date || (options.startDate ? dateParser.getDateForAttribute('startDate', options.startDate) : new Date()); + var viewDate = {year: startDate.getFullYear(), month: startDate.getMonth(), date: startDate.getDate()}; + var timezoneOffset = startDate.getTimezoneOffset() * 6e4; + + var views = [{ + format: options.dayFormat, + split: 7, + steps: {month: 1}, + update: function (date, force) { + if (!this.built || force || date.getFullYear() !== viewDate.year || date.getMonth() !== viewDate.month) { + angular.extend(viewDate, { + year: picker.$date.getFullYear(), + month: picker.$date.getMonth(), + date: picker.$date.getDate() + }); + picker.$build(); + } else if (date.getDate() !== viewDate.date) { + viewDate.date = picker.$date.getDate(); + picker.$updateSelected(); + } + }, + build: function () { + var firstDayOfMonth = new Date(viewDate.year, viewDate.month, 1), firstDayOfMonthOffset = firstDayOfMonth.getTimezoneOffset(); + var firstDate = new Date(+firstDayOfMonth - mod(firstDayOfMonth.getDay() - options.startWeek, 7) * 864e5), firstDateOffset = firstDate.getTimezoneOffset(); + var today = new Date().toDateString(); + // Handle daylight time switch + if (firstDateOffset !== firstDayOfMonthOffset) firstDate = new Date(+firstDate + (firstDateOffset - firstDayOfMonthOffset) * 60e3); + var days = [], day; + for (var i = 0; i < 42; i++) { // < 7 * 6 + day = dateParser.daylightSavingAdjust(new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate() + i)); + days.push({ + date: day, + isToday: day.toDateString() === today, + label: formatDate(day, this.format), + selected: picker.$date && this.isSelected(day), + muted: day.getMonth() !== viewDate.month, + disabled: this.isDisabled(day) + }); + } + scope.title = formatDate(firstDayOfMonth, options.monthTitleFormat); + scope.showLabels = true; + scope.labels = weekDaysLabelsHtml; + scope.rows = split(days, this.split); + this.built = true; + }, + isSelected: function (date) { + return picker.$date && date.getFullYear() === picker.$date.getFullYear() && date.getMonth() === picker.$date.getMonth() && date.getDate() === picker.$date.getDate(); + }, + isDisabled: function (date) { + var time = date.getTime(); + + // Disabled because of min/max date. + if (time < options.minDate || time > options.maxDate) return true; + + // Disabled due to being a disabled day of the week + if (options.daysOfWeekDisabled.indexOf(date.getDay()) !== -1) return true; + + // Disabled because of disabled date range. + if (options.disabledDateRanges) { + for (var i = 0; i < options.disabledDateRanges.length; i++) { + if (time >= options.disabledDateRanges[i].start && time <= options.disabledDateRanges[i].end) { + return true; + } + } + } + + return false; + }, + onKeyDown: function (evt) { + if (!picker.$date) { + return; + } + var actualTime = picker.$date.getTime(); + var newDate; + + if (evt.keyCode === 37) newDate = new Date(actualTime - 1 * 864e5); + else if (evt.keyCode === 38) newDate = new Date(actualTime - 7 * 864e5); + else if (evt.keyCode === 39) newDate = new Date(actualTime + 1 * 864e5); + else if (evt.keyCode === 40) newDate = new Date(actualTime + 7 * 864e5); + + if (!this.isDisabled(newDate)) picker.select(newDate, true); + } + }, { + name: 'month', + format: options.monthFormat, + split: 4, + steps: {year: 1}, + update: function (date, force) { + if (!this.built || date.getFullYear() !== viewDate.year) { + angular.extend(viewDate, { + year: picker.$date.getFullYear(), + month: picker.$date.getMonth(), + date: picker.$date.getDate() + }); + picker.$build(); + } else if (date.getMonth() !== viewDate.month) { + angular.extend(viewDate, {month: picker.$date.getMonth(), date: picker.$date.getDate()}); + picker.$updateSelected(); + } + }, + build: function () { + var firstMonth = new Date(viewDate.year, 0, 1); + var months = [], month; + for (var i = 0; i < 12; i++) { + month = new Date(viewDate.year, i, 1); + months.push({ + date: month, + label: formatDate(month, this.format), + selected: picker.$isSelected(month), + disabled: this.isDisabled(month) + }); + } + scope.title = formatDate(month, options.yearTitleFormat); + scope.showLabels = false; + scope.rows = split(months, this.split); + this.built = true; + }, + isSelected: function (date) { + return picker.$date && date.getFullYear() === picker.$date.getFullYear() && date.getMonth() === picker.$date.getMonth(); + }, + isDisabled: function (date) { + var lastDate = +new Date(date.getFullYear(), date.getMonth() + 1, 0); + return lastDate < options.minDate || date.getTime() > options.maxDate; + }, + onKeyDown: function (evt) { + if (!picker.$date) { + return; + } + var actualMonth = picker.$date.getMonth(); + var newDate = new Date(picker.$date); + + if (evt.keyCode === 37) newDate.setMonth(actualMonth - 1); + else if (evt.keyCode === 38) newDate.setMonth(actualMonth - 4); + else if (evt.keyCode === 39) newDate.setMonth(actualMonth + 1); + else if (evt.keyCode === 40) newDate.setMonth(actualMonth + 4); + + if (!this.isDisabled(newDate)) picker.select(newDate, true); + } + }, { + name: 'year', + format: options.yearFormat, + split: 4, + steps: {year: 12}, + update: function (date, force) { + if (!this.built || force || parseInt(date.getFullYear() / 20, 10) !== parseInt(viewDate.year / 20, 10)) { + angular.extend(viewDate, { + year: picker.$date.getFullYear(), + month: picker.$date.getMonth(), + date: picker.$date.getDate() + }); + picker.$build(); + } else if (date.getFullYear() !== viewDate.year) { + angular.extend(viewDate, { + year: picker.$date.getFullYear(), + month: picker.$date.getMonth(), + date: picker.$date.getDate() + }); + picker.$updateSelected(); + } + }, + build: function () { + var firstYear = viewDate.year - viewDate.year % (this.split * 3); + var years = [], year; + for (var i = 0; i < 12; i++) { + year = new Date(firstYear + i, 0, 1); + years.push({ + date: year, + label: formatDate(year, this.format), + selected: picker.$isSelected(year), + disabled: this.isDisabled(year) + }); + } + scope.title = years[0].label + '-' + years[years.length - 1].label; + scope.showLabels = false; + scope.rows = split(years, this.split); + this.built = true; + }, + isSelected: function (date) { + return picker.$date && date.getFullYear() === picker.$date.getFullYear(); + }, + isDisabled: function (date) { + var lastDate = +new Date(date.getFullYear() + 1, 0, 0); + return lastDate < options.minDate || date.getTime() > options.maxDate; + }, + onKeyDown: function (evt) { + if (!picker.$date) { + return; + } + var actualYear = picker.$date.getFullYear(), + newDate = new Date(picker.$date); + + if (evt.keyCode === 37) newDate.setYear(actualYear - 1); + else if (evt.keyCode === 38) newDate.setYear(actualYear - 4); + else if (evt.keyCode === 39) newDate.setYear(actualYear + 1); + else if (evt.keyCode === 40) newDate.setYear(actualYear + 4); + + if (!this.isDisabled(newDate)) picker.select(newDate, true); + } + }]; + + return { + views: options.minView ? Array.prototype.slice.call(views, options.minView) : views, + viewDate: viewDate + }; + + }; + + }]; - bsCollapseCtrl.$viewChangeListeners.push(function() { - render(); }); - render(); - } - }; +// Source: dropdown.js + angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']) + + .provider('$dropdown', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'dropdown', + placement: 'bottom-left', + template: 'dropdown/dropdown.tpl.html', + trigger: 'click', + container: false, + keyboard: true, + html: false, + delay: 0 + }; - }]); + this.$get = ["$window", "$rootScope", "$tooltip", "$timeout", function ($window, $rootScope, $tooltip, $timeout) { -// Source: datepicker.js -angular.module('mgcrea.ngStrap.datepicker', [ - 'mgcrea.ngStrap.helpers.dateParser', - 'mgcrea.ngStrap.helpers.dateFormatter', - 'mgcrea.ngStrap.tooltip']) - - .provider('$datepicker', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'datepicker', - placement: 'bottom-left', - template: 'datepicker/datepicker.tpl.html', - trigger: 'focus', - container: false, - keyboard: true, - html: false, - delay: 0, - // lang: $locale.id, - useNative: false, - dateType: 'date', - dateFormat: 'shortDate', - modelDateFormat: null, - dayFormat: 'dd', - monthFormat: 'MMM', - yearFormat: 'yyyy', - monthTitleFormat: 'MMMM yyyy', - yearTitleFormat: 'yyyy', - strictFormat: false, - autoclose: false, - minDate: -Infinity, - maxDate: +Infinity, - startView: 0, - minView: 0, - startWeek: 0, - daysOfWeekDisabled: '', - iconLeft: 'glyphicon glyphicon-chevron-left', - iconRight: 'glyphicon glyphicon-chevron-right' - }; - - this.$get = ["$window", "$document", "$rootScope", "$sce", "$dateFormatter", "datepickerViews", "$tooltip", "$timeout", function($window, $document, $rootScope, $sce, $dateFormatter, datepickerViews, $tooltip, $timeout) { - - var bodyEl = angular.element($window.document.body); - var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); - var isTouch = ('createTouch' in $window.document) && isNative; - if(!defaults.lang) defaults.lang = $dateFormatter.getDefaultLocale(); - - function DatepickerFactory(element, controller, config) { - - var $datepicker = $tooltip(element, angular.extend({}, defaults, config)); - var parentScope = config.scope; - var options = $datepicker.$options; - var scope = $datepicker.$scope; - if(options.startView) options.startView -= options.minView; - - // View vars - - var pickerViews = datepickerViews($datepicker); - $datepicker.$views = pickerViews.views; - var viewDate = pickerViews.viewDate; - scope.$mode = options.startView; - scope.$iconLeft = options.iconLeft; - scope.$iconRight = options.iconRight; - var $picker = $datepicker.$views[scope.$mode]; - - // Scope methods - - scope.$select = function(date) { - $datepicker.select(date); - }; - scope.$selectPane = function(value) { - $datepicker.$selectPane(value); - }; - scope.$toggleMode = function() { - $datepicker.setMode((scope.$mode + 1) % $datepicker.$views.length); - }; - - // Public methods - - $datepicker.update = function(date) { - // console.warn('$datepicker.update() newValue=%o', date); - if(angular.isDate(date) && !isNaN(date.getTime())) { - $datepicker.$date = date; - $picker.update.call($picker, date); - } - // Build only if pristine - $datepicker.$build(true); - }; - - $datepicker.updateDisabledDates = function(dateRanges) { - options.disabledDateRanges = dateRanges; - for(var i = 0, l = scope.rows.length; i < l; i++) { - angular.forEach(scope.rows[i], $datepicker.$setDisabledEl); - } - }; - - $datepicker.select = function(date, keep) { - // console.warn('$datepicker.select', date, scope.$mode); - if(!angular.isDate(controller.$dateValue)) controller.$dateValue = new Date(date); - if(!scope.$mode || keep) { - controller.$setViewValue(angular.copy(date)); - controller.$render(); - if(options.autoclose && !keep) { - $timeout(function() { $datepicker.hide(true); }); - } - } else { - angular.extend(viewDate, {year: date.getFullYear(), month: date.getMonth(), date: date.getDate()}); - $datepicker.setMode(scope.$mode - 1); - $datepicker.$build(); - } - }; - - $datepicker.setMode = function(mode) { - // console.warn('$datepicker.setMode', mode); - scope.$mode = mode; - $picker = $datepicker.$views[scope.$mode]; - $datepicker.$build(); - }; - - // Protected methods - - $datepicker.$build = function(pristine) { - // console.warn('$datepicker.$build() viewDate=%o', viewDate); - if(pristine === true && $picker.built) return; - if(pristine === false && !$picker.built) return; - $picker.build.call($picker); - }; - - $datepicker.$updateSelected = function() { - for(var i = 0, l = scope.rows.length; i < l; i++) { - angular.forEach(scope.rows[i], updateSelected); - } - }; - - $datepicker.$isSelected = function(date) { - return $picker.isSelected(date); - }; - - $datepicker.$setDisabledEl = function(el) { - el.disabled = $picker.isDisabled(el.date); - }; - - $datepicker.$selectPane = function(value) { - var steps = $picker.steps; - // set targetDate to first day of month to avoid problems with - // date values rollover. This assumes the viewDate does not - // depend on the day of the month - var targetDate = new Date(Date.UTC(viewDate.year + ((steps.year || 0) * value), viewDate.month + ((steps.month || 0) * value), 1)); - angular.extend(viewDate, {year: targetDate.getUTCFullYear(), month: targetDate.getUTCMonth(), date: targetDate.getUTCDate()}); - $datepicker.$build(); - }; - - $datepicker.$onMouseDown = function(evt) { - // Prevent blur on mousedown on .dropdown-menu - evt.preventDefault(); - evt.stopPropagation(); - // Emulate click for mobile devices - if(isTouch) { - var targetEl = angular.element(evt.target); - if(targetEl[0].nodeName.toLowerCase() !== 'button') { - targetEl = targetEl.parent(); - } - targetEl.triggerHandler('click'); - } - }; - - $datepicker.$onKeyDown = function(evt) { - if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; - evt.preventDefault(); - evt.stopPropagation(); - - if(evt.keyCode === 13) { - if(!scope.$mode) { - return $datepicker.hide(true); - } else { - return scope.$apply(function() { $datepicker.setMode(scope.$mode - 1); }); - } - } - - // Navigate with keyboard - $picker.onKeyDown(evt); - parentScope.$digest(); - }; - - // Private - - function updateSelected(el) { - el.selected = $datepicker.$isSelected(el.date); - } - - function focusElement() { - element[0].focus(); - } - - // Overrides - - var _init = $datepicker.init; - $datepicker.init = function() { - if(isNative && options.useNative) { - element.prop('type', 'date'); - element.css('-webkit-appearance', 'textfield'); - return; - } else if(isTouch) { - element.prop('type', 'text'); - element.attr('readonly', 'true'); - element.on('click', focusElement); - } - _init(); - }; - - var _destroy = $datepicker.destroy; - $datepicker.destroy = function() { - if(isNative && options.useNative) { - element.off('click', focusElement); - } - _destroy(); - }; - - var _show = $datepicker.show; - $datepicker.show = function() { - _show(); - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - // if $datepicker is no longer showing, don't setup events - if(!$datepicker.$isShown) return; - $datepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $datepicker.$onMouseDown); - if(options.keyboard) { - element.on('keydown', $datepicker.$onKeyDown); - } - }, 0, false); - }; + var bodyEl = angular.element($window.document.body); + var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; - var _hide = $datepicker.hide; - $datepicker.hide = function(blur) { - if(!$datepicker.$isShown) return; - $datepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $datepicker.$onMouseDown); - if(options.keyboard) { - element.off('keydown', $datepicker.$onKeyDown); - } - _hide(blur); - }; + function DropdownFactory(element, config) { - return $datepicker; + var $dropdown = {}; - } + // Common vars + var options = angular.extend({}, defaults, config); + var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new(); - DatepickerFactory.defaults = defaults; - return DatepickerFactory; + $dropdown = $tooltip(element, options); + var parentEl = element.parent(); - }]; + // Protected methods - }) + $dropdown.$onKeyDown = function (evt) { + if (!/(38|40)/.test(evt.keyCode)) return; + evt.preventDefault(); + evt.stopPropagation(); - .directive('bsDatepicker', ["$window", "$parse", "$q", "$dateFormatter", "$dateParser", "$datepicker", function($window, $parse, $q, $dateFormatter, $dateParser, $datepicker) { + // Retrieve focused index + var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a')); + if (!items.length) return; + var index; + angular.forEach(items, function (el, i) { + if (matchesSelector && matchesSelector.call(el, ':focus')) index = i; + }); - var defaults = $datepicker.defaults; - var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + // Navigate with keyboard + if (evt.keyCode === 38 && index > 0) index--; + else if (evt.keyCode === 40 && index < items.length - 1) index++; + else if (angular.isUndefined(index)) index = 0; + items.eq(index)[0].focus(); - return { - restrict: 'EAC', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { + }; - // Directive options - var options = {scope: scope, controller: controller}; - angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'dateType', 'dateFormat', 'modelDateFormat', 'dayFormat', 'strictFormat', 'startWeek', 'startDate', 'useNative', 'lang', 'startView', 'minView', 'iconLeft', 'iconRight', 'daysOfWeekDisabled', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + // Overrides - // Visibility binding support - attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { - if(!datepicker || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(datepicker),?/i); - newValue === true ? datepicker.show() : datepicker.hide(); - }); + var show = $dropdown.show; + $dropdown.show = function () { + show(); + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown); + bodyEl.on('click', onBodyClick); + }, 0, false); + parentEl.hasClass('dropdown') && parentEl.addClass('open'); + }; - // Initialize datepicker - var datepicker = $datepicker(element, controller, options); - options = datepicker.$options; - // Set expected iOS format - if(isNative && options.useNative) options.dateFormat = 'yyyy-MM-dd'; - - var lang = options.lang; - - var formatDate = function(date, format) { - return $dateFormatter.formatDate(date, format, lang); - }; - - var dateParser = $dateParser({format: options.dateFormat, lang: lang, strict: options.strictFormat}); - - // Observe attributes for changes - angular.forEach(['minDate', 'maxDate'], function(key) { - // console.warn('attr.$observe(%s)', key, attr[key]); - angular.isDefined(attr[key]) && attr.$observe(key, function(newValue) { - // console.warn('attr.$observe(%s)=%o', key, newValue); - datepicker.$options[key] = dateParser.getDateForAttribute(key, newValue); - // Build only if dirty - !isNaN(datepicker.$options[key]) && datepicker.$build(false); - validateAgainstMinMaxDate(controller.$dateValue); - }); - }); + var hide = $dropdown.hide; + $dropdown.hide = function () { + if (!$dropdown.$isShown) return; + options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown); + bodyEl.off('click', onBodyClick); + parentEl.hasClass('dropdown') && parentEl.removeClass('open'); + hide(); + }; - // Watch model for changes - scope.$watch(attr.ngModel, function(newValue, oldValue) { - datepicker.update(controller.$dateValue); - }, true); - - // Normalize undefined/null/empty array, - // so that we don't treat changing from undefined->null as a change. - function normalizeDateRanges(ranges) { - if (!ranges || !ranges.length) return null; - return ranges; - } - - if (angular.isDefined(attr.disabledDates)) { - scope.$watch(attr.disabledDates, function(disabledRanges, previousValue) { - disabledRanges = normalizeDateRanges(disabledRanges); - previousValue = normalizeDateRanges(previousValue); - - if (disabledRanges) { - datepicker.updateDisabledDates(disabledRanges); - } - }); - } - - function validateAgainstMinMaxDate(parsedDate) { - if (!angular.isDate(parsedDate)) return; - var isMinValid = isNaN(datepicker.$options.minDate) || parsedDate.getTime() >= datepicker.$options.minDate; - var isMaxValid = isNaN(datepicker.$options.maxDate) || parsedDate.getTime() <= datepicker.$options.maxDate; - var isValid = isMinValid && isMaxValid; - controller.$setValidity('date', isValid); - controller.$setValidity('min', isMinValid); - controller.$setValidity('max', isMaxValid); - // Only update the model when we have a valid date - if(isValid) controller.$dateValue = parsedDate; - } - - // viewValue -> $parsers -> modelValue - controller.$parsers.unshift(function(viewValue) { - // console.warn('$parser("%s"): viewValue=%o', element.attr('ng-model'), viewValue); - // Null values should correctly reset the model value & validity - if(!viewValue) { - controller.$setValidity('date', true); - // BREAKING CHANGE: - // return null (not undefined) when input value is empty, so angularjs 1.3 - // ngModelController can go ahead and run validators, like ngRequired - return null; - } - var parsedDate = dateParser.parse(viewValue, controller.$dateValue); - if(!parsedDate || isNaN(parsedDate.getTime())) { - controller.$setValidity('date', false); - // return undefined, causes ngModelController to - // invalidate model value - return; - } else { - validateAgainstMinMaxDate(parsedDate); - } - if(options.dateType === 'string') { - return formatDate(parsedDate, options.modelDateFormat || options.dateFormat); - } else if(options.dateType === 'number') { - return controller.$dateValue.getTime(); - } else if(options.dateType === 'unix') { - return controller.$dateValue.getTime() / 1000; - } else if(options.dateType === 'iso') { - return controller.$dateValue.toISOString(); - } else { - return new Date(controller.$dateValue); - } - }); + var destroy = $dropdown.destroy; + $dropdown.destroy = function () { + bodyEl.off('click', onBodyClick); + destroy(); + }; - // modelValue -> $formatters -> viewValue - controller.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - var date; - if(angular.isUndefined(modelValue) || modelValue === null) { - date = NaN; - } else if(angular.isDate(modelValue)) { - date = modelValue; - } else if(options.dateType === 'string') { - date = dateParser.parse(modelValue, null, options.modelDateFormat); - } else if(options.dateType === 'unix') { - date = new Date(modelValue * 1000); - } else { - date = new Date(modelValue); - } - // Setup default value? - // if(isNaN(date.getTime())) { - // var today = new Date(); - // date = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0); - // } - controller.$dateValue = date; - return getDateFormattedString(); - }); + // Private functions - // viewValue -> element - controller.$render = function() { - // console.warn('$render("%s"): viewValue=%o', element.attr('ng-model'), controller.$viewValue); - element.val(getDateFormattedString()); - }; - - function getDateFormattedString() { - return !controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : formatDate(controller.$dateValue, options.dateFormat); - } - - // Garbage collection - scope.$on('$destroy', function() { - if(datepicker) datepicker.destroy(); - options = null; - datepicker = null; - }); + function onBodyClick(evt) { + if (evt.target === element[0]) return; + return evt.target !== element[0] && $dropdown.hide(); + } - } - }; - - }]) - - .provider('datepickerViews', function() { - - var defaults = this.defaults = { - dayFormat: 'dd', - daySplit: 7 - }; - - // Split array into smaller arrays - function split(arr, size) { - var arrays = []; - while(arr.length > 0) { - arrays.push(arr.splice(0, size)); - } - return arrays; - } - - // Modulus operator - function mod(n, m) { - return ((n % m) + m) % m; - } - - this.$get = ["$dateFormatter", "$dateParser", "$sce", function($dateFormatter, $dateParser, $sce) { - - return function(picker) { - - var scope = picker.$scope; - var options = picker.$options; - - var lang = options.lang; - var formatDate = function(date, format) { - return $dateFormatter.formatDate(date, format, lang); - }; - var dateParser = $dateParser({format: options.dateFormat, lang: lang, strict: options.strictFormat}); - - var weekDaysMin = $dateFormatter.weekdaysShort(lang); - var weekDaysLabels = weekDaysMin.slice(options.startWeek).concat(weekDaysMin.slice(0, options.startWeek)); - var weekDaysLabelsHtml = $sce.trustAsHtml('' + weekDaysLabels.join('') + ''); - - var startDate = picker.$date || (options.startDate ? dateParser.getDateForAttribute('startDate', options.startDate) : new Date()); - var viewDate = {year: startDate.getFullYear(), month: startDate.getMonth(), date: startDate.getDate()}; - var timezoneOffset = startDate.getTimezoneOffset() * 6e4; - - var views = [{ - format: options.dayFormat, - split: 7, - steps: { month: 1 }, - update: function(date, force) { - if(!this.built || force || date.getFullYear() !== viewDate.year || date.getMonth() !== viewDate.month) { - angular.extend(viewDate, {year: picker.$date.getFullYear(), month: picker.$date.getMonth(), date: picker.$date.getDate()}); - picker.$build(); - } else if(date.getDate() !== viewDate.date) { - viewDate.date = picker.$date.getDate(); - picker.$updateSelected(); - } - }, - build: function() { - var firstDayOfMonth = new Date(viewDate.year, viewDate.month, 1), firstDayOfMonthOffset = firstDayOfMonth.getTimezoneOffset(); - var firstDate = new Date(+firstDayOfMonth - mod(firstDayOfMonth.getDay() - options.startWeek, 7) * 864e5), firstDateOffset = firstDate.getTimezoneOffset(); - var today = new Date().toDateString(); - // Handle daylight time switch - if(firstDateOffset !== firstDayOfMonthOffset) firstDate = new Date(+firstDate + (firstDateOffset - firstDayOfMonthOffset) * 60e3); - var days = [], day; - for(var i = 0; i < 42; i++) { // < 7 * 6 - day = dateParser.daylightSavingAdjust(new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate() + i)); - days.push({date: day, isToday: day.toDateString() === today, label: formatDate(day, this.format), selected: picker.$date && this.isSelected(day), muted: day.getMonth() !== viewDate.month, disabled: this.isDisabled(day)}); - } - scope.title = formatDate(firstDayOfMonth, options.monthTitleFormat); - scope.showLabels = true; - scope.labels = weekDaysLabelsHtml; - scope.rows = split(days, this.split); - this.built = true; - }, - isSelected: function(date) { - return picker.$date && date.getFullYear() === picker.$date.getFullYear() && date.getMonth() === picker.$date.getMonth() && date.getDate() === picker.$date.getDate(); - }, - isDisabled: function(date) { - var time = date.getTime(); - - // Disabled because of min/max date. - if (time < options.minDate || time > options.maxDate) return true; - - // Disabled due to being a disabled day of the week - if (options.daysOfWeekDisabled.indexOf(date.getDay()) !== -1) return true; - - // Disabled because of disabled date range. - if (options.disabledDateRanges) { - for (var i = 0; i < options.disabledDateRanges.length; i++) { - if (time >= options.disabledDateRanges[i].start && time <= options.disabledDateRanges[i].end) { - return true; - } - } - } - - return false; - }, - onKeyDown: function(evt) { - if (!picker.$date) { - return; - } - var actualTime = picker.$date.getTime(); - var newDate; - - if(evt.keyCode === 37) newDate = new Date(actualTime - 1 * 864e5); - else if(evt.keyCode === 38) newDate = new Date(actualTime - 7 * 864e5); - else if(evt.keyCode === 39) newDate = new Date(actualTime + 1 * 864e5); - else if(evt.keyCode === 40) newDate = new Date(actualTime + 7 * 864e5); - - if (!this.isDisabled(newDate)) picker.select(newDate, true); - } - }, { - name: 'month', - format: options.monthFormat, - split: 4, - steps: { year: 1 }, - update: function(date, force) { - if(!this.built || date.getFullYear() !== viewDate.year) { - angular.extend(viewDate, {year: picker.$date.getFullYear(), month: picker.$date.getMonth(), date: picker.$date.getDate()}); - picker.$build(); - } else if(date.getMonth() !== viewDate.month) { - angular.extend(viewDate, {month: picker.$date.getMonth(), date: picker.$date.getDate()}); - picker.$updateSelected(); - } - }, - build: function() { - var firstMonth = new Date(viewDate.year, 0, 1); - var months = [], month; - for (var i = 0; i < 12; i++) { - month = new Date(viewDate.year, i, 1); - months.push({date: month, label: formatDate(month, this.format), selected: picker.$isSelected(month), disabled: this.isDisabled(month)}); - } - scope.title = formatDate(month, options.yearTitleFormat); - scope.showLabels = false; - scope.rows = split(months, this.split); - this.built = true; - }, - isSelected: function(date) { - return picker.$date && date.getFullYear() === picker.$date.getFullYear() && date.getMonth() === picker.$date.getMonth(); - }, - isDisabled: function(date) { - var lastDate = +new Date(date.getFullYear(), date.getMonth() + 1, 0); - return lastDate < options.minDate || date.getTime() > options.maxDate; - }, - onKeyDown: function(evt) { - if (!picker.$date) { - return; - } - var actualMonth = picker.$date.getMonth(); - var newDate = new Date(picker.$date); - - if(evt.keyCode === 37) newDate.setMonth(actualMonth - 1); - else if(evt.keyCode === 38) newDate.setMonth(actualMonth - 4); - else if(evt.keyCode === 39) newDate.setMonth(actualMonth + 1); - else if(evt.keyCode === 40) newDate.setMonth(actualMonth + 4); - - if (!this.isDisabled(newDate)) picker.select(newDate, true); - } - }, { - name: 'year', - format: options.yearFormat, - split: 4, - steps: { year: 12 }, - update: function(date, force) { - if(!this.built || force || parseInt(date.getFullYear()/20, 10) !== parseInt(viewDate.year/20, 10)) { - angular.extend(viewDate, {year: picker.$date.getFullYear(), month: picker.$date.getMonth(), date: picker.$date.getDate()}); - picker.$build(); - } else if(date.getFullYear() !== viewDate.year) { - angular.extend(viewDate, {year: picker.$date.getFullYear(), month: picker.$date.getMonth(), date: picker.$date.getDate()}); - picker.$updateSelected(); - } - }, - build: function() { - var firstYear = viewDate.year - viewDate.year % (this.split * 3); - var years = [], year; - for (var i = 0; i < 12; i++) { - year = new Date(firstYear + i, 0, 1); - years.push({date: year, label: formatDate(year, this.format), selected: picker.$isSelected(year), disabled: this.isDisabled(year)}); - } - scope.title = years[0].label + '-' + years[years.length - 1].label; - scope.showLabels = false; - scope.rows = split(years, this.split); - this.built = true; - }, - isSelected: function(date) { - return picker.$date && date.getFullYear() === picker.$date.getFullYear(); - }, - isDisabled: function(date) { - var lastDate = +new Date(date.getFullYear() + 1, 0, 0); - return lastDate < options.minDate || date.getTime() > options.maxDate; - }, - onKeyDown: function(evt) { - if (!picker.$date) { - return; - } - var actualYear = picker.$date.getFullYear(), - newDate = new Date(picker.$date); - - if(evt.keyCode === 37) newDate.setYear(actualYear - 1); - else if(evt.keyCode === 38) newDate.setYear(actualYear - 4); - else if(evt.keyCode === 39) newDate.setYear(actualYear + 1); - else if(evt.keyCode === 40) newDate.setYear(actualYear + 4); - - if (!this.isDisabled(newDate)) picker.select(newDate, true); - } - }]; + return $dropdown; - return { - views: options.minView ? Array.prototype.slice.call(views, options.minView) : views, - viewDate: viewDate - }; + } - }; + return DropdownFactory; - }]; + }]; - }); + }) -// Source: dropdown.js -angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']) + .directive('bsDropdown', ["$window", "$sce", "$dropdown", function ($window, $sce, $dropdown) { - .provider('$dropdown', function() { + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr, transclusion) { - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'dropdown', - placement: 'bottom-left', - template: 'dropdown/dropdown.tpl.html', - trigger: 'click', - container: false, - keyboard: true, - html: false, - delay: 0 - }; - - this.$get = ["$window", "$rootScope", "$tooltip", "$timeout", function($window, $rootScope, $tooltip, $timeout) { - - var bodyEl = angular.element($window.document.body); - var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; - - function DropdownFactory(element, config) { - - var $dropdown = {}; - - // Common vars - var options = angular.extend({}, defaults, config); - var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new(); - - $dropdown = $tooltip(element, options); - var parentEl = element.parent(); - - // Protected methods - - $dropdown.$onKeyDown = function(evt) { - if (!/(38|40)/.test(evt.keyCode)) return; - evt.preventDefault(); - evt.stopPropagation(); - - // Retrieve focused index - var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a')); - if(!items.length) return; - var index; - angular.forEach(items, function(el, i) { - if(matchesSelector && matchesSelector.call(el, ':focus')) index = i; - }); - - // Navigate with keyboard - if(evt.keyCode === 38 && index > 0) index--; - else if(evt.keyCode === 40 && index < items.length - 1) index++; - else if(angular.isUndefined(index)) index = 0; - items.eq(index)[0].focus(); - - }; - - // Overrides - - var show = $dropdown.show; - $dropdown.show = function() { - show(); - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown); - bodyEl.on('click', onBodyClick); - }, 0, false); - parentEl.hasClass('dropdown') && parentEl.addClass('open'); - }; - - var hide = $dropdown.hide; - $dropdown.hide = function() { - if(!$dropdown.$isShown) return; - options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown); - bodyEl.off('click', onBodyClick); - parentEl.hasClass('dropdown') && parentEl.removeClass('open'); - hide(); - }; - - var destroy = $dropdown.destroy; - $dropdown.destroy = function() { - bodyEl.off('click', onBodyClick); - destroy(); - }; - - // Private functions - - function onBodyClick(evt) { - if(evt.target === element[0]) return; - return evt.target !== element[0] && $dropdown.hide(); - } - - return $dropdown; - - } - - return DropdownFactory; - - }]; - - }) - - .directive('bsDropdown', ["$window", "$sce", "$dropdown", function($window, $sce, $dropdown) { - - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr, transclusion) { - - // Directive options - var options = {scope: scope}; - angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + // Directive options + var options = {scope: scope}; + angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - // Support scope as an object - attr.bsDropdown && scope.$watch(attr.bsDropdown, function(newValue, oldValue) { - scope.content = newValue; - }, true); + // Support scope as an object + attr.bsDropdown && scope.$watch(attr.bsDropdown, function (newValue, oldValue) { + scope.content = newValue; + }, true); - // Visibility binding support - attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { - if(!dropdown || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(dropdown),?/i); - newValue === true ? dropdown.show() : dropdown.hide(); - }); + // Visibility binding support + attr.bsShow && scope.$watch(attr.bsShow, function (newValue, oldValue) { + if (!dropdown || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(dropdown),?/i); + newValue === true ? dropdown.show() : dropdown.hide(); + }); - // Initialize dropdown - var dropdown = $dropdown(element, options); + // Initialize dropdown + var dropdown = $dropdown(element, options); - // Garbage collection - scope.$on('$destroy', function() { - if (dropdown) dropdown.destroy(); - options = null; - dropdown = null; - }); + // Garbage collection + scope.$on('$destroy', function () { + if (dropdown) dropdown.destroy(); + options = null; + dropdown = null; + }); - } - }; + } + }; - }]); + }]); // Source: date-formatter.js -angular.module('mgcrea.ngStrap.helpers.dateFormatter', []) + angular.module('mgcrea.ngStrap.helpers.dateFormatter', []) - .service('$dateFormatter', ["$locale", "dateFilter", function($locale, dateFilter) { + .service('$dateFormatter', ["$locale", "dateFilter", function ($locale, dateFilter) { - // The unused `lang` arguments are on purpose. The default implementation does not - // use them and it always uses the locale loaded into the `$locale` service. - // Custom implementations might use it, thus allowing different directives to - // have different languages. + // The unused `lang` arguments are on purpose. The default implementation does not + // use them and it always uses the locale loaded into the `$locale` service. + // Custom implementations might use it, thus allowing different directives to + // have different languages. - this.getDefaultLocale = function() { - return $locale.id; - }; + this.getDefaultLocale = function () { + return $locale.id; + }; - // Format is either a data format name, e.g. "shortTime" or "fullDate", or a date format - // Return either the corresponding date format or the given date format. - this.getDatetimeFormat = function(format, lang) { - return $locale.DATETIME_FORMATS[format] || format; - }; + // Format is either a data format name, e.g. "shortTime" or "fullDate", or a date format + // Return either the corresponding date format or the given date format. + this.getDatetimeFormat = function (format, lang) { + return $locale.DATETIME_FORMATS[format] || format; + }; - this.weekdaysShort = function(lang) { - return $locale.DATETIME_FORMATS.SHORTDAY; - }; + this.weekdaysShort = function (lang) { + return $locale.DATETIME_FORMATS.SHORTDAY; + }; - function splitTimeFormat(format) { - return /(h+)([:\.])?(m+)[ ]?(a?)/i.exec(format).slice(1); - } + function splitTimeFormat(format) { + return /(h+)([:\.])?(m+)[ ]?(a?)/i.exec(format).slice(1); + } - // h:mm a => h - this.hoursFormat = function(timeFormat) { - return splitTimeFormat(timeFormat)[0]; - }; + // h:mm a => h + this.hoursFormat = function (timeFormat) { + return splitTimeFormat(timeFormat)[0]; + }; - // h:mm a => mm - this.minutesFormat = function(timeFormat) { - return splitTimeFormat(timeFormat)[2]; - }; + // h:mm a => mm + this.minutesFormat = function (timeFormat) { + return splitTimeFormat(timeFormat)[2]; + }; - // h:mm a => : - this.timeSeparator = function(timeFormat) { - return splitTimeFormat(timeFormat)[1]; - }; + // h:mm a => : + this.timeSeparator = function (timeFormat) { + return splitTimeFormat(timeFormat)[1]; + }; - // h:mm a => true, H.mm => false - this.showAM = function(timeFormat) { - return !!splitTimeFormat(timeFormat)[3]; - }; + // h:mm a => true, H.mm => false + this.showAM = function (timeFormat) { + return !!splitTimeFormat(timeFormat)[3]; + }; - this.formatDate = function(date, format, lang){ - return dateFilter(date, format); - }; + this.formatDate = function (date, format, lang) { + return dateFilter(date, format); + }; - }]); + }]); // Source: date-parser.js -angular.module('mgcrea.ngStrap.helpers.dateParser', []) - -.provider('$dateParser', ["$localeProvider", function($localeProvider) { - - // define a custom ParseDate object to use instead of native Date - // to avoid date values wrapping when setting date component values - function ParseDate() { - this.year = 1970; - this.month = 0; - this.day = 1; - this.hours = 0; - this.minutes = 0; - this.seconds = 0; - this.milliseconds = 0; - } - - ParseDate.prototype.setMilliseconds = function(value) { this.milliseconds = value; }; - ParseDate.prototype.setSeconds = function(value) { this.seconds = value; }; - ParseDate.prototype.setMinutes = function(value) { this.minutes = value; }; - ParseDate.prototype.setHours = function(value) { this.hours = value; }; - ParseDate.prototype.getHours = function() { return this.hours; }; - ParseDate.prototype.setDate = function(value) { this.day = value; }; - ParseDate.prototype.setMonth = function(value) { this.month = value; }; - ParseDate.prototype.setFullYear = function(value) { this.year = value; }; - ParseDate.prototype.fromDate = function(value) { - this.year = value.getFullYear(); - this.month = value.getMonth(); - this.day = value.getDate(); - this.hours = value.getHours(); - this.minutes = value.getMinutes(); - this.seconds = value.getSeconds(); - this.milliseconds = value.getMilliseconds(); - return this; - }; - - ParseDate.prototype.toDate = function() { - return new Date(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds); - }; - - var proto = ParseDate.prototype; - - function noop() { - } - - function isNumeric(n) { - return !isNaN(parseFloat(n)) && isFinite(n); - } - - function indexOfCaseInsensitive(array, value) { - var len = array.length, str=value.toString().toLowerCase(); - for (var i=0; i 12 when midnight changeover, but then cannot generate - * midnight datetime, so jump to 1AM, otherwise reset. - * @param date (Date) the date to check - * @return (Date) the corrected date - * - * __ copied from jquery ui datepicker __ - */ - $dateParser.daylightSavingAdjust = function(date) { - if (!date) { - return null; - } - date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); - return date; - }; - - // Private functions - - function setMapForFormat(format) { - var keys = Object.keys(setFnMap), i; - var map = [], sortedMap = []; - // Map to setFn - var clonedFormat = format; - for(i = 0; i < keys.length; i++) { - if(format.split(keys[i]).length > 1) { - var index = clonedFormat.search(keys[i]); - format = format.split(keys[i]).join(''); - if(setFnMap[keys[i]]) { - map[index] = setFnMap[keys[i]]; + angular.module('mgcrea.ngStrap.helpers.dateParser', []) + + .provider('$dateParser', ["$localeProvider", function ($localeProvider) { + + // define a custom ParseDate object to use instead of native Date + // to avoid date values wrapping when setting date component values + function ParseDate() { + this.year = 1970; + this.month = 0; + this.day = 1; + this.hours = 0; + this.minutes = 0; + this.seconds = 0; + this.milliseconds = 0; } - } - } - // Sort result map - angular.forEach(map, function(v) { - // conditional required since angular.forEach broke around v1.2.21 - // related pr: https://github.com/angular/angular.js/pull/8525 - if(v) sortedMap.push(v); - }); - return sortedMap; - } - function escapeReservedSymbols(text) { - return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]'); - } - - function regExpForFormat(format) { - var keys = Object.keys(regExpMap), i; + ParseDate.prototype.setMilliseconds = function (value) { + this.milliseconds = value; + }; + ParseDate.prototype.setSeconds = function (value) { + this.seconds = value; + }; + ParseDate.prototype.setMinutes = function (value) { + this.minutes = value; + }; + ParseDate.prototype.setHours = function (value) { + this.hours = value; + }; + ParseDate.prototype.getHours = function () { + return this.hours; + }; + ParseDate.prototype.setDate = function (value) { + this.day = value; + }; + ParseDate.prototype.setMonth = function (value) { + this.month = value; + }; + ParseDate.prototype.setFullYear = function (value) { + this.year = value; + }; + ParseDate.prototype.fromDate = function (value) { + this.year = value.getFullYear(); + this.month = value.getMonth(); + this.day = value.getDate(); + this.hours = value.getHours(); + this.minutes = value.getMinutes(); + this.seconds = value.getSeconds(); + this.milliseconds = value.getMilliseconds(); + return this; + }; - var re = format; - // Abstract replaces to avoid collisions - for(i = 0; i < keys.length; i++) { - re = re.split(keys[i]).join('${' + i + '}'); - } - // Replace abstracted values - for(i = 0; i < keys.length; i++) { - re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')'); - } - format = escapeReservedSymbols(format); + ParseDate.prototype.toDate = function () { + return new Date(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds); + }; - return new RegExp('^' + re + '$', ['i']); - } + var proto = ParseDate.prototype; - $dateParser.init(); - return $dateParser; + function noop() { + } - }; + function isNumeric(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + } - return DateParserFactory; + function indexOfCaseInsensitive(array, value) { + var len = array.length, str = value.toString().toLowerCase(); + for (var i = 0; i < len; i++) { + if (array[i].toLowerCase() === str) { + return i; + } + } + return -1; // Return -1 per the "Array.indexOf()" method. + } - }]; + var defaults = this.defaults = { + format: 'shortDate', + strict: false + }; -}]); + this.$get = ["$locale", "dateFilter", function ($locale, dateFilter) { + + var DateParserFactory = function (config) { + + var options = angular.extend({}, defaults, config); + + var $dateParser = {}; + + var regExpMap = { + 'sss': '[0-9]{3}', + 'ss': '[0-5][0-9]', + 's': options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]', + 'mm': '[0-5][0-9]', + 'm': options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]', + 'HH': '[01][0-9]|2[0-3]', + 'H': options.strict ? '1?[0-9]|2[0-3]' : '[01]?[0-9]|2[0-3]', + 'hh': '[0][1-9]|[1][012]', + 'h': options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]', + 'a': 'AM|PM', + 'EEEE': $locale.DATETIME_FORMATS.DAY.join('|'), + 'EEE': $locale.DATETIME_FORMATS.SHORTDAY.join('|'), + 'dd': '0[1-9]|[12][0-9]|3[01]', + 'd': options.strict ? '[1-9]|[1-2][0-9]|3[01]' : '0?[1-9]|[1-2][0-9]|3[01]', + 'MMMM': $locale.DATETIME_FORMATS.MONTH.join('|'), + 'MMM': $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), + 'MM': '0[1-9]|1[012]', + 'M': options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]', + 'yyyy': '[1]{1}[0-9]{3}|[2]{1}[0-9]{3}', + 'yy': '[0-9]{2}', + 'y': options.strict ? '-?(0|[1-9][0-9]{0,3})' : '-?0*[0-9]{1,4}', + }; + + var setFnMap = { + 'sss': proto.setMilliseconds, + 'ss': proto.setSeconds, + 's': proto.setSeconds, + 'mm': proto.setMinutes, + 'm': proto.setMinutes, + 'HH': proto.setHours, + 'H': proto.setHours, + 'hh': proto.setHours, + 'h': proto.setHours, + 'EEEE': noop, + 'EEE': noop, + 'dd': proto.setDate, + 'd': proto.setDate, + 'a': function (value) { + var hours = this.getHours() % 12; + return this.setHours(value.match(/pm/i) ? hours + 12 : hours); + }, + 'MMMM': function (value) { + return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.MONTH, value)); + }, + 'MMM': function (value) { + return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.SHORTMONTH, value)); + }, + 'MM': function (value) { + return this.setMonth(1 * value - 1); + }, + 'M': function (value) { + return this.setMonth(1 * value - 1); + }, + 'yyyy': proto.setFullYear, + 'yy': function (value) { + return this.setFullYear(2000 + 1 * value); + }, + 'y': proto.setFullYear + }; + + var regex, setMap; + + $dateParser.init = function () { + $dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format; + regex = regExpForFormat($dateParser.$format); + setMap = setMapForFormat($dateParser.$format); + }; + + $dateParser.isValid = function (date) { + if (angular.isDate(date)) return !isNaN(date.getTime()); + return regex.test(date); + }; + + $dateParser.parse = function (value, baseDate, format) { + // check for date format special names + if (format) format = $locale.DATETIME_FORMATS[format] || format; + if (angular.isDate(value)) value = dateFilter(value, format || $dateParser.$format); + var formatRegex = format ? regExpForFormat(format) : regex; + var formatSetMap = format ? setMapForFormat(format) : setMap; + var matches = formatRegex.exec(value); + if (!matches) return false; + // use custom ParseDate object to set parsed values + var date = baseDate && !isNaN(baseDate.getTime()) ? new ParseDate().fromDate(baseDate) : new ParseDate().fromDate(new Date(1970, 0, 1, 0)); + for (var i = 0; i < matches.length - 1; i++) { + formatSetMap[i] && formatSetMap[i].call(date, matches[i + 1]); + } + // convert back to native Date object + var newDate = date.toDate(); + + // check new native Date object for day values overflow + if (parseInt(date.day, 10) !== newDate.getDate()) { + return false; + } + + return newDate; + }; + + $dateParser.getDateForAttribute = function (key, value) { + var date; + + if (value === 'today') { + var today = new Date(); + date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (key === 'maxDate' ? 1 : 0), 0, 0, 0, (key === 'minDate' ? 0 : -1)); + } else if (angular.isString(value) && value.match(/^".+"$/)) { // Support {{ dateObj }} + date = new Date(value.substr(1, value.length - 2)); + } else if (isNumeric(value)) { + date = new Date(parseInt(value, 10)); + } else if (angular.isString(value) && 0 === value.length) { // Reset date + date = key === 'minDate' ? -Infinity : +Infinity; + } else { + date = new Date(value); + } + + return date; + }; + + $dateParser.getTimeForAttribute = function (key, value) { + var time; + + if (value === 'now') { + time = new Date().setFullYear(1970, 0, 1); + } else if (angular.isString(value) && value.match(/^".+"$/)) { + time = new Date(value.substr(1, value.length - 2)).setFullYear(1970, 0, 1); + } else if (isNumeric(value)) { + time = new Date(parseInt(value, 10)).setFullYear(1970, 0, 1); + } else if (angular.isString(value) && 0 === value.length) { // Reset time + time = key === 'minTime' ? -Infinity : +Infinity; + } else { + time = $dateParser.parse(value, new Date(1970, 0, 1, 0)); + } + + return time; + }; + + /* Handle switch to/from daylight saving. + * Hours may be non-zero on daylight saving cut-over: + * > 12 when midnight changeover, but then cannot generate + * midnight datetime, so jump to 1AM, otherwise reset. + * @param date (Date) the date to check + * @return (Date) the corrected date + * + * __ copied from jquery ui datepicker __ + */ + $dateParser.daylightSavingAdjust = function (date) { + if (!date) { + return null; + } + date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); + return date; + }; + + // Private functions + + function setMapForFormat(format) { + var keys = Object.keys(setFnMap), i; + var map = [], sortedMap = []; + // Map to setFn + var clonedFormat = format; + for (i = 0; i < keys.length; i++) { + if (format.split(keys[i]).length > 1) { + var index = clonedFormat.search(keys[i]); + format = format.split(keys[i]).join(''); + if (setFnMap[keys[i]]) { + map[index] = setFnMap[keys[i]]; + } + } + } + // Sort result map + angular.forEach(map, function (v) { + // conditional required since angular.forEach broke around v1.2.21 + // related pr: https://github.com/angular/angular.js/pull/8525 + if (v) sortedMap.push(v); + }); + return sortedMap; + } + + function escapeReservedSymbols(text) { + return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]'); + } + + function regExpForFormat(format) { + var keys = Object.keys(regExpMap), i; + + var re = format; + // Abstract replaces to avoid collisions + for (i = 0; i < keys.length; i++) { + re = re.split(keys[i]).join('${' + i + '}'); + } + // Replace abstracted values + for (i = 0; i < keys.length; i++) { + re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')'); + } + format = escapeReservedSymbols(format); + + return new RegExp('^' + re + '$', ['i']); + } + + $dateParser.init(); + return $dateParser; + + }; + + return DateParserFactory; + + }]; + + }]); // Source: debounce.js -angular.module('mgcrea.ngStrap.helpers.debounce', []) + angular.module('mgcrea.ngStrap.helpers.debounce', []) // @source jashkenas/underscore // @url https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L693 -.factory('debounce', ["$timeout", function($timeout) { - return function(func, wait, immediate) { - var timeout = null; - return function() { - var context = this, - args = arguments, - callNow = immediate && !timeout; - if(timeout) { - $timeout.cancel(timeout); - } - timeout = $timeout(function later() { - timeout = null; - if(!immediate) { - func.apply(context, args); - } - }, wait, false); - if(callNow) { - func.apply(context, args); - } - return timeout; - }; - }; -}]) + .factory('debounce', ["$timeout", function ($timeout) { + return function (func, wait, immediate) { + var timeout = null; + return function () { + var context = this, + args = arguments, + callNow = immediate && !timeout; + if (timeout) { + $timeout.cancel(timeout); + } + timeout = $timeout(function later() { + timeout = null; + if (!immediate) { + func.apply(context, args); + } + }, wait, false); + if (callNow) { + func.apply(context, args); + } + return timeout; + }; + }; + }]) // @source jashkenas/underscore // @url https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L661 -.factory('throttle', ["$timeout", function($timeout) { - return function(func, wait, options) { - var timeout = null; - options || (options = {}); - return function() { - var context = this, - args = arguments; - if(!timeout) { - if(options.leading !== false) { - func.apply(context, args); - } - timeout = $timeout(function later() { - timeout = null; - if(options.trailing !== false) { - func.apply(context, args); - } - }, wait, false); - } - }; - }; -}]); + .factory('throttle', ["$timeout", function ($timeout) { + return function (func, wait, options) { + var timeout = null; + options || (options = {}); + return function () { + var context = this, + args = arguments; + if (!timeout) { + if (options.leading !== false) { + func.apply(context, args); + } + timeout = $timeout(function later() { + timeout = null; + if (options.trailing !== false) { + func.apply(context, args); + } + }, wait, false); + } + }; + }; + }]); // Source: dimensions.js -angular.module('mgcrea.ngStrap.helpers.dimensions', []) - - .factory('dimensions', ["$document", "$window", function($document, $window) { - - var jqLite = angular.element; - var fn = {}; - - /** - * Test the element nodeName - * @param element - * @param name - */ - var nodeName = fn.nodeName = function(element, name) { - return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase(); - }; - - /** - * Returns the element computed style - * @param element - * @param prop - * @param extra - */ - fn.css = function(element, prop, extra) { - var value; - if (element.currentStyle) { //IE - value = element.currentStyle[prop]; - } else if (window.getComputedStyle) { - value = window.getComputedStyle(element)[prop]; - } else { - value = element.style[prop]; - } - return extra === true ? parseFloat(value) || 0 : value; - }; - - /** - * Provides read-only equivalent of jQuery's offset function: - * @required-by bootstrap-tooltip, bootstrap-affix - * @url http://api.jquery.com/offset/ - * @param element - */ - fn.offset = function(element) { - var boxRect = element.getBoundingClientRect(); - var docElement = element.ownerDocument; - return { - width: boxRect.width || element.offsetWidth, - height: boxRect.height || element.offsetHeight, - top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0), - left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0) - }; - }; - - /** - * Provides read-only equivalent of jQuery's position function - * @required-by bootstrap-tooltip, bootstrap-affix - * @url http://api.jquery.com/offset/ - * @param element - */ - fn.position = function(element) { - - var offsetParentRect = {top: 0, left: 0}, - offsetParentElement, - offset; - - // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent - if (fn.css(element, 'position') === 'fixed') { - - // We assume that getBoundingClientRect is available when computed position is fixed - offset = element.getBoundingClientRect(); - - } else { - - // Get *real* offsetParentElement - offsetParentElement = offsetParent(element); - - // Get correct offsets - offset = fn.offset(element); - if (!nodeName(offsetParentElement, 'html')) { - offsetParentRect = fn.offset(offsetParentElement); - } - - // Add offsetParent borders - offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true); - offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true); - } - - // Subtract parent offsets and element margins - return { - width: element.offsetWidth, - height: element.offsetHeight, - top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true), - left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true) - }; - - }; - - /** - * Returns the closest, non-statically positioned offsetParent of a given element - * @required-by fn.position - * @param element - */ - var offsetParent = function offsetParentElement(element) { - var docElement = element.ownerDocument; - var offsetParent = element.offsetParent || docElement; - if(nodeName(offsetParent, '#document')) return docElement.documentElement; - while(offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') { - offsetParent = offsetParent.offsetParent; - } - return offsetParent || docElement.documentElement; - }; - - /** - * Provides equivalent of jQuery's height function - * @required-by bootstrap-affix - * @url http://api.jquery.com/height/ - * @param element - * @param outer - */ - fn.height = function(element, outer) { - var value = element.offsetHeight; - if(outer) { - value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true); - } else { - value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true); - } - return value; - }; - - /** - * Provides equivalent of jQuery's width function - * @required-by bootstrap-affix - * @url http://api.jquery.com/width/ - * @param element - * @param outer - */ - fn.width = function(element, outer) { - var value = element.offsetWidth; - if(outer) { - value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true); - } else { - value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true); - } - return value; - }; - - return fn; - - }]); + angular.module('mgcrea.ngStrap.helpers.dimensions', []) -// Source: parse-options.js -angular.module('mgcrea.ngStrap.helpers.parseOptions', []) + .factory('dimensions', ["$document", "$window", function ($document, $window) { + + var jqLite = angular.element; + var fn = {}; + + /** + * Test the element nodeName + * @param element + * @param name + */ + var nodeName = fn.nodeName = function (element, name) { + return element.nodeName && element.nodeName.toLowerCase() === name.toLowerCase(); + }; + + /** + * Returns the element computed style + * @param element + * @param prop + * @param extra + */ + fn.css = function (element, prop, extra) { + var value; + if (element.currentStyle) { //IE + value = element.currentStyle[prop]; + } else if (window.getComputedStyle) { + value = window.getComputedStyle(element)[prop]; + } else { + value = element.style[prop]; + } + return extra === true ? parseFloat(value) || 0 : value; + }; - .provider('$parseOptions', function() { + /** + * Provides read-only equivalent of jQuery's offset function: + * @required-by bootstrap-tooltip, bootstrap-affix + * @url http://api.jquery.com/offset/ + * @param element + */ + fn.offset = function (element) { + var boxRect = element.getBoundingClientRect(); + var docElement = element.ownerDocument; + return { + width: boxRect.width || element.offsetWidth, + height: boxRect.height || element.offsetHeight, + top: boxRect.top + (window.pageYOffset || docElement.documentElement.scrollTop) - (docElement.documentElement.clientTop || 0), + left: boxRect.left + (window.pageXOffset || docElement.documentElement.scrollLeft) - (docElement.documentElement.clientLeft || 0) + }; + }; - var defaults = this.defaults = { - regexp: /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/ - }; + /** + * Provides read-only equivalent of jQuery's position function + * @required-by bootstrap-tooltip, bootstrap-affix + * @url http://api.jquery.com/offset/ + * @param element + */ + fn.position = function (element) { - this.$get = ["$parse", "$q", function($parse, $q) { + var offsetParentRect = {top: 0, left: 0}, + offsetParentElement, + offset; - function ParseOptionsFactory(attr, config) { + // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent + if (fn.css(element, 'position') === 'fixed') { - var $parseOptions = {}; + // We assume that getBoundingClientRect is available when computed position is fixed + offset = element.getBoundingClientRect(); - // Common vars - var options = angular.extend({}, defaults, config); - $parseOptions.$values = []; + } else { - // Private vars - var match, displayFn, valueName, keyName, groupByFn, valueFn, valuesFn; + // Get *real* offsetParentElement + offsetParentElement = offsetParent(element); - $parseOptions.init = function() { - $parseOptions.$match = match = attr.match(options.regexp); - displayFn = $parse(match[2] || match[1]), - valueName = match[4] || match[6], - keyName = match[5], - groupByFn = $parse(match[3] || ''), - valueFn = $parse(match[2] ? match[1] : valueName), - valuesFn = $parse(match[7]); - }; + // Get correct offsets + offset = fn.offset(element); + if (!nodeName(offsetParentElement, 'html')) { + offsetParentRect = fn.offset(offsetParentElement); + } - $parseOptions.valuesFn = function(scope, controller) { - return $q.when(valuesFn(scope, controller)) - .then(function(values) { - $parseOptions.$values = values ? parseValues(values, scope) : {}; - return $parseOptions.$values; - }); - }; + // Add offsetParent borders + offsetParentRect.top += fn.css(offsetParentElement, 'borderTopWidth', true); + offsetParentRect.left += fn.css(offsetParentElement, 'borderLeftWidth', true); + } - $parseOptions.displayValue = function(modelValue) { - var scope = {}; - scope[valueName] = modelValue; - return displayFn(scope); - }; + // Subtract parent offsets and element margins + return { + width: element.offsetWidth, + height: element.offsetHeight, + top: offset.top - offsetParentRect.top - fn.css(element, 'marginTop', true), + left: offset.left - offsetParentRect.left - fn.css(element, 'marginLeft', true) + }; - // Private functions + }; - function parseValues(values, scope) { - return values.map(function(match, index) { - var locals = {}, label, value; - locals[valueName] = match; - label = displayFn(scope, locals); - value = valueFn(scope, locals); - return {label: label, value: value, index: index}; - }); - } + /** + * Returns the closest, non-statically positioned offsetParent of a given element + * @required-by fn.position + * @param element + */ + var offsetParent = function offsetParentElement(element) { + var docElement = element.ownerDocument; + var offsetParent = element.offsetParent || docElement; + if (nodeName(offsetParent, '#document')) return docElement.documentElement; + while (offsetParent && !nodeName(offsetParent, 'html') && fn.css(offsetParent, 'position') === 'static') { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || docElement.documentElement; + }; - $parseOptions.init(); - return $parseOptions; + /** + * Provides equivalent of jQuery's height function + * @required-by bootstrap-affix + * @url http://api.jquery.com/height/ + * @param element + * @param outer + */ + fn.height = function (element, outer) { + var value = element.offsetHeight; + if (outer) { + value += fn.css(element, 'marginTop', true) + fn.css(element, 'marginBottom', true); + } else { + value -= fn.css(element, 'paddingTop', true) + fn.css(element, 'paddingBottom', true) + fn.css(element, 'borderTopWidth', true) + fn.css(element, 'borderBottomWidth', true); + } + return value; + }; - } + /** + * Provides equivalent of jQuery's width function + * @required-by bootstrap-affix + * @url http://api.jquery.com/width/ + * @param element + * @param outer + */ + fn.width = function (element, outer) { + var value = element.offsetWidth; + if (outer) { + value += fn.css(element, 'marginLeft', true) + fn.css(element, 'marginRight', true); + } else { + value -= fn.css(element, 'paddingLeft', true) + fn.css(element, 'paddingRight', true) + fn.css(element, 'borderLeftWidth', true) + fn.css(element, 'borderRightWidth', true); + } + return value; + }; - return ParseOptionsFactory; + return fn; - }]; + }]); - }); +// Source: parse-options.js + angular.module('mgcrea.ngStrap.helpers.parseOptions', []) + + .provider('$parseOptions', function () { + + var defaults = this.defaults = { + regexp: /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/ + }; + + this.$get = ["$parse", "$q", function ($parse, $q) { + + function ParseOptionsFactory(attr, config) { + + var $parseOptions = {}; + + // Common vars + var options = angular.extend({}, defaults, config); + $parseOptions.$values = []; + + // Private vars + var match, displayFn, valueName, keyName, groupByFn, valueFn, valuesFn; + + $parseOptions.init = function () { + $parseOptions.$match = match = attr.match(options.regexp); + displayFn = $parse(match[2] || match[1]), + valueName = match[4] || match[6], + keyName = match[5], + groupByFn = $parse(match[3] || ''), + valueFn = $parse(match[2] ? match[1] : valueName), + valuesFn = $parse(match[7]); + }; + + $parseOptions.valuesFn = function (scope, controller) { + return $q.when(valuesFn(scope, controller)) + .then(function (values) { + $parseOptions.$values = values ? parseValues(values, scope) : {}; + return $parseOptions.$values; + }); + }; + + $parseOptions.displayValue = function (modelValue) { + var scope = {}; + scope[valueName] = modelValue; + return displayFn(scope); + }; + + // Private functions + + function parseValues(values, scope) { + return values.map(function (match, index) { + var locals = {}, label, value; + locals[valueName] = match; + label = displayFn(scope, locals); + value = valueFn(scope, locals); + return {label: label, value: value, index: index}; + }); + } + + $parseOptions.init(); + return $parseOptions; + + } + + return ParseOptionsFactory; + + }]; + + }); // Source: raf.js -(angular.version.minor < 3 && angular.version.dot < 14) && angular.module('ng') + (angular.version.minor < 3 && angular.version.dot < 14) && angular.module('ng') -.factory('$$rAF', ["$window", "$timeout", function($window, $timeout) { + .factory('$$rAF', ["$window", "$timeout", function ($window, $timeout) { - var requestAnimationFrame = $window.requestAnimationFrame || - $window.webkitRequestAnimationFrame || - $window.mozRequestAnimationFrame; + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame || + $window.mozRequestAnimationFrame; - var cancelAnimationFrame = $window.cancelAnimationFrame || - $window.webkitCancelAnimationFrame || - $window.mozCancelAnimationFrame || - $window.webkitCancelRequestAnimationFrame; + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.mozCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; - var rafSupported = !!requestAnimationFrame; - var raf = rafSupported ? - function(fn) { - var id = requestAnimationFrame(fn); - return function() { - cancelAnimationFrame(id); - }; - } : - function(fn) { - var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 - return function() { - $timeout.cancel(timer); - }; - }; + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported ? + function (fn) { + var id = requestAnimationFrame(fn); + return function () { + cancelAnimationFrame(id); + }; + } : + function (fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function () { + $timeout.cancel(timer); + }; + }; - raf.supported = rafSupported; + raf.supported = rafSupported; - return raf; + return raf; -}]); + }]); // .factory('$$animateReflow', function($$rAF, $document) { @@ -2329,2686 +2401,2714 @@ angular.module('mgcrea.ngStrap.helpers.parseOptions', []) // }); // Source: modal.js -angular.module('mgcrea.ngStrap.modal', ['mgcrea.ngStrap.helpers.dimensions']) - - .provider('$modal', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - backdropAnimation: 'am-fade', - prefixClass: 'modal', - prefixEvent: 'modal', - placement: 'top', - template: 'modal/modal.tpl.html', - contentTemplate: false, - container: false, - element: null, - backdrop: true, - keyboard: true, - html: false, - show: true - }; - - this.$get = ["$window", "$rootScope", "$compile", "$q", "$templateCache", "$http", "$animate", "$timeout", "$sce", "dimensions", function($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $timeout, $sce, dimensions) { - - var forEach = angular.forEach; - var trim = String.prototype.trim; - var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; - var bodyElement = angular.element($window.document.body); - var htmlReplaceRegExp = /ng-bind="/ig; - - function ModalFactory(config) { - - var $modal = {}; - - // Common vars - var options = $modal.$options = angular.extend({}, defaults, config); - $modal.$promise = fetchTemplate(options.template); - var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new(); - if(!options.element && !options.container) { - options.container = 'body'; - } - - // store $id to identify the triggering element in events - // give priority to options.id, otherwise, try to use - // element id if defined - $modal.$id = options.id || options.element && options.element.attr('id') || ''; - - // Support scope as string options - forEach(['title', 'content'], function(key) { - if(options[key]) scope[key] = $sce.trustAsHtml(options[key]); - }); - - // Provide scope helpers - scope.$hide = function() { - scope.$$postDigest(function() { - $modal.hide(); - }); - }; - scope.$show = function() { - scope.$$postDigest(function() { - $modal.show(); - }); - }; - scope.$toggle = function() { - scope.$$postDigest(function() { - $modal.toggle(); - }); - }; - // Publish isShown as a protected var on scope - $modal.$isShown = scope.$isShown = false; - - // Support contentTemplate option - if(options.contentTemplate) { - $modal.$promise = $modal.$promise.then(function(template) { - var templateEl = angular.element(template); - return fetchTemplate(options.contentTemplate) - .then(function(contentTemplate) { - var contentEl = findElement('[ng-bind="content"]', templateEl[0]).removeAttr('ng-bind').html(contentTemplate); - // Drop the default footer as you probably don't want it if you use a custom contentTemplate - if(!config.template) contentEl.next().remove(); - return templateEl[0].outerHTML; - }); - }); - } - - // Fetch, compile then initialize modal - var modalLinker, modalElement; - var backdropElement = angular.element('
          '); - $modal.$promise.then(function(template) { - if(angular.isObject(template)) template = template.data; - if(options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); - template = trim.apply(template); - modalLinker = $compile(template); - $modal.init(); - }); - - $modal.init = function() { - - // Options: show - if(options.show) { - scope.$$postDigest(function() { - $modal.show(); - }); - } - - }; - - $modal.destroy = function() { - - // Remove element - if(modalElement) { - modalElement.remove(); - modalElement = null; - } - if(backdropElement) { - backdropElement.remove(); - backdropElement = null; - } - - // Destroy scope - scope.$destroy(); - - }; - - $modal.show = function() { - if($modal.$isShown) return; - - if(scope.$emit(options.prefixEvent + '.show.before', $modal).defaultPrevented) { - return; - } - var parent, after; - if(angular.isElement(options.container)) { - parent = options.container; - after = options.container[0].lastChild ? angular.element(options.container[0].lastChild) : null; - } else { - if (options.container) { - parent = findElement(options.container); - after = parent[0].lastChild ? angular.element(parent[0].lastChild) : null; - } else { - parent = null; - after = options.element; - } - } - - // Fetch a cloned element linked from template - modalElement = $modal.$element = modalLinker(scope, function(clonedElement, scope) {}); - - // Set the initial positioning. - modalElement.css({display: 'block'}).addClass(options.placement); - - // Options: animation - if(options.animation) { - if(options.backdrop) { - backdropElement.addClass(options.backdropAnimation); - } - modalElement.addClass(options.animation); - } - - if(options.backdrop) { - $animate.enter(backdropElement, bodyElement, null); - } - // Support v1.3+ $animate - // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 - var promise = $animate.enter(modalElement, parent, after, enterAnimateCallback); - if(promise && promise.then) promise.then(enterAnimateCallback); - - $modal.$isShown = scope.$isShown = true; - safeDigest(scope); - // Focus once the enter-animation has started - // Weird PhantomJS bug hack - var el = modalElement[0]; - requestAnimationFrame(function() { - el.focus(); - }); - - bodyElement.addClass(options.prefixClass + '-open'); - if(options.animation) { - bodyElement.addClass(options.prefixClass + '-with-' + options.animation); - } - - // Bind events - if(options.backdrop) { - modalElement.on('click', hideOnBackdropClick); - backdropElement.on('click', hideOnBackdropClick); - backdropElement.on('wheel', preventEventDefault); - } - if(options.keyboard) { - modalElement.on('keyup', $modal.$onKeyUp); - } - }; - - function enterAnimateCallback() { - scope.$emit(options.prefixEvent + '.show', $modal); - } - - $modal.hide = function() { - if(!$modal.$isShown) return; - - if(scope.$emit(options.prefixEvent + '.hide.before', $modal).defaultPrevented) { - return; - } - var promise = $animate.leave(modalElement, leaveAnimateCallback); - // Support v1.3+ $animate - // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 - if(promise && promise.then) promise.then(leaveAnimateCallback); - - if(options.backdrop) { - $animate.leave(backdropElement); - } - $modal.$isShown = scope.$isShown = false; - safeDigest(scope); - - // Unbind events - if(options.backdrop) { - modalElement.off('click', hideOnBackdropClick); - backdropElement.off('click', hideOnBackdropClick); - backdropElement.off('wheel', preventEventDefault); - } - if(options.keyboard) { - modalElement.off('keyup', $modal.$onKeyUp); - } - }; - - function leaveAnimateCallback() { - scope.$emit(options.prefixEvent + '.hide', $modal); - bodyElement.removeClass(options.prefixClass + '-open'); - if(options.animation) { - bodyElement.removeClass(options.prefixClass + '-with-' + options.animation); - } - } - - $modal.toggle = function() { - - $modal.$isShown ? $modal.hide() : $modal.show(); - - }; - - $modal.focus = function() { - modalElement[0].focus(); - }; - - // Protected methods - - $modal.$onKeyUp = function(evt) { - - if (evt.which === 27 && $modal.$isShown) { - $modal.hide(); - evt.stopPropagation(); - } - - }; - - // Private methods - - function hideOnBackdropClick(evt) { - if(evt.target !== evt.currentTarget) return; - options.backdrop === 'static' ? $modal.focus() : $modal.hide(); - } - - function preventEventDefault(evt) { - evt.preventDefault(); - } - - return $modal; - - } - - // Helper functions - - function safeDigest(scope) { - scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest(); - } - - function findElement(query, element) { - return angular.element((element || document).querySelectorAll(query)); - } - - var fetchPromises = {}; - function fetchTemplate(template) { - if(fetchPromises[template]) return fetchPromises[template]; - return (fetchPromises[template] = $q.when($templateCache.get(template) || $http.get(template)) - .then(function(res) { - if(angular.isObject(res)) { - $templateCache.put(template, res.data); - return res.data; - } - return res; - })); - } - - return ModalFactory; - - }]; + angular.module('mgcrea.ngStrap.modal', ['mgcrea.ngStrap.helpers.dimensions']) + + .provider('$modal', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + backdropAnimation: 'am-fade', + prefixClass: 'modal', + prefixEvent: 'modal', + placement: 'top', + template: 'modal/modal.tpl.html', + contentTemplate: false, + container: false, + element: null, + backdrop: true, + keyboard: true, + html: false, + show: true + }; - }) - - .directive('bsModal', ["$window", "$sce", "$modal", function($window, $sce, $modal) { + this.$get = ["$window", "$rootScope", "$compile", "$q", "$templateCache", "$http", "$animate", "$timeout", "$sce", "dimensions", function ($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $timeout, $sce, dimensions) { + + var forEach = angular.forEach; + var trim = String.prototype.trim; + var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; + var bodyElement = angular.element($window.document.body); + var htmlReplaceRegExp = /ng-bind="/ig; + + function ModalFactory(config) { + + var $modal = {}; + + // Common vars + var options = $modal.$options = angular.extend({}, defaults, config); + $modal.$promise = fetchTemplate(options.template); + var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new(); + if (!options.element && !options.container) { + options.container = 'body'; + } + + // store $id to identify the triggering element in events + // give priority to options.id, otherwise, try to use + // element id if defined + $modal.$id = options.id || options.element && options.element.attr('id') || ''; + + // Support scope as string options + forEach(['title', 'content'], function (key) { + if (options[key]) scope[key] = $sce.trustAsHtml(options[key]); + }); + + // Provide scope helpers + scope.$hide = function () { + scope.$$postDigest(function () { + $modal.hide(); + }); + }; + scope.$show = function () { + scope.$$postDigest(function () { + $modal.show(); + }); + }; + scope.$toggle = function () { + scope.$$postDigest(function () { + $modal.toggle(); + }); + }; + // Publish isShown as a protected var on scope + $modal.$isShown = scope.$isShown = false; + + // Support contentTemplate option + if (options.contentTemplate) { + $modal.$promise = $modal.$promise.then(function (template) { + var templateEl = angular.element(template); + return fetchTemplate(options.contentTemplate) + .then(function (contentTemplate) { + var contentEl = findElement('[ng-bind="content"]', templateEl[0]).removeAttr('ng-bind').html(contentTemplate); + // Drop the default footer as you probably don't want it if you use a custom contentTemplate + if (!config.template) contentEl.next().remove(); + return templateEl[0].outerHTML; + }); + }); + } + + // Fetch, compile then initialize modal + var modalLinker, modalElement; + var backdropElement = angular.element('
          '); + $modal.$promise.then(function (template) { + if (angular.isObject(template)) template = template.data; + if (options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); + template = trim.apply(template); + modalLinker = $compile(template); + $modal.init(); + }); + + $modal.init = function () { + + // Options: show + if (options.show) { + scope.$$postDigest(function () { + $modal.show(); + }); + } + + }; + + $modal.destroy = function () { + + // Remove element + if (modalElement) { + modalElement.remove(); + modalElement = null; + } + if (backdropElement) { + backdropElement.remove(); + backdropElement = null; + } + + // Destroy scope + scope.$destroy(); + + }; + + $modal.show = function () { + if ($modal.$isShown) return; + + if (scope.$emit(options.prefixEvent + '.show.before', $modal).defaultPrevented) { + return; + } + var parent, after; + if (angular.isElement(options.container)) { + parent = options.container; + after = options.container[0].lastChild ? angular.element(options.container[0].lastChild) : null; + } else { + if (options.container) { + parent = findElement(options.container); + after = parent[0].lastChild ? angular.element(parent[0].lastChild) : null; + } else { + parent = null; + after = options.element; + } + } + + // Fetch a cloned element linked from template + modalElement = $modal.$element = modalLinker(scope, function (clonedElement, scope) { + }); + + // Set the initial positioning. + modalElement.css({display: 'block'}).addClass(options.placement); + + // Options: animation + if (options.animation) { + if (options.backdrop) { + backdropElement.addClass(options.backdropAnimation); + } + modalElement.addClass(options.animation); + } + + if (options.backdrop) { + $animate.enter(backdropElement, bodyElement, null); + } + // Support v1.3+ $animate + // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 + var promise = $animate.enter(modalElement, parent, after, enterAnimateCallback); + if (promise && promise.then) promise.then(enterAnimateCallback); + + $modal.$isShown = scope.$isShown = true; + safeDigest(scope); + // Focus once the enter-animation has started + // Weird PhantomJS bug hack + var el = modalElement[0]; + requestAnimationFrame(function () { + el.focus(); + }); + + bodyElement.addClass(options.prefixClass + '-open'); + if (options.animation) { + bodyElement.addClass(options.prefixClass + '-with-' + options.animation); + } + + // Bind events + if (options.backdrop) { + modalElement.on('click', hideOnBackdropClick); + backdropElement.on('click', hideOnBackdropClick); + backdropElement.on('wheel', preventEventDefault); + } + if (options.keyboard) { + modalElement.on('keyup', $modal.$onKeyUp); + } + }; + + function enterAnimateCallback() { + scope.$emit(options.prefixEvent + '.show', $modal); + } + + $modal.hide = function () { + if (!$modal.$isShown) return; + + if (scope.$emit(options.prefixEvent + '.hide.before', $modal).defaultPrevented) { + return; + } + var promise = $animate.leave(modalElement, leaveAnimateCallback); + // Support v1.3+ $animate + // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 + if (promise && promise.then) promise.then(leaveAnimateCallback); + + if (options.backdrop) { + $animate.leave(backdropElement); + } + $modal.$isShown = scope.$isShown = false; + safeDigest(scope); + + // Unbind events + if (options.backdrop) { + modalElement.off('click', hideOnBackdropClick); + backdropElement.off('click', hideOnBackdropClick); + backdropElement.off('wheel', preventEventDefault); + } + if (options.keyboard) { + modalElement.off('keyup', $modal.$onKeyUp); + } + }; + + function leaveAnimateCallback() { + scope.$emit(options.prefixEvent + '.hide', $modal); + bodyElement.removeClass(options.prefixClass + '-open'); + if (options.animation) { + bodyElement.removeClass(options.prefixClass + '-with-' + options.animation); + } + } + + $modal.toggle = function () { + + $modal.$isShown ? $modal.hide() : $modal.show(); + + }; + + $modal.focus = function () { + modalElement[0].focus(); + }; + + // Protected methods + + $modal.$onKeyUp = function (evt) { + + if (evt.which === 27 && $modal.$isShown) { + $modal.hide(); + evt.stopPropagation(); + } + + }; + + // Private methods + + function hideOnBackdropClick(evt) { + if (evt.target !== evt.currentTarget) return; + options.backdrop === 'static' ? $modal.focus() : $modal.hide(); + } + + function preventEventDefault(evt) { + evt.preventDefault(); + } + + return $modal; - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr, transclusion) { + } - // Directive options - var options = {scope: scope, element: element, show: false}; - angular.forEach(['template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + // Helper functions - // Support scope as data-attrs - angular.forEach(['title', 'content'], function(key) { - attr[key] && attr.$observe(key, function(newValue, oldValue) { - scope[key] = $sce.trustAsHtml(newValue); - }); - }); + function safeDigest(scope) { + scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest(); + } - // Support scope as an object - attr.bsModal && scope.$watch(attr.bsModal, function(newValue, oldValue) { - if(angular.isObject(newValue)) { - angular.extend(scope, newValue); - } else { - scope.content = newValue; - } - }, true); - - // Initialize modal - var modal = $modal(options); - - // Trigger - element.on(attr.trigger || 'click', modal.toggle); - - // Garbage collection - scope.$on('$destroy', function() { - if (modal) modal.destroy(); - options = null; - modal = null; - }); + function findElement(query, element) { + return angular.element((element || document).querySelectorAll(query)); + } - } - }; + var fetchPromises = {}; + + function fetchTemplate(template) { + if (fetchPromises[template]) return fetchPromises[template]; + return (fetchPromises[template] = $q.when($templateCache.get(template) || $http.get(template)) + .then(function (res) { + if (angular.isObject(res)) { + $templateCache.put(template, res.data); + return res.data; + } + return res; + })); + } - }]); + return ModalFactory; -// Source: navbar.js -angular.module('mgcrea.ngStrap.navbar', []) + }]; - .provider('$navbar', function() { + }) - var defaults = this.defaults = { - activeClass: 'active', - routeAttr: 'data-match-route', - strict: false - }; + .directive('bsModal', ["$window", "$sce", "$modal", function ($window, $sce, $modal) { - this.$get = function() { - return {defaults: defaults}; - }; + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr, transclusion) { - }) + // Directive options + var options = {scope: scope, element: element, show: false}; + angular.forEach(['template', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - .directive('bsNavbar', ["$window", "$location", "$navbar", function($window, $location, $navbar) { + // Support scope as data-attrs + angular.forEach(['title', 'content'], function (key) { + attr[key] && attr.$observe(key, function (newValue, oldValue) { + scope[key] = $sce.trustAsHtml(newValue); + }); + }); - var defaults = $navbar.defaults; + // Support scope as an object + attr.bsModal && scope.$watch(attr.bsModal, function (newValue, oldValue) { + if (angular.isObject(newValue)) { + angular.extend(scope, newValue); + } else { + scope.content = newValue; + } + }, true); - return { - restrict: 'A', - link: function postLink(scope, element, attr, controller) { + // Initialize modal + var modal = $modal(options); - // Directive options - var options = angular.copy(defaults); - angular.forEach(Object.keys(defaults), function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + // Trigger + element.on(attr.trigger || 'click', modal.toggle); - // Watch for the $location - scope.$watch(function() { + // Garbage collection + scope.$on('$destroy', function () { + if (modal) modal.destroy(); + options = null; + modal = null; + }); - return $location.path(); + } + }; - }, function(newValue, oldValue) { + }]); - var liElements = element[0].querySelectorAll('li[' + options.routeAttr + ']'); +// Source: navbar.js + angular.module('mgcrea.ngStrap.navbar', []) - angular.forEach(liElements, function(li) { + .provider('$navbar', function () { - var liElement = angular.element(li); - var pattern = liElement.attr(options.routeAttr).replace('/', '\\/'); - if(options.strict) { - pattern = '^' + pattern + '$'; - } - var regexp = new RegExp(pattern, ['i']); + var defaults = this.defaults = { + activeClass: 'active', + routeAttr: 'data-match-route', + strict: false + }; - if(regexp.test(newValue)) { - liElement.addClass(options.activeClass); - } else { - liElement.removeClass(options.activeClass); - } + this.$get = function () { + return {defaults: defaults}; + }; - }); + }) - }); + .directive('bsNavbar', ["$window", "$location", "$navbar", function ($window, $location, $navbar) { - } + var defaults = $navbar.defaults; - }; + return { + restrict: 'A', + link: function postLink(scope, element, attr, controller) { - }]); + // Directive options + var options = angular.copy(defaults); + angular.forEach(Object.keys(defaults), function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); -// Source: popover.js -angular.module('mgcrea.ngStrap.popover', ['mgcrea.ngStrap.tooltip']) + // Watch for the $location + scope.$watch(function () { - .provider('$popover', function() { + return $location.path(); - var defaults = this.defaults = { - animation: 'am-fade', - customClass: '', - container: false, - target: false, - placement: 'right', - template: 'popover/popover.tpl.html', - contentTemplate: false, - trigger: 'click', - keyboard: true, - html: false, - title: '', - content: '', - delay: 0, - autoClose: false - }; + }, function (newValue, oldValue) { - this.$get = ["$tooltip", function($tooltip) { + var liElements = element[0].querySelectorAll('li[' + options.routeAttr + ']'); - function PopoverFactory(element, config) { + angular.forEach(liElements, function (li) { - // Common vars - var options = angular.extend({}, defaults, config); + var liElement = angular.element(li); + var pattern = liElement.attr(options.routeAttr).replace('/', '\\/'); + if (options.strict) { + pattern = '^' + pattern + '$'; + } + var regexp = new RegExp(pattern, ['i']); - var $popover = $tooltip(element, options); + if (regexp.test(newValue)) { + liElement.addClass(options.activeClass); + } else { + liElement.removeClass(options.activeClass); + } - // Support scope as string options [/*title, */content] - if(options.content) { - $popover.$scope.content = options.content; - } + }); - return $popover; + }); - } + } - return PopoverFactory; + }; - }]; + }]); - }) +// Source: popover.js + angular.module('mgcrea.ngStrap.popover', ['mgcrea.ngStrap.tooltip']) + + .provider('$popover', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + customClass: '', + container: false, + target: false, + placement: 'right', + template: 'popover/popover.tpl.html', + contentTemplate: false, + trigger: 'click', + keyboard: true, + html: false, + title: '', + content: '', + delay: 0, + autoClose: false + }; - .directive('bsPopover', ["$window", "$sce", "$popover", function($window, $sce, $popover) { + this.$get = ["$tooltip", function ($tooltip) { - var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; + function PopoverFactory(element, config) { - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr) { + // Common vars + var options = angular.extend({}, defaults, config); - // Directive options - var options = {scope: scope}; - angular.forEach(['template', 'contentTemplate', 'placement', 'container', 'target', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'customClass', 'autoClose', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + var $popover = $tooltip(element, options); - // Support scope as data-attrs - angular.forEach(['title', 'content'], function(key) { - attr[key] && attr.$observe(key, function(newValue, oldValue) { - scope[key] = $sce.trustAsHtml(newValue); - angular.isDefined(oldValue) && requestAnimationFrame(function() { - popover && popover.$applyPlacement(); - }); - }); - }); + // Support scope as string options [/*title, */content] + if (options.content) { + $popover.$scope.content = options.content; + } - // Support scope as an object - attr.bsPopover && scope.$watch(attr.bsPopover, function(newValue, oldValue) { - if(angular.isObject(newValue)) { - angular.extend(scope, newValue); - } else { - scope.content = newValue; - } - angular.isDefined(oldValue) && requestAnimationFrame(function() { - popover && popover.$applyPlacement(); - }); - }, true); - - // Visibility binding support - attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { - if(!popover || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(popover),?/i); - newValue === true ? popover.show() : popover.hide(); - }); + return $popover; - // Initialize popover - var popover = $popover(element, options); + } - // Garbage collection - scope.$on('$destroy', function() { - if (popover) popover.destroy(); - options = null; - popover = null; - }); + return PopoverFactory; + + }]; + + }) + + .directive('bsPopover', ["$window", "$sce", "$popover", function ($window, $sce, $popover) { + + var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; + + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr) { + + // Directive options + var options = {scope: scope}; + angular.forEach(['template', 'contentTemplate', 'placement', 'container', 'target', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'customClass', 'autoClose', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // Support scope as data-attrs + angular.forEach(['title', 'content'], function (key) { + attr[key] && attr.$observe(key, function (newValue, oldValue) { + scope[key] = $sce.trustAsHtml(newValue); + angular.isDefined(oldValue) && requestAnimationFrame(function () { + popover && popover.$applyPlacement(); + }); + }); + }); + + // Support scope as an object + attr.bsPopover && scope.$watch(attr.bsPopover, function (newValue, oldValue) { + if (angular.isObject(newValue)) { + angular.extend(scope, newValue); + } else { + scope.content = newValue; + } + angular.isDefined(oldValue) && requestAnimationFrame(function () { + popover && popover.$applyPlacement(); + }); + }, true); + + // Visibility binding support + attr.bsShow && scope.$watch(attr.bsShow, function (newValue, oldValue) { + if (!popover || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(popover),?/i); + newValue === true ? popover.show() : popover.hide(); + }); + + // Initialize popover + var popover = $popover(element, options); + + // Garbage collection + scope.$on('$destroy', function () { + if (popover) popover.destroy(); + options = null; + popover = null; + }); - } - }; + } + }; - }]); + }]); // Source: select.js -angular.module('mgcrea.ngStrap.select', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) - - .provider('$select', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'select', - prefixEvent: '$select', - placement: 'bottom-left', - template: 'select/select.tpl.html', - trigger: 'focus', - container: false, - keyboard: true, - html: false, - delay: 0, - multiple: false, - allNoneButtons: false, - sort: true, - caretHtml: ' ', - placeholder: 'Choose among the following...', - allText: 'All', - noneText: 'None', - maxLength: 3, - maxLengthHtml: 'selected', - iconCheckmark: 'glyphicon glyphicon-ok' - }; - - this.$get = ["$window", "$document", "$rootScope", "$tooltip", "$timeout", function($window, $document, $rootScope, $tooltip, $timeout) { - - var bodyEl = angular.element($window.document.body); - var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); - var isTouch = ('createTouch' in $window.document) && isNative; - - function SelectFactory(element, controller, config) { - - var $select = {}; - - // Common vars - var options = angular.extend({}, defaults, config); - - $select = $tooltip(element, options); - var scope = $select.$scope; - - scope.$matches = []; - scope.$activeIndex = 0; - scope.$isMultiple = options.multiple; - scope.$showAllNoneButtons = options.allNoneButtons && options.multiple; - scope.$iconCheckmark = options.iconCheckmark; - scope.$allText = options.allText; - scope.$noneText = options.noneText; - - scope.$activate = function(index) { - scope.$$postDigest(function() { - $select.activate(index); - }); - }; - - scope.$select = function(index, evt) { - scope.$$postDigest(function() { - $select.select(index); - }); - }; - - scope.$isVisible = function() { - return $select.$isVisible(); - }; - - scope.$isActive = function(index) { - return $select.$isActive(index); - }; - - scope.$selectAll = function () { - for (var i = 0; i < scope.$matches.length; i++) { - if (!scope.$isActive(i)) { - scope.$select(i); - } - } - }; - - scope.$selectNone = function () { - for (var i = 0; i < scope.$matches.length; i++) { - if (scope.$isActive(i)) { - scope.$select(i); - } - } - }; - - // Public methods - - $select.update = function(matches) { - scope.$matches = matches; - $select.$updateActiveIndex(); - }; - - $select.activate = function(index) { - if(options.multiple) { - scope.$activeIndex.sort(); - $select.$isActive(index) ? scope.$activeIndex.splice(scope.$activeIndex.indexOf(index), 1) : scope.$activeIndex.push(index); - if(options.sort) scope.$activeIndex.sort(); - } else { - scope.$activeIndex = index; - } - return scope.$activeIndex; - }; - - $select.select = function(index) { - var value = scope.$matches[index].value; - scope.$apply(function() { - $select.activate(index); - if(options.multiple) { - controller.$setViewValue(scope.$activeIndex.map(function(index) { - return scope.$matches[index].value; - })); - } else { - controller.$setViewValue(value); - // Hide if single select - $select.hide(); - } - }); - // Emit event - scope.$emit(options.prefixEvent + '.select', value, index, $select); - }; - - // Protected methods - - $select.$updateActiveIndex = function() { - if(controller.$modelValue && scope.$matches.length) { - if(options.multiple && angular.isArray(controller.$modelValue)) { - scope.$activeIndex = controller.$modelValue.map(function(value) { - return $select.$getIndex(value); - }); - } else { - scope.$activeIndex = $select.$getIndex(controller.$modelValue); - } - } else if(scope.$activeIndex >= scope.$matches.length) { - scope.$activeIndex = options.multiple ? [] : 0; - } - }; - - $select.$isVisible = function() { - if(!options.minLength || !controller) { - return scope.$matches.length; - } - // minLength support - return scope.$matches.length && controller.$viewValue.length >= options.minLength; - }; - - $select.$isActive = function(index) { - if(options.multiple) { - return scope.$activeIndex.indexOf(index) !== -1; - } else { - return scope.$activeIndex === index; - } - }; - - $select.$getIndex = function(value) { - var l = scope.$matches.length, i = l; - if(!l) return; - for(i = l; i--;) { - if(scope.$matches[i].value === value) break; - } - if(i < 0) return; - return i; - }; - - $select.$onMouseDown = function(evt) { - // Prevent blur on mousedown on .dropdown-menu - evt.preventDefault(); - evt.stopPropagation(); - // Emulate click for mobile devices - if(isTouch) { - var targetEl = angular.element(evt.target); - targetEl.triggerHandler('click'); - } - }; - - $select.$onKeyDown = function(evt) { - if (!/(9|13|38|40)/.test(evt.keyCode)) return; - evt.preventDefault(); - evt.stopPropagation(); - - // Select with enter - if(!options.multiple && (evt.keyCode === 13 || evt.keyCode === 9)) { - return $select.select(scope.$activeIndex); - } - - // Navigate with keyboard - if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; - else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; - else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; - scope.$digest(); - }; - - // Overrides - - var _show = $select.show; - $select.show = function() { - _show(); - if(options.multiple) { - $select.$element.addClass('select-multiple'); - } - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - $select.$element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); - if(options.keyboard) { - element.on('keydown', $select.$onKeyDown); - } - }, 0, false); - }; - - var _hide = $select.hide; - $select.hide = function() { - $select.$element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); - if(options.keyboard) { - element.off('keydown', $select.$onKeyDown); - } - _hide(true); - }; - - return $select; - - } - - SelectFactory.defaults = defaults; - return SelectFactory; - - }]; - - }) - - .directive('bsSelect', ["$window", "$parse", "$q", "$select", "$parseOptions", function($window, $parse, $q, $select, $parseOptions) { - - var defaults = $select.defaults; + angular.module('mgcrea.ngStrap.select', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) + + .provider('$select', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'select', + prefixEvent: '$select', + placement: 'bottom-left', + template: 'select/select.tpl.html', + trigger: 'focus', + container: false, + keyboard: true, + html: false, + delay: 0, + multiple: false, + allNoneButtons: false, + sort: true, + caretHtml: ' ', + placeholder: 'Choose among the following...', + allText: 'All', + noneText: 'None', + maxLength: 3, + maxLengthHtml: 'selected', + iconCheckmark: 'glyphicon glyphicon-ok' + }; - return { - restrict: 'EAC', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { + this.$get = ["$window", "$document", "$rootScope", "$tooltip", "$timeout", function ($window, $document, $rootScope, $tooltip, $timeout) { + + var bodyEl = angular.element($window.document.body); + var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + var isTouch = ('createTouch' in $window.document) && isNative; + + function SelectFactory(element, controller, config) { + + var $select = {}; + + // Common vars + var options = angular.extend({}, defaults, config); + + $select = $tooltip(element, options); + var scope = $select.$scope; + + scope.$matches = []; + scope.$activeIndex = 0; + scope.$isMultiple = options.multiple; + scope.$showAllNoneButtons = options.allNoneButtons && options.multiple; + scope.$iconCheckmark = options.iconCheckmark; + scope.$allText = options.allText; + scope.$noneText = options.noneText; + + scope.$activate = function (index) { + scope.$$postDigest(function () { + $select.activate(index); + }); + }; + + scope.$select = function (index, evt) { + scope.$$postDigest(function () { + $select.select(index); + }); + }; + + scope.$isVisible = function () { + return $select.$isVisible(); + }; + + scope.$isActive = function (index) { + return $select.$isActive(index); + }; + + scope.$selectAll = function () { + for (var i = 0; i < scope.$matches.length; i++) { + if (!scope.$isActive(i)) { + scope.$select(i); + } + } + }; + + scope.$selectNone = function () { + for (var i = 0; i < scope.$matches.length; i++) { + if (scope.$isActive(i)) { + scope.$select(i); + } + } + }; + + // Public methods + + $select.update = function (matches) { + scope.$matches = matches; + $select.$updateActiveIndex(); + }; + + $select.activate = function (index) { + if (options.multiple) { + scope.$activeIndex.sort(); + $select.$isActive(index) ? scope.$activeIndex.splice(scope.$activeIndex.indexOf(index), 1) : scope.$activeIndex.push(index); + if (options.sort) scope.$activeIndex.sort(); + } else { + scope.$activeIndex = index; + } + return scope.$activeIndex; + }; + + $select.select = function (index) { + var value = scope.$matches[index].value; + scope.$apply(function () { + $select.activate(index); + if (options.multiple) { + controller.$setViewValue(scope.$activeIndex.map(function (index) { + return scope.$matches[index].value; + })); + } else { + controller.$setViewValue(value); + // Hide if single select + $select.hide(); + } + }); + // Emit event + scope.$emit(options.prefixEvent + '.select', value, index, $select); + }; + + // Protected methods + + $select.$updateActiveIndex = function () { + if (controller.$modelValue && scope.$matches.length) { + if (options.multiple && angular.isArray(controller.$modelValue)) { + scope.$activeIndex = controller.$modelValue.map(function (value) { + return $select.$getIndex(value); + }); + } else { + scope.$activeIndex = $select.$getIndex(controller.$modelValue); + } + } else if (scope.$activeIndex >= scope.$matches.length) { + scope.$activeIndex = options.multiple ? [] : 0; + } + }; + + $select.$isVisible = function () { + if (!options.minLength || !controller) { + return scope.$matches.length; + } + // minLength support + return scope.$matches.length && controller.$viewValue.length >= options.minLength; + }; + + $select.$isActive = function (index) { + if (options.multiple) { + return scope.$activeIndex.indexOf(index) !== -1; + } else { + return scope.$activeIndex === index; + } + }; + + $select.$getIndex = function (value) { + var l = scope.$matches.length, i = l; + if (!l) return; + for (i = l; i--;) { + if (scope.$matches[i].value === value) break; + } + if (i < 0) return; + return i; + }; + + $select.$onMouseDown = function (evt) { + // Prevent blur on mousedown on .dropdown-menu + evt.preventDefault(); + evt.stopPropagation(); + // Emulate click for mobile devices + if (isTouch) { + var targetEl = angular.element(evt.target); + targetEl.triggerHandler('click'); + } + }; + + $select.$onKeyDown = function (evt) { + if (!/(9|13|38|40)/.test(evt.keyCode)) return; + evt.preventDefault(); + evt.stopPropagation(); + + // Select with enter + if (!options.multiple && (evt.keyCode === 13 || evt.keyCode === 9)) { + return $select.select(scope.$activeIndex); + } + + // Navigate with keyboard + if (evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; + else if (evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; + else if (angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; + scope.$digest(); + }; + + // Overrides + + var _show = $select.show; + $select.show = function () { + _show(); + if (options.multiple) { + $select.$element.addClass('select-multiple'); + } + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + $select.$element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); + if (options.keyboard) { + element.on('keydown', $select.$onKeyDown); + } + }, 0, false); + }; + + var _hide = $select.hide; + $select.hide = function () { + $select.$element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); + if (options.keyboard) { + element.off('keydown', $select.$onKeyDown); + } + _hide(true); + }; + + return $select; - // Directive options - var options = {scope: scope, placeholder: defaults.placeholder}; - angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'placeholder', 'multiple', 'allNoneButtons', 'maxLength', 'maxLengthHtml', 'allText', 'noneText', 'iconCheckmark', 'autoClose', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + } - // Add support for select markup - if(element[0].nodeName.toLowerCase() === 'select') { - var inputEl = element; - inputEl.css('display', 'none'); - element = angular.element(''); - inputEl.after(element); - } - - // Build proper ngOptions - var parsedOptions = $parseOptions(attr.ngOptions); - - // Initialize select - var select = $select(element, controller, options); - - // Watch ngOptions values before filtering for changes - var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').trim(); - scope.$watch(watchedOptions, function(newValue, oldValue) { - // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); - parsedOptions.valuesFn(scope, controller) - .then(function(values) { - select.update(values); - controller.$render(); - }); - }, true); - - // Watch model for changes - scope.$watch(attr.ngModel, function(newValue, oldValue) { - // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue); - select.$updateActiveIndex(); - controller.$render(); - }, true); - - // Model rendering in view - controller.$render = function () { - // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); - var selected, index; - if(options.multiple && angular.isArray(controller.$modelValue)) { - selected = controller.$modelValue.map(function(value) { - index = select.$getIndex(value); - return angular.isDefined(index) ? select.$scope.$matches[index].label : false; - }).filter(angular.isDefined); - if(selected.length > (options.maxLength || defaults.maxLength)) { - selected = selected.length + ' ' + (options.maxLengthHtml || defaults.maxLengthHtml); - } else { - selected = selected.join(', '); - } - } else { - index = select.$getIndex(controller.$modelValue); - selected = angular.isDefined(index) ? select.$scope.$matches[index].label : false; - } - element.html((selected ? selected : options.placeholder) + defaults.caretHtml); - }; - - if(options.multiple){ - controller.$isEmpty = function(value){ - return !value || value.length === 0; - }; - } - - // Garbage collection - scope.$on('$destroy', function() { - if (select) select.destroy(); - options = null; - select = null; - }); + SelectFactory.defaults = defaults; + return SelectFactory; + + }]; + + }) + + .directive('bsSelect', ["$window", "$parse", "$q", "$select", "$parseOptions", function ($window, $parse, $q, $select, $parseOptions) { + + var defaults = $select.defaults; + + return { + restrict: 'EAC', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { + + // Directive options + var options = {scope: scope, placeholder: defaults.placeholder}; + angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'placeholder', 'multiple', 'allNoneButtons', 'maxLength', 'maxLengthHtml', 'allText', 'noneText', 'iconCheckmark', 'autoClose', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // Add support for select markup + if (element[0].nodeName.toLowerCase() === 'select') { + var inputEl = element; + inputEl.css('display', 'none'); + element = angular.element(''); + inputEl.after(element); + } + + // Build proper ngOptions + var parsedOptions = $parseOptions(attr.ngOptions); + + // Initialize select + var select = $select(element, controller, options); + + // Watch ngOptions values before filtering for changes + var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').trim(); + scope.$watch(watchedOptions, function (newValue, oldValue) { + // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); + parsedOptions.valuesFn(scope, controller) + .then(function (values) { + select.update(values); + controller.$render(); + }); + }, true); + + // Watch model for changes + scope.$watch(attr.ngModel, function (newValue, oldValue) { + // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue); + select.$updateActiveIndex(); + controller.$render(); + }, true); + + // Model rendering in view + controller.$render = function () { + // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); + var selected, index; + if (options.multiple && angular.isArray(controller.$modelValue)) { + selected = controller.$modelValue.map(function (value) { + index = select.$getIndex(value); + return angular.isDefined(index) ? select.$scope.$matches[index].label : false; + }).filter(angular.isDefined); + if (selected.length > (options.maxLength || defaults.maxLength)) { + selected = selected.length + ' ' + (options.maxLengthHtml || defaults.maxLengthHtml); + } else { + selected = selected.join(', '); + } + } else { + index = select.$getIndex(controller.$modelValue); + selected = angular.isDefined(index) ? select.$scope.$matches[index].label : false; + } + element.html((selected ? selected : options.placeholder) + defaults.caretHtml); + }; + + if (options.multiple) { + controller.$isEmpty = function (value) { + return !value || value.length === 0; + }; + } + + // Garbage collection + scope.$on('$destroy', function () { + if (select) select.destroy(); + options = null; + select = null; + }); - } - }; + } + }; - }]); + }]); // Source: tab.js -angular.module('mgcrea.ngStrap.tab', []) - - .provider('$tab', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - template: 'tab/tab.tpl.html', - navClass: 'nav-tabs', - activeClass: 'active' - }; - - var controller = this.controller = function($scope, $element, $attrs) { - var self = this; - - // Attributes options - self.$options = angular.copy(defaults); - angular.forEach(['animation', 'navClass', 'activeClass'], function(key) { - if(angular.isDefined($attrs[key])) self.$options[key] = $attrs[key]; - }); - - // Publish options on scope - $scope.$navClass = self.$options.navClass; - $scope.$activeClass = self.$options.activeClass; - - self.$panes = $scope.$panes = []; - - // DEPRECATED: $viewChangeListeners, please use $activePaneChangeListeners - // Because we deprecated ngModel usage, we rename viewChangeListeners to - // activePaneChangeListeners to make more sense. - self.$activePaneChangeListeners = self.$viewChangeListeners = []; - - self.$push = function(pane) { - self.$panes.push(pane); - }; - - self.$remove = function(pane) { - var index = self.$panes.indexOf(pane); - var activeIndex = self.$panes.$active; - - // remove pane from $panes array - self.$panes.splice(index, 1); - - if (index < activeIndex) { - // we removed a pane before the active pane, so we need to - // decrement the active pane index - activeIndex--; - } - else if (index === activeIndex && activeIndex === self.$panes.length) { - // we remove the active pane and it was the one at the end, - // so select the previous one - activeIndex--; - } - self.$setActive(activeIndex); - }; - - self.$panes.$active = 0; - self.$setActive = $scope.$setActive = function(value) { - self.$panes.$active = value; - self.$activePaneChangeListeners.forEach(function(fn) { - fn(); - }); - }; - - }; - - this.$get = function() { - var $tab = {}; - $tab.defaults = defaults; - $tab.controller = controller; - return $tab; - }; - - }) - - .directive('bsTabs', ["$window", "$animate", "$tab", "$parse", function($window, $animate, $tab, $parse) { - - var defaults = $tab.defaults; - - return { - require: ['?ngModel', 'bsTabs'], - transclude: true, - scope: true, - controller: ['$scope', '$element', '$attrs', $tab.controller], - templateUrl: function(element, attr) { - return attr.template || defaults.template; - }, - link: function postLink(scope, element, attrs, controllers) { - - var ngModelCtrl = controllers[0]; - var bsTabsCtrl = controllers[1]; - - // DEPRECATED: ngModel, please use bsActivePane - // 'ngModel' is deprecated bacause if interferes with form validation - // and status, so avoid using it here. - if(ngModelCtrl) { - console.warn('Usage of ngModel is deprecated, please use bsActivePane instead!'); - - // Update the modelValue following - bsTabsCtrl.$activePaneChangeListeners.push(function() { - ngModelCtrl.$setViewValue(bsTabsCtrl.$panes.$active); - }); - - // modelValue -> $formatters -> viewValue - ngModelCtrl.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - bsTabsCtrl.$setActive(modelValue * 1); - return modelValue; - }); - - } - - if (attrs.bsActivePane) { - // adapted from angularjs ngModelController bindings - // https://github.com/angular/angular.js/blob/v1.3.1/src%2Fng%2Fdirective%2Finput.js#L1730 - var parsedBsActivePane = $parse(attrs.bsActivePane); - - // Update bsActivePane value with change - bsTabsCtrl.$activePaneChangeListeners.push(function() { - parsedBsActivePane.assign(scope, bsTabsCtrl.$panes.$active); - }); - - // watch bsActivePane for value changes - scope.$watch(attrs.bsActivePane, function(newValue, oldValue) { - bsTabsCtrl.$setActive(newValue * 1); - }, true); - } - } - }; - - }]) - - .directive('bsPane', ["$window", "$animate", "$sce", function($window, $animate, $sce) { - - return { - require: ['^?ngModel', '^bsTabs'], - scope: true, - link: function postLink(scope, element, attrs, controllers) { - - var ngModelCtrl = controllers[0]; - var bsTabsCtrl = controllers[1]; - - // Add base class - element.addClass('tab-pane'); - - // Observe title attribute for change - attrs.$observe('title', function(newValue, oldValue) { - scope.title = $sce.trustAsHtml(newValue); - }); - - // Add animation class - if(bsTabsCtrl.$options.animation) { - element.addClass(bsTabsCtrl.$options.animation); - } - - // Push pane to parent bsTabs controller - bsTabsCtrl.$push(scope); - - // remove pane from tab controller when pane is destroyed - scope.$on('$destroy', function() { - bsTabsCtrl.$remove(scope); - }); - - function render() { - var index = bsTabsCtrl.$panes.indexOf(scope); - var active = bsTabsCtrl.$panes.$active; - $animate[index === active ? 'addClass' : 'removeClass'](element, bsTabsCtrl.$options.activeClass); - } - - bsTabsCtrl.$activePaneChangeListeners.push(function() { - render(); - }); - render(); - - } - }; - - }]); - -// Source: scrollspy.js -angular.module('mgcrea.ngStrap.scrollspy', ['mgcrea.ngStrap.helpers.debounce', 'mgcrea.ngStrap.helpers.dimensions']) - - .provider('$scrollspy', function() { - - // Pool of registered spies - var spies = this.$$spies = {}; - - var defaults = this.defaults = { - debounce: 150, - throttle: 100, - offset: 100 - }; - - this.$get = ["$window", "$document", "$rootScope", "dimensions", "debounce", "throttle", function($window, $document, $rootScope, dimensions, debounce, throttle) { - - var windowEl = angular.element($window); - var docEl = angular.element($document.prop('documentElement')); - var bodyEl = angular.element($window.document.body); - - // Helper functions - - function nodeName(element, name) { - return element[0].nodeName && element[0].nodeName.toLowerCase() === name.toLowerCase(); - } - - function ScrollSpyFactory(config) { - - // Common vars - var options = angular.extend({}, defaults, config); - if(!options.element) options.element = bodyEl; - var isWindowSpy = nodeName(options.element, 'body'); - var scrollEl = isWindowSpy ? windowEl : options.element; - var scrollId = isWindowSpy ? 'window' : options.id; - - // Use existing spy - if(spies[scrollId]) { - spies[scrollId].$$count++; - return spies[scrollId]; - } - - var $scrollspy = {}; - - // Private vars - var unbindViewContentLoaded, unbindIncludeContentLoaded; - var trackedElements = $scrollspy.$trackedElements = []; - var sortedElements = []; - var activeTarget; - var debouncedCheckPosition; - var throttledCheckPosition; - var debouncedCheckOffsets; - var viewportHeight; - var scrollTop; - - $scrollspy.init = function() { - - // Setup internal ref counter - this.$$count = 1; - - // Bind events - debouncedCheckPosition = debounce(this.checkPosition, options.debounce); - throttledCheckPosition = throttle(this.checkPosition, options.throttle); - scrollEl.on('click', this.checkPositionWithEventLoop); - windowEl.on('resize', debouncedCheckPosition); - scrollEl.on('scroll', throttledCheckPosition); - - debouncedCheckOffsets = debounce(this.checkOffsets, options.debounce); - unbindViewContentLoaded = $rootScope.$on('$viewContentLoaded', debouncedCheckOffsets); - unbindIncludeContentLoaded = $rootScope.$on('$includeContentLoaded', debouncedCheckOffsets); - debouncedCheckOffsets(); - - // Register spy for reuse - if(scrollId) { - spies[scrollId] = $scrollspy; - } - - }; - - $scrollspy.destroy = function() { - - // Check internal ref counter - this.$$count--; - if(this.$$count > 0) { - return; - } - - // Unbind events - scrollEl.off('click', this.checkPositionWithEventLoop); - windowEl.off('resize', debouncedCheckPosition); - scrollEl.off('scroll', throttledCheckPosition); - unbindViewContentLoaded(); - unbindIncludeContentLoaded(); - if (scrollId) { - delete spies[scrollId]; - } - }; - - $scrollspy.checkPosition = function() { - - // Not ready yet - if(!sortedElements.length) return; - - // Calculate the scroll position - scrollTop = (isWindowSpy ? $window.pageYOffset : scrollEl.prop('scrollTop')) || 0; - - // Calculate the viewport height for use by the components - viewportHeight = Math.max($window.innerHeight, docEl.prop('clientHeight')); - - // Activate first element if scroll is smaller - if(scrollTop < sortedElements[0].offsetTop && activeTarget !== sortedElements[0].target) { - return $scrollspy.$activateElement(sortedElements[0]); - } - - // Activate proper element - for (var i = sortedElements.length; i--;) { - if(angular.isUndefined(sortedElements[i].offsetTop) || sortedElements[i].offsetTop === null) continue; - if(activeTarget === sortedElements[i].target) continue; - if(scrollTop < sortedElements[i].offsetTop) continue; - if(sortedElements[i + 1] && scrollTop > sortedElements[i + 1].offsetTop) continue; - return $scrollspy.$activateElement(sortedElements[i]); - } - - }; - - $scrollspy.checkPositionWithEventLoop = function() { - // IE 9 throws an error if we use 'this' instead of '$scrollspy' - // in this setTimeout call - setTimeout($scrollspy.checkPosition, 1); - }; - - // Protected methods - - $scrollspy.$activateElement = function(element) { - if(activeTarget) { - var activeElement = $scrollspy.$getTrackedElement(activeTarget); - if(activeElement) { - activeElement.source.removeClass('active'); - if(nodeName(activeElement.source, 'li') && nodeName(activeElement.source.parent().parent(), 'li')) { - activeElement.source.parent().parent().removeClass('active'); - } - } - } - activeTarget = element.target; - element.source.addClass('active'); - if(nodeName(element.source, 'li') && nodeName(element.source.parent().parent(), 'li')) { - element.source.parent().parent().addClass('active'); - } - }; - - $scrollspy.$getTrackedElement = function(target) { - return trackedElements.filter(function(obj) { - return obj.target === target; - })[0]; - }; - - // Track offsets behavior - - $scrollspy.checkOffsets = function() { - - angular.forEach(trackedElements, function(trackedElement) { - var targetElement = document.querySelector(trackedElement.target); - trackedElement.offsetTop = targetElement ? dimensions.offset(targetElement).top : null; - if(options.offset && trackedElement.offsetTop !== null) trackedElement.offsetTop -= options.offset * 1; - }); - - sortedElements = trackedElements - .filter(function(el) { - return el.offsetTop !== null; - }) - .sort(function(a, b) { - return a.offsetTop - b.offsetTop; - }); - - debouncedCheckPosition(); - - }; - - $scrollspy.trackElement = function(target, source) { - trackedElements.push({target: target, source: source}); - }; - - $scrollspy.untrackElement = function(target, source) { - var toDelete; - for (var i = trackedElements.length; i--;) { - if(trackedElements[i].target === target && trackedElements[i].source === source) { - toDelete = i; - break; - } - } - trackedElements = trackedElements.splice(toDelete, 1); - }; - - $scrollspy.activate = function(i) { - trackedElements[i].addClass('active'); - }; - - // Initialize plugin - - $scrollspy.init(); - return $scrollspy; - - } - - return ScrollSpyFactory; - - }]; - - }) - - .directive('bsScrollspy', ["$rootScope", "debounce", "dimensions", "$scrollspy", function($rootScope, debounce, dimensions, $scrollspy) { - - return { - restrict: 'EAC', - link: function postLink(scope, element, attr) { - - var options = {scope: scope}; - angular.forEach(['offset', 'target'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); - - var scrollspy = $scrollspy(options); - scrollspy.trackElement(options.target, element); - - scope.$on('$destroy', function() { - if (scrollspy) { - scrollspy.untrackElement(options.target, element); - scrollspy.destroy(); - } - options = null; - scrollspy = null; - }); - - } - }; - - }]) - - - .directive('bsScrollspyList', ["$rootScope", "debounce", "dimensions", "$scrollspy", function($rootScope, debounce, dimensions, $scrollspy) { - - return { - restrict: 'A', - compile: function postLink(element, attr) { - var children = element[0].querySelectorAll('li > a[href]'); - angular.forEach(children, function(child) { - var childEl = angular.element(child); - childEl.parent().attr('bs-scrollspy', '').attr('data-target', childEl.attr('href')); - }); - } - - }; - - }]); - -// Source: timepicker.js -angular.module('mgcrea.ngStrap.timepicker', [ - 'mgcrea.ngStrap.helpers.dateParser', - 'mgcrea.ngStrap.helpers.dateFormatter', - 'mgcrea.ngStrap.tooltip']) - - .provider('$timepicker', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'timepicker', - placement: 'bottom-left', - template: 'timepicker/timepicker.tpl.html', - trigger: 'focus', - container: false, - keyboard: true, - html: false, - delay: 0, - // lang: $locale.id, - useNative: true, - timeType: 'date', - timeFormat: 'shortTime', - modelTimeFormat: null, - autoclose: false, - minTime: -Infinity, - maxTime: +Infinity, - length: 5, - hourStep: 1, - minuteStep: 5, - iconUp: 'glyphicon glyphicon-chevron-up', - iconDown: 'glyphicon glyphicon-chevron-down', - arrowBehavior: 'pager' - }; - - this.$get = ["$window", "$document", "$rootScope", "$sce", "$dateFormatter", "$tooltip", "$timeout", function($window, $document, $rootScope, $sce, $dateFormatter, $tooltip, $timeout) { - - var bodyEl = angular.element($window.document.body); - var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); - var isTouch = ('createTouch' in $window.document) && isNative; - if(!defaults.lang) defaults.lang = $dateFormatter.getDefaultLocale(); - - function timepickerFactory(element, controller, config) { - - var $timepicker = $tooltip(element, angular.extend({}, defaults, config)); - var parentScope = config.scope; - var options = $timepicker.$options; - var scope = $timepicker.$scope; - - var lang = options.lang; - var formatDate = function(date, format) { - return $dateFormatter.formatDate(date, format, lang); - }; - - // View vars - - var selectedIndex = 0; - var startDate = controller.$dateValue || new Date(); - var viewDate = {hour: startDate.getHours(), meridian: startDate.getHours() < 12, minute: startDate.getMinutes(), second: startDate.getSeconds(), millisecond: startDate.getMilliseconds()}; - - var format = $dateFormatter.getDatetimeFormat(options.timeFormat, lang); - - var hoursFormat = $dateFormatter.hoursFormat(format), - timeSeparator = $dateFormatter.timeSeparator(format), - minutesFormat = $dateFormatter.minutesFormat(format), - showAM = $dateFormatter.showAM(format); - - scope.$iconUp = options.iconUp; - scope.$iconDown = options.iconDown; - - // Scope methods - - scope.$select = function(date, index) { - $timepicker.select(date, index); - }; - scope.$moveIndex = function(value, index) { - $timepicker.$moveIndex(value, index); - }; - scope.$switchMeridian = function(date) { - $timepicker.switchMeridian(date); - }; - - // Public methods - - $timepicker.update = function(date) { - // console.warn('$timepicker.update() newValue=%o', date); - if(angular.isDate(date) && !isNaN(date.getTime())) { - $timepicker.$date = date; - angular.extend(viewDate, {hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(), millisecond: date.getMilliseconds()}); - $timepicker.$build(); - } else if(!$timepicker.$isBuilt) { - $timepicker.$build(); - } - }; - - $timepicker.select = function(date, index, keep) { - // console.warn('$timepicker.select', date, scope.$mode); - if(!controller.$dateValue || isNaN(controller.$dateValue.getTime())) controller.$dateValue = new Date(1970, 0, 1); - if(!angular.isDate(date)) date = new Date(date); - if(index === 0) controller.$dateValue.setHours(date.getHours()); - else if(index === 1) controller.$dateValue.setMinutes(date.getMinutes()); - controller.$setViewValue(angular.copy(controller.$dateValue)); - controller.$render(); - if(options.autoclose && !keep) { - $timeout(function() { $timepicker.hide(true); }); - } - }; - - $timepicker.switchMeridian = function(date) { - if (!controller.$dateValue || isNaN(controller.$dateValue.getTime())) { - return; - } - var hours = (date || controller.$dateValue).getHours(); - controller.$dateValue.setHours(hours < 12 ? hours + 12 : hours - 12); - controller.$setViewValue(angular.copy(controller.$dateValue)); - controller.$render(); - }; - - // Protected methods - - $timepicker.$build = function() { - // console.warn('$timepicker.$build() viewDate=%o', viewDate); - var i, midIndex = scope.midIndex = parseInt(options.length / 2, 10); - var hours = [], hour; - for(i = 0; i < options.length; i++) { - hour = new Date(1970, 0, 1, viewDate.hour - (midIndex - i) * options.hourStep); - hours.push({date: hour, label: formatDate(hour, hoursFormat), selected: $timepicker.$date && $timepicker.$isSelected(hour, 0), disabled: $timepicker.$isDisabled(hour, 0)}); - } - var minutes = [], minute; - for(i = 0; i < options.length; i++) { - minute = new Date(1970, 0, 1, 0, viewDate.minute - (midIndex - i) * options.minuteStep); - minutes.push({date: minute, label: formatDate(minute, minutesFormat), selected: $timepicker.$date && $timepicker.$isSelected(minute, 1), disabled: $timepicker.$isDisabled(minute, 1)}); - } - - var rows = []; - for(i = 0; i < options.length; i++) { - rows.push([hours[i], minutes[i]]); - } - scope.rows = rows; - scope.showAM = showAM; - scope.isAM = ($timepicker.$date || hours[midIndex].date).getHours() < 12; - scope.timeSeparator = timeSeparator; - $timepicker.$isBuilt = true; - }; - - $timepicker.$isSelected = function(date, index) { - if(!$timepicker.$date) return false; - else if(index === 0) { - return date.getHours() === $timepicker.$date.getHours(); - } else if(index === 1) { - return date.getMinutes() === $timepicker.$date.getMinutes(); - } - }; - - $timepicker.$isDisabled = function(date, index) { - var selectedTime; - if(index === 0) { - selectedTime = date.getTime() + viewDate.minute * 6e4; - } else if(index === 1) { - selectedTime = date.getTime() + viewDate.hour * 36e5; - } - return selectedTime < options.minTime * 1 || selectedTime > options.maxTime * 1; - }; - - scope.$arrowAction = function (value, index) { - if (options.arrowBehavior === 'picker') { - $timepicker.$setTimeByStep(value,index); - } else { - $timepicker.$moveIndex(value,index); - } - }; - - $timepicker.$setTimeByStep = function(value, index) { - var newDate = new Date($timepicker.$date); - var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; - var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; - if (index === 0) { - newDate.setHours(hours - (parseInt(options.hourStep, 10) * value)); - } - else { - newDate.setMinutes(minutes - (parseInt(options.minuteStep, 10) * value)); - } - $timepicker.select(newDate, index, true); - }; - - $timepicker.$moveIndex = function(value, index) { - var targetDate; - if(index === 0) { - targetDate = new Date(1970, 0, 1, viewDate.hour + (value * options.length), viewDate.minute); - angular.extend(viewDate, {hour: targetDate.getHours()}); - } else if(index === 1) { - targetDate = new Date(1970, 0, 1, viewDate.hour, viewDate.minute + (value * options.length * options.minuteStep)); - angular.extend(viewDate, {minute: targetDate.getMinutes()}); - } - $timepicker.$build(); - }; - - $timepicker.$onMouseDown = function(evt) { - // Prevent blur on mousedown on .dropdown-menu - if(evt.target.nodeName.toLowerCase() !== 'input') evt.preventDefault(); - evt.stopPropagation(); - // Emulate click for mobile devices - if(isTouch) { - var targetEl = angular.element(evt.target); - if(targetEl[0].nodeName.toLowerCase() !== 'button') { - targetEl = targetEl.parent(); - } - targetEl.triggerHandler('click'); - } - }; - - $timepicker.$onKeyDown = function(evt) { - if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; - evt.preventDefault(); - evt.stopPropagation(); - - // Close on enter - if(evt.keyCode === 13) return $timepicker.hide(true); - - // Navigate with keyboard - var newDate = new Date($timepicker.$date); - var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; - var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; - var lateralMove = /(37|39)/.test(evt.keyCode); - var count = 2 + showAM * 1; - - // Navigate indexes (left, right) - if (lateralMove) { - if(evt.keyCode === 37) selectedIndex = selectedIndex < 1 ? count - 1 : selectedIndex - 1; - else if(evt.keyCode === 39) selectedIndex = selectedIndex < count - 1 ? selectedIndex + 1 : 0; - } - - // Update values (up, down) - var selectRange = [0, hoursLength]; - if(selectedIndex === 0) { - if(evt.keyCode === 38) newDate.setHours(hours - parseInt(options.hourStep, 10)); - else if(evt.keyCode === 40) newDate.setHours(hours + parseInt(options.hourStep, 10)); - // re-calculate hours length because we have changed hours value - hoursLength = formatDate(newDate, hoursFormat).length; - selectRange = [0, hoursLength]; - } else if(selectedIndex === 1) { - if(evt.keyCode === 38) newDate.setMinutes(minutes - parseInt(options.minuteStep, 10)); - else if(evt.keyCode === 40) newDate.setMinutes(minutes + parseInt(options.minuteStep, 10)); - // re-calculate minutes length because we have changes minutes value - minutesLength = formatDate(newDate, minutesFormat).length; - selectRange = [hoursLength + 1, hoursLength + 1 + minutesLength]; - } else if(selectedIndex === 2) { - if(!lateralMove) $timepicker.switchMeridian(); - selectRange = [hoursLength + 1 + minutesLength + 1, hoursLength + 1 + minutesLength + 3]; - } - $timepicker.select(newDate, selectedIndex, true); - createSelection(selectRange[0], selectRange[1]); - parentScope.$digest(); - }; - - // Private - - function createSelection(start, end) { - if(element[0].createTextRange) { - var selRange = element[0].createTextRange(); - selRange.collapse(true); - selRange.moveStart('character', start); - selRange.moveEnd('character', end); - selRange.select(); - } else if(element[0].setSelectionRange) { - element[0].setSelectionRange(start, end); - } else if(angular.isUndefined(element[0].selectionStart)) { - element[0].selectionStart = start; - element[0].selectionEnd = end; - } - } - - function focusElement() { - element[0].focus(); - } - - // Overrides - - var _init = $timepicker.init; - $timepicker.init = function() { - if(isNative && options.useNative) { - element.prop('type', 'time'); - element.css('-webkit-appearance', 'textfield'); - return; - } else if(isTouch) { - element.prop('type', 'text'); - element.attr('readonly', 'true'); - element.on('click', focusElement); - } - _init(); - }; - - var _destroy = $timepicker.destroy; - $timepicker.destroy = function() { - if(isNative && options.useNative) { - element.off('click', focusElement); - } - _destroy(); - }; - - var _show = $timepicker.show; - $timepicker.show = function() { - _show(); - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - $timepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); - if(options.keyboard) { - element.on('keydown', $timepicker.$onKeyDown); - } - }, 0, false); - }; - - var _hide = $timepicker.hide; - $timepicker.hide = function(blur) { - if(!$timepicker.$isShown) return; - $timepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); - if(options.keyboard) { - element.off('keydown', $timepicker.$onKeyDown); - } - _hide(blur); - }; - - return $timepicker; - - } - - timepickerFactory.defaults = defaults; - return timepickerFactory; - - }]; + angular.module('mgcrea.ngStrap.tab', []) - }) + .provider('$tab', function () { - - .directive('bsTimepicker', ["$window", "$parse", "$q", "$dateFormatter", "$dateParser", "$timepicker", function($window, $parse, $q, $dateFormatter, $dateParser, $timepicker) { - - var defaults = $timepicker.defaults; - var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); - var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; - - return { - restrict: 'EAC', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { - - // Directive options - var options = {scope: scope, controller: controller}; - angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'timeType', 'timeFormat', 'modelTimeFormat', 'useNative', 'hourStep', 'minuteStep', 'length', 'arrowBehavior', 'iconUp', 'iconDown', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); - - // Visibility binding support - attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { - if(!timepicker || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(timepicker),?/i); - newValue === true ? timepicker.show() : timepicker.hide(); - }); - - // Initialize timepicker - if(isNative && (options.useNative || defaults.useNative)) options.timeFormat = 'HH:mm'; - var timepicker = $timepicker(element, controller, options); - options = timepicker.$options; - - var lang = options.lang; - var formatDate = function(date, format) { - return $dateFormatter.formatDate(date, format, lang); - }; - - // Initialize parser - var dateParser = $dateParser({format: options.timeFormat, lang: lang}); - - // Observe attributes for changes - angular.forEach(['minTime', 'maxTime'], function(key) { - // console.warn('attr.$observe(%s)', key, attr[key]); - angular.isDefined(attr[key]) && attr.$observe(key, function(newValue) { - timepicker.$options[key] = dateParser.getTimeForAttribute(key, newValue); - !isNaN(timepicker.$options[key]) && timepicker.$build(); - validateAgainstMinMaxTime(controller.$dateValue); - }); - }); - - // Watch model for changes - scope.$watch(attr.ngModel, function(newValue, oldValue) { - // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue, controller.$dateValue); - timepicker.update(controller.$dateValue); - }, true); - - function validateAgainstMinMaxTime(parsedTime) { - if (!angular.isDate(parsedTime)) return; - var isMinValid = isNaN(options.minTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) >= options.minTime; - var isMaxValid = isNaN(options.maxTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) <= options.maxTime; - var isValid = isMinValid && isMaxValid; - controller.$setValidity('date', isValid); - controller.$setValidity('min', isMinValid); - controller.$setValidity('max', isMaxValid); - // Only update the model when we have a valid date - if(!isValid) { - return; - } - controller.$dateValue = parsedTime; - } - - // viewValue -> $parsers -> modelValue - controller.$parsers.unshift(function(viewValue) { - // console.warn('$parser("%s"): viewValue=%o', element.attr('ng-model'), viewValue); - // Null values should correctly reset the model value & validity - if(!viewValue) { - // BREAKING CHANGE: - // return null (not undefined) when input value is empty, so angularjs 1.3 - // ngModelController can go ahead and run validators, like ngRequired - controller.$setValidity('date', true); - return null; - } - var parsedTime = angular.isDate(viewValue) ? viewValue : dateParser.parse(viewValue, controller.$dateValue); - if(!parsedTime || isNaN(parsedTime.getTime())) { - controller.$setValidity('date', false); - // return undefined, causes ngModelController to - // invalidate model value - return; - } else { - validateAgainstMinMaxTime(parsedTime); - } - if(options.timeType === 'string') { - return formatDate(parsedTime, options.modelTimeFormat || options.timeFormat); - } else if(options.timeType === 'number') { - return controller.$dateValue.getTime(); - } else if(options.timeType === 'unix') { - return controller.$dateValue.getTime() / 1000; - } else if(options.timeType === 'iso') { - return controller.$dateValue.toISOString(); - } else { - return new Date(controller.$dateValue); - } - }); - - // modelValue -> $formatters -> viewValue - controller.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - var date; - if(angular.isUndefined(modelValue) || modelValue === null) { - date = NaN; - } else if(angular.isDate(modelValue)) { - date = modelValue; - } else if(options.timeType === 'string') { - date = dateParser.parse(modelValue, null, options.modelTimeFormat); - } else if(options.timeType === 'unix') { - date = new Date(modelValue * 1000); - } else { - date = new Date(modelValue); - } - // Setup default value? - // if(isNaN(date.getTime())) date = new Date(new Date().setMinutes(0) + 36e5); - controller.$dateValue = date; - return getTimeFormattedString(); - }); - - // viewValue -> element - controller.$render = function() { - // console.warn('$render("%s"): viewValue=%o', element.attr('ng-model'), controller.$viewValue); - element.val(getTimeFormattedString()); - }; - - function getTimeFormattedString() { - return !controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : formatDate(controller.$dateValue, options.timeFormat); - } - - // Garbage collection - scope.$on('$destroy', function() { - if (timepicker) timepicker.destroy(); - options = null; - timepicker = null; - }); - - } - }; - - }]); - -// Source: tooltip.js -angular.module('mgcrea.ngStrap.tooltip', ['mgcrea.ngStrap.helpers.dimensions']) - - .provider('$tooltip', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - customClass: '', - prefixClass: 'tooltip', - prefixEvent: 'tooltip', - container: false, - target: false, - placement: 'top', - template: 'tooltip/tooltip.tpl.html', - contentTemplate: false, - trigger: 'hover focus', - keyboard: false, - html: false, - show: false, - title: '', - type: '', - delay: 0, - autoClose: false, - bsEnabled: true - }; - - this.$get = ["$window", "$rootScope", "$compile", "$q", "$templateCache", "$http", "$animate", "$sce", "dimensions", "$$rAF", "$timeout", function($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $sce, dimensions, $$rAF, $timeout) { - - var trim = String.prototype.trim; - var isTouch = 'createTouch' in $window.document; - var htmlReplaceRegExp = /ng-bind="/ig; - var $body = angular.element($window.document); - - function TooltipFactory(element, config) { - - var $tooltip = {}; - - // Common vars - var nodeName = element[0].nodeName.toLowerCase(); - var options = $tooltip.$options = angular.extend({}, defaults, config); - $tooltip.$promise = fetchTemplate(options.template); - var scope = $tooltip.$scope = options.scope && options.scope.$new() || $rootScope.$new(); - if(options.delay && angular.isString(options.delay)) { - var split = options.delay.split(',').map(parseFloat); - options.delay = split.length > 1 ? {show: split[0], hide: split[1]} : split[0]; - } - - // store $id to identify the triggering element in events - // give priority to options.id, otherwise, try to use - // element id if defined - $tooltip.$id = options.id || element.attr('id') || ''; - - // Support scope as string options - if(options.title) { - scope.title = $sce.trustAsHtml(options.title); - } - - // Provide scope helpers - scope.$setEnabled = function(isEnabled) { - scope.$$postDigest(function() { - $tooltip.setEnabled(isEnabled); - }); - }; - scope.$hide = function() { - scope.$$postDigest(function() { - $tooltip.hide(); - }); - }; - scope.$show = function() { - scope.$$postDigest(function() { - $tooltip.show(); - }); - }; - scope.$toggle = function() { - scope.$$postDigest(function() { - $tooltip.toggle(); - }); - }; - // Publish isShown as a protected var on scope - $tooltip.$isShown = scope.$isShown = false; - - // Private vars - var timeout, hoverState; - - // Support contentTemplate option - if(options.contentTemplate) { - $tooltip.$promise = $tooltip.$promise.then(function(template) { - var templateEl = angular.element(template); - return fetchTemplate(options.contentTemplate) - .then(function(contentTemplate) { - var contentEl = findElement('[ng-bind="content"]', templateEl[0]); - if(!contentEl.length) contentEl = findElement('[ng-bind="title"]', templateEl[0]); - contentEl.removeAttr('ng-bind').html(contentTemplate); - return templateEl[0].outerHTML; - }); - }); - } - - // Fetch, compile then initialize tooltip - var tipLinker, tipElement, tipTemplate, tipContainer, tipScope; - $tooltip.$promise.then(function(template) { - if(angular.isObject(template)) template = template.data; - if(options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); - template = trim.apply(template); - tipTemplate = template; - tipLinker = $compile(template); - $tooltip.init(); - }); - - $tooltip.init = function() { - - // Options: delay - if (options.delay && angular.isNumber(options.delay)) { - options.delay = { - show: options.delay, - hide: options.delay + var defaults = this.defaults = { + animation: 'am-fade', + template: 'tab/tab.tpl.html', + navClass: 'nav-tabs', + activeClass: 'active' }; - } - - // Replace trigger on touch devices ? - // if(isTouch && options.trigger === defaults.trigger) { - // options.trigger.replace(/hover/g, 'click'); - // } - - // Options : container - if(options.container === 'self') { - tipContainer = element; - } else if(angular.isElement(options.container)) { - tipContainer = options.container; - } else if(options.container) { - tipContainer = findElement(options.container); - } - // Options: trigger - bindTriggerEvents(); + var controller = this.controller = function ($scope, $element, $attrs) { + var self = this; + + // Attributes options + self.$options = angular.copy(defaults); + angular.forEach(['animation', 'navClass', 'activeClass'], function (key) { + if (angular.isDefined($attrs[key])) self.$options[key] = $attrs[key]; + }); + + // Publish options on scope + $scope.$navClass = self.$options.navClass; + $scope.$activeClass = self.$options.activeClass; + + self.$panes = $scope.$panes = []; + + // DEPRECATED: $viewChangeListeners, please use $activePaneChangeListeners + // Because we deprecated ngModel usage, we rename viewChangeListeners to + // activePaneChangeListeners to make more sense. + self.$activePaneChangeListeners = self.$viewChangeListeners = []; + + self.$push = function (pane) { + self.$panes.push(pane); + }; + + self.$remove = function (pane) { + var index = self.$panes.indexOf(pane); + var activeIndex = self.$panes.$active; + + // remove pane from $panes array + self.$panes.splice(index, 1); + + if (index < activeIndex) { + // we removed a pane before the active pane, so we need to + // decrement the active pane index + activeIndex--; + } + else if (index === activeIndex && activeIndex === self.$panes.length) { + // we remove the active pane and it was the one at the end, + // so select the previous one + activeIndex--; + } + self.$setActive(activeIndex); + }; + + self.$panes.$active = 0; + self.$setActive = $scope.$setActive = function (value) { + self.$panes.$active = value; + self.$activePaneChangeListeners.forEach(function (fn) { + fn(); + }); + }; - // Options: target - if(options.target) { - options.target = angular.isElement(options.target) ? options.target : findElement(options.target); - } + }; - // Options: show - if(options.show) { - scope.$$postDigest(function() { - options.trigger === 'focus' ? element[0].focus() : $tooltip.show(); - }); - } + this.$get = function () { + var $tab = {}; + $tab.defaults = defaults; + $tab.controller = controller; + return $tab; + }; - }; + }) + + .directive('bsTabs', ["$window", "$animate", "$tab", "$parse", function ($window, $animate, $tab, $parse) { + + var defaults = $tab.defaults; + + return { + require: ['?ngModel', 'bsTabs'], + transclude: true, + scope: true, + controller: ['$scope', '$element', '$attrs', $tab.controller], + templateUrl: function (element, attr) { + return attr.template || defaults.template; + }, + link: function postLink(scope, element, attrs, controllers) { + + var ngModelCtrl = controllers[0]; + var bsTabsCtrl = controllers[1]; + + // DEPRECATED: ngModel, please use bsActivePane + // 'ngModel' is deprecated bacause if interferes with form validation + // and status, so avoid using it here. + if (ngModelCtrl) { + console.warn('Usage of ngModel is deprecated, please use bsActivePane instead!'); + + // Update the modelValue following + bsTabsCtrl.$activePaneChangeListeners.push(function () { + ngModelCtrl.$setViewValue(bsTabsCtrl.$panes.$active); + }); + + // modelValue -> $formatters -> viewValue + ngModelCtrl.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + bsTabsCtrl.$setActive(modelValue * 1); + return modelValue; + }); + + } + + if (attrs.bsActivePane) { + // adapted from angularjs ngModelController bindings + // https://github.com/angular/angular.js/blob/v1.3.1/src%2Fng%2Fdirective%2Finput.js#L1730 + var parsedBsActivePane = $parse(attrs.bsActivePane); + + // Update bsActivePane value with change + bsTabsCtrl.$activePaneChangeListeners.push(function () { + parsedBsActivePane.assign(scope, bsTabsCtrl.$panes.$active); + }); + + // watch bsActivePane for value changes + scope.$watch(attrs.bsActivePane, function (newValue, oldValue) { + bsTabsCtrl.$setActive(newValue * 1); + }, true); + } + } + }; - $tooltip.destroy = function() { + }]) - // Unbind events - unbindTriggerEvents(); + .directive('bsPane', ["$window", "$animate", "$sce", function ($window, $animate, $sce) { - // Remove element - destroyTipElement(); + return { + require: ['^?ngModel', '^bsTabs'], + scope: true, + link: function postLink(scope, element, attrs, controllers) { - // Destroy scope - scope.$destroy(); + var ngModelCtrl = controllers[0]; + var bsTabsCtrl = controllers[1]; - }; + // Add base class + element.addClass('tab-pane'); - $tooltip.enter = function() { + // Observe title attribute for change + attrs.$observe('title', function (newValue, oldValue) { + scope.title = $sce.trustAsHtml(newValue); + }); - clearTimeout(timeout); - hoverState = 'in'; - if (!options.delay || !options.delay.show) { - return $tooltip.show(); - } + // Add animation class + if (bsTabsCtrl.$options.animation) { + element.addClass(bsTabsCtrl.$options.animation); + } - timeout = setTimeout(function() { - if (hoverState ==='in') $tooltip.show(); - }, options.delay.show); + // Push pane to parent bsTabs controller + bsTabsCtrl.$push(scope); - }; + // remove pane from tab controller when pane is destroyed + scope.$on('$destroy', function () { + bsTabsCtrl.$remove(scope); + }); - $tooltip.show = function() { - if (!options.bsEnabled || $tooltip.$isShown) return; + function render() { + var index = bsTabsCtrl.$panes.indexOf(scope); + var active = bsTabsCtrl.$panes.$active; + $animate[index === active ? 'addClass' : 'removeClass'](element, bsTabsCtrl.$options.activeClass); + } - scope.$emit(options.prefixEvent + '.show.before', $tooltip); - var parent, after; - if (options.container) { - parent = tipContainer; - if (tipContainer[0].lastChild) { - after = angular.element(tipContainer[0].lastChild); - } else { - after = null; - } - } else { - parent = null; - after = element; - } - - - // Hide any existing tipElement - if(tipElement) destroyTipElement(); - // Fetch a cloned element linked from template - tipScope = $tooltip.$scope.$new(); - tipElement = $tooltip.$element = tipLinker(tipScope, function(clonedElement, scope) {}); - - // Set the initial positioning. Make the tooltip invisible - // so IE doesn't try to focus on it off screen. - tipElement.css({top: '-9999px', left: '-9999px', display: 'block', visibility: 'hidden'}); - - // Options: animation - if(options.animation) tipElement.addClass(options.animation); - // Options: type - if(options.type) tipElement.addClass(options.prefixClass + '-' + options.type); - // Options: custom classes - if(options.customClass) tipElement.addClass(options.customClass); - - // Support v1.3+ $animate - // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 - var promise = $animate.enter(tipElement, parent, after, enterAnimateCallback); - if(promise && promise.then) promise.then(enterAnimateCallback); - - $tooltip.$isShown = scope.$isShown = true; - safeDigest(scope); - $$rAF(function () { - $tooltip.$applyPlacement(); - - // Once placed, make the tooltip visible - if(tipElement) tipElement.css({visibility: 'visible'}); - }); // var a = bodyEl.offsetWidth + 1; ? - - // Bind events - if(options.keyboard) { - if(options.trigger !== 'focus') { - $tooltip.focus(); - } - bindKeyboardEvents(); - } + bsTabsCtrl.$activePaneChangeListeners.push(function () { + render(); + }); + render(); - if(options.autoClose) { - bindAutoCloseEvents(); - } + } + }; - }; + }]); - function enterAnimateCallback() { - scope.$emit(options.prefixEvent + '.show', $tooltip); - } +// Source: scrollspy.js + angular.module('mgcrea.ngStrap.scrollspy', ['mgcrea.ngStrap.helpers.debounce', 'mgcrea.ngStrap.helpers.dimensions']) - $tooltip.leave = function() { + .provider('$scrollspy', function () { - clearTimeout(timeout); - hoverState = 'out'; - if (!options.delay || !options.delay.hide) { - return $tooltip.hide(); - } - timeout = setTimeout(function () { - if (hoverState === 'out') { - $tooltip.hide(); - } - }, options.delay.hide); + // Pool of registered spies + var spies = this.$$spies = {}; - }; + var defaults = this.defaults = { + debounce: 150, + throttle: 100, + offset: 100 + }; - var _blur; - var _tipToHide; - $tooltip.hide = function(blur) { + this.$get = ["$window", "$document", "$rootScope", "dimensions", "debounce", "throttle", function ($window, $document, $rootScope, dimensions, debounce, throttle) { - if(!$tooltip.$isShown) return; - scope.$emit(options.prefixEvent + '.hide.before', $tooltip); + var windowEl = angular.element($window); + var docEl = angular.element($document.prop('documentElement')); + var bodyEl = angular.element($window.document.body); - // store blur value for leaveAnimateCallback to use - _blur = blur; + // Helper functions - // store current tipElement reference to use - // in leaveAnimateCallback - _tipToHide = tipElement; + function nodeName(element, name) { + return element[0].nodeName && element[0].nodeName.toLowerCase() === name.toLowerCase(); + } - // Support v1.3+ $animate - // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 - var promise = $animate.leave(tipElement, leaveAnimateCallback); - if(promise && promise.then) promise.then(leaveAnimateCallback); + function ScrollSpyFactory(config) { + + // Common vars + var options = angular.extend({}, defaults, config); + if (!options.element) options.element = bodyEl; + var isWindowSpy = nodeName(options.element, 'body'); + var scrollEl = isWindowSpy ? windowEl : options.element; + var scrollId = isWindowSpy ? 'window' : options.id; + + // Use existing spy + if (spies[scrollId]) { + spies[scrollId].$$count++; + return spies[scrollId]; + } + + var $scrollspy = {}; + + // Private vars + var unbindViewContentLoaded, unbindIncludeContentLoaded; + var trackedElements = $scrollspy.$trackedElements = []; + var sortedElements = []; + var activeTarget; + var debouncedCheckPosition; + var throttledCheckPosition; + var debouncedCheckOffsets; + var viewportHeight; + var scrollTop; + + $scrollspy.init = function () { + + // Setup internal ref counter + this.$$count = 1; + + // Bind events + debouncedCheckPosition = debounce(this.checkPosition, options.debounce); + throttledCheckPosition = throttle(this.checkPosition, options.throttle); + scrollEl.on('click', this.checkPositionWithEventLoop); + windowEl.on('resize', debouncedCheckPosition); + scrollEl.on('scroll', throttledCheckPosition); + + debouncedCheckOffsets = debounce(this.checkOffsets, options.debounce); + unbindViewContentLoaded = $rootScope.$on('$viewContentLoaded', debouncedCheckOffsets); + unbindIncludeContentLoaded = $rootScope.$on('$includeContentLoaded', debouncedCheckOffsets); + debouncedCheckOffsets(); + + // Register spy for reuse + if (scrollId) { + spies[scrollId] = $scrollspy; + } + + }; + + $scrollspy.destroy = function () { + + // Check internal ref counter + this.$$count--; + if (this.$$count > 0) { + return; + } + + // Unbind events + scrollEl.off('click', this.checkPositionWithEventLoop); + windowEl.off('resize', debouncedCheckPosition); + scrollEl.off('scroll', throttledCheckPosition); + unbindViewContentLoaded(); + unbindIncludeContentLoaded(); + if (scrollId) { + delete spies[scrollId]; + } + }; + + $scrollspy.checkPosition = function () { + + // Not ready yet + if (!sortedElements.length) return; + + // Calculate the scroll position + scrollTop = (isWindowSpy ? $window.pageYOffset : scrollEl.prop('scrollTop')) || 0; + + // Calculate the viewport height for use by the components + viewportHeight = Math.max($window.innerHeight, docEl.prop('clientHeight')); + + // Activate first element if scroll is smaller + if (scrollTop < sortedElements[0].offsetTop && activeTarget !== sortedElements[0].target) { + return $scrollspy.$activateElement(sortedElements[0]); + } + + // Activate proper element + for (var i = sortedElements.length; i--;) { + if (angular.isUndefined(sortedElements[i].offsetTop) || sortedElements[i].offsetTop === null) continue; + if (activeTarget === sortedElements[i].target) continue; + if (scrollTop < sortedElements[i].offsetTop) continue; + if (sortedElements[i + 1] && scrollTop > sortedElements[i + 1].offsetTop) continue; + return $scrollspy.$activateElement(sortedElements[i]); + } + + }; + + $scrollspy.checkPositionWithEventLoop = function () { + // IE 9 throws an error if we use 'this' instead of '$scrollspy' + // in this setTimeout call + setTimeout($scrollspy.checkPosition, 1); + }; + + // Protected methods + + $scrollspy.$activateElement = function (element) { + if (activeTarget) { + var activeElement = $scrollspy.$getTrackedElement(activeTarget); + if (activeElement) { + activeElement.source.removeClass('active'); + if (nodeName(activeElement.source, 'li') && nodeName(activeElement.source.parent().parent(), 'li')) { + activeElement.source.parent().parent().removeClass('active'); + } + } + } + activeTarget = element.target; + element.source.addClass('active'); + if (nodeName(element.source, 'li') && nodeName(element.source.parent().parent(), 'li')) { + element.source.parent().parent().addClass('active'); + } + }; + + $scrollspy.$getTrackedElement = function (target) { + return trackedElements.filter(function (obj) { + return obj.target === target; + })[0]; + }; + + // Track offsets behavior + + $scrollspy.checkOffsets = function () { + + angular.forEach(trackedElements, function (trackedElement) { + var targetElement = document.querySelector(trackedElement.target); + trackedElement.offsetTop = targetElement ? dimensions.offset(targetElement).top : null; + if (options.offset && trackedElement.offsetTop !== null) trackedElement.offsetTop -= options.offset * 1; + }); + + sortedElements = trackedElements + .filter(function (el) { + return el.offsetTop !== null; + }) + .sort(function (a, b) { + return a.offsetTop - b.offsetTop; + }); + + debouncedCheckPosition(); + + }; + + $scrollspy.trackElement = function (target, source) { + trackedElements.push({target: target, source: source}); + }; + + $scrollspy.untrackElement = function (target, source) { + var toDelete; + for (var i = trackedElements.length; i--;) { + if (trackedElements[i].target === target && trackedElements[i].source === source) { + toDelete = i; + break; + } + } + trackedElements = trackedElements.splice(toDelete, 1); + }; + + $scrollspy.activate = function (i) { + trackedElements[i].addClass('active'); + }; + + // Initialize plugin + + $scrollspy.init(); + return $scrollspy; - $tooltip.$isShown = scope.$isShown = false; - safeDigest(scope); + } - // Unbind events - if(options.keyboard && tipElement !== null) { - unbindKeyboardEvents(); - } + return ScrollSpyFactory; - if(options.autoClose && tipElement !== null) { - unbindAutoCloseEvents(); - } - }; + }]; - function leaveAnimateCallback() { - scope.$emit(options.prefixEvent + '.hide', $tooltip); + }) - // check if current tipElement still references - // the same element when hide was called - if (tipElement === _tipToHide) { - // Allow to blur the input when hidden, like when pressing enter key - if(_blur && options.trigger === 'focus') { - return element[0].blur(); - } + .directive('bsScrollspy', ["$rootScope", "debounce", "dimensions", "$scrollspy", function ($rootScope, debounce, dimensions, $scrollspy) { - // clean up child scopes - destroyTipElement(); - } - } - - $tooltip.toggle = function() { - $tooltip.$isShown ? $tooltip.leave() : $tooltip.enter(); - }; - - $tooltip.focus = function() { - tipElement[0].focus(); - }; - - $tooltip.setEnabled = function(isEnabled) { - options.bsEnabled = isEnabled; - }; - - // Protected methods - - $tooltip.$applyPlacement = function() { - if(!tipElement) return; - - // Determine if we're doing an auto or normal placement - var placement = options.placement, - autoToken = /\s?auto?\s?/i, - autoPlace = autoToken.test(placement); - - if (autoPlace) { - placement = placement.replace(autoToken, '') || defaults.placement; - } - - // Need to add the position class before we get - // the offsets - tipElement.addClass(options.placement); - - // Get the position of the target element - // and the height and width of the tooltip so we can center it. - var elementPosition = getPosition(), - tipWidth = tipElement.prop('offsetWidth'), - tipHeight = tipElement.prop('offsetHeight'); - - // If we're auto placing, we need to check the positioning - if (autoPlace) { - var originalPlacement = placement; - var container = options.container ? angular.element(document.querySelector(options.container)) : element.parent(); - var containerPosition = getPosition(container); - - // Determine if the vertical placement - if (originalPlacement.indexOf('bottom') >= 0 && elementPosition.bottom + tipHeight > containerPosition.bottom) { - placement = originalPlacement.replace('bottom', 'top'); - } else if (originalPlacement.indexOf('top') >= 0 && elementPosition.top - tipHeight < containerPosition.top) { - placement = originalPlacement.replace('top', 'bottom'); - } + return { + restrict: 'EAC', + link: function postLink(scope, element, attr) { - // Determine the horizontal placement - // The exotic placements of left and right are opposite of the standard placements. Their arrows are put on the left/right - // and flow in the opposite direction of their placement. - if ((originalPlacement === 'right' || originalPlacement === 'bottom-left' || originalPlacement === 'top-left') && - elementPosition.right + tipWidth > containerPosition.width) { + var options = {scope: scope}; + angular.forEach(['offset', 'target'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); - placement = originalPlacement === 'right' ? 'left' : placement.replace('left', 'right'); - } else if ((originalPlacement === 'left' || originalPlacement === 'bottom-right' || originalPlacement === 'top-right') && - elementPosition.left - tipWidth < containerPosition.left) { + var scrollspy = $scrollspy(options); + scrollspy.trackElement(options.target, element); - placement = originalPlacement === 'left' ? 'right' : placement.replace('right', 'left'); - } + scope.$on('$destroy', function () { + if (scrollspy) { + scrollspy.untrackElement(options.target, element); + scrollspy.destroy(); + } + options = null; + scrollspy = null; + }); - tipElement.removeClass(originalPlacement).addClass(placement); - } - - // Get the tooltip's top and left coordinates to center it with this directive. - var tipPosition = getCalculatedOffset(placement, elementPosition, tipWidth, tipHeight); - applyPlacementCss(tipPosition.top, tipPosition.left); - }; - - $tooltip.$onKeyUp = function(evt) { - if (evt.which === 27 && $tooltip.$isShown) { - $tooltip.hide(); - evt.stopPropagation(); - } - }; - - $tooltip.$onFocusKeyUp = function(evt) { - if (evt.which === 27) { - element[0].blur(); - evt.stopPropagation(); - } - }; - - $tooltip.$onFocusElementMouseDown = function(evt) { - evt.preventDefault(); - evt.stopPropagation(); - // Some browsers do not auto-focus buttons (eg. Safari) - $tooltip.$isShown ? element[0].blur() : element[0].focus(); - }; - - // bind/unbind events - function bindTriggerEvents() { - var triggers = options.trigger.split(' '); - angular.forEach(triggers, function(trigger) { - if(trigger === 'click') { - element.on('click', $tooltip.toggle); - } else if(trigger !== 'manual') { - element.on(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); - element.on(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); - nodeName === 'button' && trigger !== 'hover' && element.on(isTouch ? 'touchstart' : 'mousedown', $tooltip.$onFocusElementMouseDown); - } - }); - } - - function unbindTriggerEvents() { - var triggers = options.trigger.split(' '); - for (var i = triggers.length; i--;) { - var trigger = triggers[i]; - if(trigger === 'click') { - element.off('click', $tooltip.toggle); - } else if(trigger !== 'manual') { - element.off(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); - element.off(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); - nodeName === 'button' && trigger !== 'hover' && element.off(isTouch ? 'touchstart' : 'mousedown', $tooltip.$onFocusElementMouseDown); - } - } - } - - function bindKeyboardEvents() { - if(options.trigger !== 'focus') { - tipElement.on('keyup', $tooltip.$onKeyUp); - } else { - element.on('keyup', $tooltip.$onFocusKeyUp); - } - } - - function unbindKeyboardEvents() { - if(options.trigger !== 'focus') { - tipElement.off('keyup', $tooltip.$onKeyUp); - } else { - element.off('keyup', $tooltip.$onFocusKeyUp); - } - } - - var _autoCloseEventsBinded = false; - function bindAutoCloseEvents() { - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - // Stop propagation when clicking inside tooltip - tipElement.on('click', stopEventPropagation); - - // Hide when clicking outside tooltip - $body.on('click', $tooltip.hide); - - _autoCloseEventsBinded = true; - }, 0, false); - } - - function unbindAutoCloseEvents() { - if (_autoCloseEventsBinded) { - tipElement.off('click', stopEventPropagation); - $body.off('click', $tooltip.hide); - _autoCloseEventsBinded = false; - } - } - - function stopEventPropagation(event) { - event.stopPropagation(); - } - - // Private methods - - function getPosition($element) { - $element = $element || (options.target || element); - - var el = $element[0]; - - var elRect = el.getBoundingClientRect(); - if (elRect.width === null) { - // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 - elRect = angular.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }); - } - - var elPos; - if (options.container === 'body') { - elPos = dimensions.offset(el); - } else { - elPos = dimensions.position(el); - } - - return angular.extend({}, elRect, elPos); - } - - function getCalculatedOffset(placement, position, actualWidth, actualHeight) { - var offset; - var split = placement.split('-'); - - switch (split[0]) { - case 'right': - offset = { - top: position.top + position.height / 2 - actualHeight / 2, - left: position.left + position.width - }; - break; - case 'bottom': - offset = { - top: position.top + position.height, - left: position.left + position.width / 2 - actualWidth / 2 - }; - break; - case 'left': - offset = { - top: position.top + position.height / 2 - actualHeight / 2, - left: position.left - actualWidth - }; - break; - default: - offset = { - top: position.top - actualHeight, - left: position.left + position.width / 2 - actualWidth / 2 + } }; - break; - } - - if(!split[1]) { - return offset; - } - - // Add support for corners @todo css - if(split[0] === 'top' || split[0] === 'bottom') { - switch (split[1]) { - case 'left': - offset.left = position.left; - break; - case 'right': - offset.left = position.left + position.width - actualWidth; - } - } else if(split[0] === 'left' || split[0] === 'right') { - switch (split[1]) { - case 'top': - offset.top = position.top - actualHeight; - break; - case 'bottom': - offset.top = position.top + position.height; - } - } - - return offset; - } - - function applyPlacementCss(top, left) { - tipElement.css({ top: top + 'px', left: left + 'px' }); - } - function destroyTipElement() { - // Cancel pending callbacks - clearTimeout(timeout); + }]) - if($tooltip.$isShown && tipElement !== null) { - if(options.autoClose) { - unbindAutoCloseEvents(); - } - - if(options.keyboard) { - unbindKeyboardEvents(); - } - } - if(tipScope) { - tipScope.$destroy(); - tipScope = null; - } + .directive('bsScrollspyList', ["$rootScope", "debounce", "dimensions", "$scrollspy", function ($rootScope, debounce, dimensions, $scrollspy) { - if(tipElement) { - tipElement.remove(); - tipElement = $tooltip.$element = null; - } - } + return { + restrict: 'A', + compile: function postLink(element, attr) { + var children = element[0].querySelectorAll('li > a[href]'); + angular.forEach(children, function (child) { + var childEl = angular.element(child); + childEl.parent().attr('bs-scrollspy', '').attr('data-target', childEl.attr('href')); + }); + } - return $tooltip; + }; - } + }]); - // Helper functions +// Source: timepicker.js + angular.module('mgcrea.ngStrap.timepicker', [ + 'mgcrea.ngStrap.helpers.dateParser', + 'mgcrea.ngStrap.helpers.dateFormatter', + 'mgcrea.ngStrap.tooltip']) + + .provider('$timepicker', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'timepicker', + placement: 'bottom-left', + template: 'timepicker/timepicker.tpl.html', + trigger: 'focus', + container: false, + keyboard: true, + html: false, + delay: 0, + // lang: $locale.id, + useNative: true, + timeType: 'date', + timeFormat: 'shortTime', + modelTimeFormat: null, + autoclose: false, + minTime: -Infinity, + maxTime: +Infinity, + length: 5, + hourStep: 1, + minuteStep: 5, + iconUp: 'glyphicon glyphicon-chevron-up', + iconDown: 'glyphicon glyphicon-chevron-down', + arrowBehavior: 'pager' + }; - function safeDigest(scope) { - scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest(); - } + this.$get = ["$window", "$document", "$rootScope", "$sce", "$dateFormatter", "$tooltip", "$timeout", function ($window, $document, $rootScope, $sce, $dateFormatter, $tooltip, $timeout) { + + var bodyEl = angular.element($window.document.body); + var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + var isTouch = ('createTouch' in $window.document) && isNative; + if (!defaults.lang) defaults.lang = $dateFormatter.getDefaultLocale(); + + function timepickerFactory(element, controller, config) { + + var $timepicker = $tooltip(element, angular.extend({}, defaults, config)); + var parentScope = config.scope; + var options = $timepicker.$options; + var scope = $timepicker.$scope; + + var lang = options.lang; + var formatDate = function (date, format) { + return $dateFormatter.formatDate(date, format, lang); + }; + + // View vars + + var selectedIndex = 0; + var startDate = controller.$dateValue || new Date(); + var viewDate = { + hour: startDate.getHours(), + meridian: startDate.getHours() < 12, + minute: startDate.getMinutes(), + second: startDate.getSeconds(), + millisecond: startDate.getMilliseconds() + }; + + var format = $dateFormatter.getDatetimeFormat(options.timeFormat, lang); + + var hoursFormat = $dateFormatter.hoursFormat(format), + timeSeparator = $dateFormatter.timeSeparator(format), + minutesFormat = $dateFormatter.minutesFormat(format), + showAM = $dateFormatter.showAM(format); + + scope.$iconUp = options.iconUp; + scope.$iconDown = options.iconDown; + + // Scope methods + + scope.$select = function (date, index) { + $timepicker.select(date, index); + }; + scope.$moveIndex = function (value, index) { + $timepicker.$moveIndex(value, index); + }; + scope.$switchMeridian = function (date) { + $timepicker.switchMeridian(date); + }; + + // Public methods + + $timepicker.update = function (date) { + // console.warn('$timepicker.update() newValue=%o', date); + if (angular.isDate(date) && !isNaN(date.getTime())) { + $timepicker.$date = date; + angular.extend(viewDate, { + hour: date.getHours(), + minute: date.getMinutes(), + second: date.getSeconds(), + millisecond: date.getMilliseconds() + }); + $timepicker.$build(); + } else if (!$timepicker.$isBuilt) { + $timepicker.$build(); + } + }; + + $timepicker.select = function (date, index, keep) { + // console.warn('$timepicker.select', date, scope.$mode); + if (!controller.$dateValue || isNaN(controller.$dateValue.getTime())) controller.$dateValue = new Date(1970, 0, 1); + if (!angular.isDate(date)) date = new Date(date); + if (index === 0) controller.$dateValue.setHours(date.getHours()); + else if (index === 1) controller.$dateValue.setMinutes(date.getMinutes()); + controller.$setViewValue(angular.copy(controller.$dateValue)); + controller.$render(); + if (options.autoclose && !keep) { + $timeout(function () { + $timepicker.hide(true); + }); + } + }; + + $timepicker.switchMeridian = function (date) { + if (!controller.$dateValue || isNaN(controller.$dateValue.getTime())) { + return; + } + var hours = (date || controller.$dateValue).getHours(); + controller.$dateValue.setHours(hours < 12 ? hours + 12 : hours - 12); + controller.$setViewValue(angular.copy(controller.$dateValue)); + controller.$render(); + }; + + // Protected methods + + $timepicker.$build = function () { + // console.warn('$timepicker.$build() viewDate=%o', viewDate); + var i, midIndex = scope.midIndex = parseInt(options.length / 2, 10); + var hours = [], hour; + for (i = 0; i < options.length; i++) { + hour = new Date(1970, 0, 1, viewDate.hour - (midIndex - i) * options.hourStep); + hours.push({ + date: hour, + label: formatDate(hour, hoursFormat), + selected: $timepicker.$date && $timepicker.$isSelected(hour, 0), + disabled: $timepicker.$isDisabled(hour, 0) + }); + } + var minutes = [], minute; + for (i = 0; i < options.length; i++) { + minute = new Date(1970, 0, 1, 0, viewDate.minute - (midIndex - i) * options.minuteStep); + minutes.push({ + date: minute, + label: formatDate(minute, minutesFormat), + selected: $timepicker.$date && $timepicker.$isSelected(minute, 1), + disabled: $timepicker.$isDisabled(minute, 1) + }); + } + + var rows = []; + for (i = 0; i < options.length; i++) { + rows.push([hours[i], minutes[i]]); + } + scope.rows = rows; + scope.showAM = showAM; + scope.isAM = ($timepicker.$date || hours[midIndex].date).getHours() < 12; + scope.timeSeparator = timeSeparator; + $timepicker.$isBuilt = true; + }; + + $timepicker.$isSelected = function (date, index) { + if (!$timepicker.$date) return false; + else if (index === 0) { + return date.getHours() === $timepicker.$date.getHours(); + } else if (index === 1) { + return date.getMinutes() === $timepicker.$date.getMinutes(); + } + }; + + $timepicker.$isDisabled = function (date, index) { + var selectedTime; + if (index === 0) { + selectedTime = date.getTime() + viewDate.minute * 6e4; + } else if (index === 1) { + selectedTime = date.getTime() + viewDate.hour * 36e5; + } + return selectedTime < options.minTime * 1 || selectedTime > options.maxTime * 1; + }; + + scope.$arrowAction = function (value, index) { + if (options.arrowBehavior === 'picker') { + $timepicker.$setTimeByStep(value, index); + } else { + $timepicker.$moveIndex(value, index); + } + }; + + $timepicker.$setTimeByStep = function (value, index) { + var newDate = new Date($timepicker.$date); + var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; + var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; + if (index === 0) { + newDate.setHours(hours - (parseInt(options.hourStep, 10) * value)); + } + else { + newDate.setMinutes(minutes - (parseInt(options.minuteStep, 10) * value)); + } + $timepicker.select(newDate, index, true); + }; + + $timepicker.$moveIndex = function (value, index) { + var targetDate; + if (index === 0) { + targetDate = new Date(1970, 0, 1, viewDate.hour + (value * options.length), viewDate.minute); + angular.extend(viewDate, {hour: targetDate.getHours()}); + } else if (index === 1) { + targetDate = new Date(1970, 0, 1, viewDate.hour, viewDate.minute + (value * options.length * options.minuteStep)); + angular.extend(viewDate, {minute: targetDate.getMinutes()}); + } + $timepicker.$build(); + }; + + $timepicker.$onMouseDown = function (evt) { + // Prevent blur on mousedown on .dropdown-menu + if (evt.target.nodeName.toLowerCase() !== 'input') evt.preventDefault(); + evt.stopPropagation(); + // Emulate click for mobile devices + if (isTouch) { + var targetEl = angular.element(evt.target); + if (targetEl[0].nodeName.toLowerCase() !== 'button') { + targetEl = targetEl.parent(); + } + targetEl.triggerHandler('click'); + } + }; + + $timepicker.$onKeyDown = function (evt) { + if (!/(38|37|39|40|13)/.test(evt.keyCode) || evt.shiftKey || evt.altKey) return; + evt.preventDefault(); + evt.stopPropagation(); + + // Close on enter + if (evt.keyCode === 13) return $timepicker.hide(true); + + // Navigate with keyboard + var newDate = new Date($timepicker.$date); + var hours = newDate.getHours(), hoursLength = formatDate(newDate, hoursFormat).length; + var minutes = newDate.getMinutes(), minutesLength = formatDate(newDate, minutesFormat).length; + var lateralMove = /(37|39)/.test(evt.keyCode); + var count = 2 + showAM * 1; + + // Navigate indexes (left, right) + if (lateralMove) { + if (evt.keyCode === 37) selectedIndex = selectedIndex < 1 ? count - 1 : selectedIndex - 1; + else if (evt.keyCode === 39) selectedIndex = selectedIndex < count - 1 ? selectedIndex + 1 : 0; + } + + // Update values (up, down) + var selectRange = [0, hoursLength]; + if (selectedIndex === 0) { + if (evt.keyCode === 38) newDate.setHours(hours - parseInt(options.hourStep, 10)); + else if (evt.keyCode === 40) newDate.setHours(hours + parseInt(options.hourStep, 10)); + // re-calculate hours length because we have changed hours value + hoursLength = formatDate(newDate, hoursFormat).length; + selectRange = [0, hoursLength]; + } else if (selectedIndex === 1) { + if (evt.keyCode === 38) newDate.setMinutes(minutes - parseInt(options.minuteStep, 10)); + else if (evt.keyCode === 40) newDate.setMinutes(minutes + parseInt(options.minuteStep, 10)); + // re-calculate minutes length because we have changes minutes value + minutesLength = formatDate(newDate, minutesFormat).length; + selectRange = [hoursLength + 1, hoursLength + 1 + minutesLength]; + } else if (selectedIndex === 2) { + if (!lateralMove) $timepicker.switchMeridian(); + selectRange = [hoursLength + 1 + minutesLength + 1, hoursLength + 1 + minutesLength + 3]; + } + $timepicker.select(newDate, selectedIndex, true); + createSelection(selectRange[0], selectRange[1]); + parentScope.$digest(); + }; + + // Private + + function createSelection(start, end) { + if (element[0].createTextRange) { + var selRange = element[0].createTextRange(); + selRange.collapse(true); + selRange.moveStart('character', start); + selRange.moveEnd('character', end); + selRange.select(); + } else if (element[0].setSelectionRange) { + element[0].setSelectionRange(start, end); + } else if (angular.isUndefined(element[0].selectionStart)) { + element[0].selectionStart = start; + element[0].selectionEnd = end; + } + } + + function focusElement() { + element[0].focus(); + } + + // Overrides + + var _init = $timepicker.init; + $timepicker.init = function () { + if (isNative && options.useNative) { + element.prop('type', 'time'); + element.css('-webkit-appearance', 'textfield'); + return; + } else if (isTouch) { + element.prop('type', 'text'); + element.attr('readonly', 'true'); + element.on('click', focusElement); + } + _init(); + }; + + var _destroy = $timepicker.destroy; + $timepicker.destroy = function () { + if (isNative && options.useNative) { + element.off('click', focusElement); + } + _destroy(); + }; + + var _show = $timepicker.show; + $timepicker.show = function () { + _show(); + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + $timepicker.$element.on(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); + if (options.keyboard) { + element.on('keydown', $timepicker.$onKeyDown); + } + }, 0, false); + }; + + var _hide = $timepicker.hide; + $timepicker.hide = function (blur) { + if (!$timepicker.$isShown) return; + $timepicker.$element.off(isTouch ? 'touchstart' : 'mousedown', $timepicker.$onMouseDown); + if (options.keyboard) { + element.off('keydown', $timepicker.$onKeyDown); + } + _hide(blur); + }; + + return $timepicker; - function findElement(query, element) { - return angular.element((element || document).querySelectorAll(query)); - } + } - var fetchPromises = {}; - function fetchTemplate(template) { - if(fetchPromises[template]) return fetchPromises[template]; - return (fetchPromises[template] = $q.when($templateCache.get(template) || $http.get(template)) - .then(function(res) { - if(angular.isObject(res)) { - $templateCache.put(template, res.data); - return res.data; - } - return res; - })); - } + timepickerFactory.defaults = defaults; + return timepickerFactory; + + }]; + + }) + + + .directive('bsTimepicker', ["$window", "$parse", "$q", "$dateFormatter", "$dateParser", "$timepicker", function ($window, $parse, $q, $dateFormatter, $dateParser, $timepicker) { + + var defaults = $timepicker.defaults; + var isNative = /(ip(a|o)d|iphone|android)/ig.test($window.navigator.userAgent); + var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout; + + return { + restrict: 'EAC', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { + + // Directive options + var options = {scope: scope, controller: controller}; + angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'autoclose', 'timeType', 'timeFormat', 'modelTimeFormat', 'useNative', 'hourStep', 'minuteStep', 'length', 'arrowBehavior', 'iconUp', 'iconDown', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // Visibility binding support + attr.bsShow && scope.$watch(attr.bsShow, function (newValue, oldValue) { + if (!timepicker || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(timepicker),?/i); + newValue === true ? timepicker.show() : timepicker.hide(); + }); + + // Initialize timepicker + if (isNative && (options.useNative || defaults.useNative)) options.timeFormat = 'HH:mm'; + var timepicker = $timepicker(element, controller, options); + options = timepicker.$options; + + var lang = options.lang; + var formatDate = function (date, format) { + return $dateFormatter.formatDate(date, format, lang); + }; + + // Initialize parser + var dateParser = $dateParser({format: options.timeFormat, lang: lang}); + + // Observe attributes for changes + angular.forEach(['minTime', 'maxTime'], function (key) { + // console.warn('attr.$observe(%s)', key, attr[key]); + angular.isDefined(attr[key]) && attr.$observe(key, function (newValue) { + timepicker.$options[key] = dateParser.getTimeForAttribute(key, newValue); + !isNaN(timepicker.$options[key]) && timepicker.$build(); + validateAgainstMinMaxTime(controller.$dateValue); + }); + }); + + // Watch model for changes + scope.$watch(attr.ngModel, function (newValue, oldValue) { + // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue, controller.$dateValue); + timepicker.update(controller.$dateValue); + }, true); + + function validateAgainstMinMaxTime(parsedTime) { + if (!angular.isDate(parsedTime)) return; + var isMinValid = isNaN(options.minTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) >= options.minTime; + var isMaxValid = isNaN(options.maxTime) || new Date(parsedTime.getTime()).setFullYear(1970, 0, 1) <= options.maxTime; + var isValid = isMinValid && isMaxValid; + controller.$setValidity('date', isValid); + controller.$setValidity('min', isMinValid); + controller.$setValidity('max', isMaxValid); + // Only update the model when we have a valid date + if (!isValid) { + return; + } + controller.$dateValue = parsedTime; + } + + // viewValue -> $parsers -> modelValue + controller.$parsers.unshift(function (viewValue) { + // console.warn('$parser("%s"): viewValue=%o', element.attr('ng-model'), viewValue); + // Null values should correctly reset the model value & validity + if (!viewValue) { + // BREAKING CHANGE: + // return null (not undefined) when input value is empty, so angularjs 1.3 + // ngModelController can go ahead and run validators, like ngRequired + controller.$setValidity('date', true); + return null; + } + var parsedTime = angular.isDate(viewValue) ? viewValue : dateParser.parse(viewValue, controller.$dateValue); + if (!parsedTime || isNaN(parsedTime.getTime())) { + controller.$setValidity('date', false); + // return undefined, causes ngModelController to + // invalidate model value + return; + } else { + validateAgainstMinMaxTime(parsedTime); + } + if (options.timeType === 'string') { + return formatDate(parsedTime, options.modelTimeFormat || options.timeFormat); + } else if (options.timeType === 'number') { + return controller.$dateValue.getTime(); + } else if (options.timeType === 'unix') { + return controller.$dateValue.getTime() / 1000; + } else if (options.timeType === 'iso') { + return controller.$dateValue.toISOString(); + } else { + return new Date(controller.$dateValue); + } + }); + + // modelValue -> $formatters -> viewValue + controller.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + var date; + if (angular.isUndefined(modelValue) || modelValue === null) { + date = NaN; + } else if (angular.isDate(modelValue)) { + date = modelValue; + } else if (options.timeType === 'string') { + date = dateParser.parse(modelValue, null, options.modelTimeFormat); + } else if (options.timeType === 'unix') { + date = new Date(modelValue * 1000); + } else { + date = new Date(modelValue); + } + // Setup default value? + // if(isNaN(date.getTime())) date = new Date(new Date().setMinutes(0) + 36e5); + controller.$dateValue = date; + return getTimeFormattedString(); + }); + + // viewValue -> element + controller.$render = function () { + // console.warn('$render("%s"): viewValue=%o', element.attr('ng-model'), controller.$viewValue); + element.val(getTimeFormattedString()); + }; + + function getTimeFormattedString() { + return !controller.$dateValue || isNaN(controller.$dateValue.getTime()) ? '' : formatDate(controller.$dateValue, options.timeFormat); + } + + // Garbage collection + scope.$on('$destroy', function () { + if (timepicker) timepicker.destroy(); + options = null; + timepicker = null; + }); - return TooltipFactory; + } + }; - }]; + }]); - }) +// Source: tooltip.js + angular.module('mgcrea.ngStrap.tooltip', ['mgcrea.ngStrap.helpers.dimensions']) + + .provider('$tooltip', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + customClass: '', + prefixClass: 'tooltip', + prefixEvent: 'tooltip', + container: false, + target: false, + placement: 'top', + template: 'tooltip/tooltip.tpl.html', + contentTemplate: false, + trigger: 'hover focus', + keyboard: false, + html: false, + show: false, + title: '', + type: '', + delay: 0, + autoClose: false, + bsEnabled: true + }; - .directive('bsTooltip', ["$window", "$location", "$sce", "$tooltip", "$$rAF", function($window, $location, $sce, $tooltip, $$rAF) { + this.$get = ["$window", "$rootScope", "$compile", "$q", "$templateCache", "$http", "$animate", "$sce", "dimensions", "$$rAF", "$timeout", function ($window, $rootScope, $compile, $q, $templateCache, $http, $animate, $sce, dimensions, $$rAF, $timeout) { + + var trim = String.prototype.trim; + var isTouch = 'createTouch' in $window.document; + var htmlReplaceRegExp = /ng-bind="/ig; + var $body = angular.element($window.document); + + function TooltipFactory(element, config) { + + var $tooltip = {}; + + // Common vars + var nodeName = element[0].nodeName.toLowerCase(); + var options = $tooltip.$options = angular.extend({}, defaults, config); + $tooltip.$promise = fetchTemplate(options.template); + var scope = $tooltip.$scope = options.scope && options.scope.$new() || $rootScope.$new(); + if (options.delay && angular.isString(options.delay)) { + var split = options.delay.split(',').map(parseFloat); + options.delay = split.length > 1 ? {show: split[0], hide: split[1]} : split[0]; + } + + // store $id to identify the triggering element in events + // give priority to options.id, otherwise, try to use + // element id if defined + $tooltip.$id = options.id || element.attr('id') || ''; + + // Support scope as string options + if (options.title) { + scope.title = $sce.trustAsHtml(options.title); + } + + // Provide scope helpers + scope.$setEnabled = function (isEnabled) { + scope.$$postDigest(function () { + $tooltip.setEnabled(isEnabled); + }); + }; + scope.$hide = function () { + scope.$$postDigest(function () { + $tooltip.hide(); + }); + }; + scope.$show = function () { + scope.$$postDigest(function () { + $tooltip.show(); + }); + }; + scope.$toggle = function () { + scope.$$postDigest(function () { + $tooltip.toggle(); + }); + }; + // Publish isShown as a protected var on scope + $tooltip.$isShown = scope.$isShown = false; + + // Private vars + var timeout, hoverState; + + // Support contentTemplate option + if (options.contentTemplate) { + $tooltip.$promise = $tooltip.$promise.then(function (template) { + var templateEl = angular.element(template); + return fetchTemplate(options.contentTemplate) + .then(function (contentTemplate) { + var contentEl = findElement('[ng-bind="content"]', templateEl[0]); + if (!contentEl.length) contentEl = findElement('[ng-bind="title"]', templateEl[0]); + contentEl.removeAttr('ng-bind').html(contentTemplate); + return templateEl[0].outerHTML; + }); + }); + } + + // Fetch, compile then initialize tooltip + var tipLinker, tipElement, tipTemplate, tipContainer, tipScope; + $tooltip.$promise.then(function (template) { + if (angular.isObject(template)) template = template.data; + if (options.html) template = template.replace(htmlReplaceRegExp, 'ng-bind-html="'); + template = trim.apply(template); + tipTemplate = template; + tipLinker = $compile(template); + $tooltip.init(); + }); + + $tooltip.init = function () { + + // Options: delay + if (options.delay && angular.isNumber(options.delay)) { + options.delay = { + show: options.delay, + hide: options.delay + }; + } + + // Replace trigger on touch devices ? + // if(isTouch && options.trigger === defaults.trigger) { + // options.trigger.replace(/hover/g, 'click'); + // } + + // Options : container + if (options.container === 'self') { + tipContainer = element; + } else if (angular.isElement(options.container)) { + tipContainer = options.container; + } else if (options.container) { + tipContainer = findElement(options.container); + } + + // Options: trigger + bindTriggerEvents(); + + // Options: target + if (options.target) { + options.target = angular.isElement(options.target) ? options.target : findElement(options.target); + } + + // Options: show + if (options.show) { + scope.$$postDigest(function () { + options.trigger === 'focus' ? element[0].focus() : $tooltip.show(); + }); + } + + }; + + $tooltip.destroy = function () { + + // Unbind events + unbindTriggerEvents(); + + // Remove element + destroyTipElement(); + + // Destroy scope + scope.$destroy(); + + }; + + $tooltip.enter = function () { + + clearTimeout(timeout); + hoverState = 'in'; + if (!options.delay || !options.delay.show) { + return $tooltip.show(); + } + + timeout = setTimeout(function () { + if (hoverState === 'in') $tooltip.show(); + }, options.delay.show); + + }; + + $tooltip.show = function () { + if (!options.bsEnabled || $tooltip.$isShown) return; + + scope.$emit(options.prefixEvent + '.show.before', $tooltip); + var parent, after; + if (options.container) { + parent = tipContainer; + if (tipContainer[0].lastChild) { + after = angular.element(tipContainer[0].lastChild); + } else { + after = null; + } + } else { + parent = null; + after = element; + } + + + // Hide any existing tipElement + if (tipElement) destroyTipElement(); + // Fetch a cloned element linked from template + tipScope = $tooltip.$scope.$new(); + tipElement = $tooltip.$element = tipLinker(tipScope, function (clonedElement, scope) { + }); + + // Set the initial positioning. Make the tooltip invisible + // so IE doesn't try to focus on it off screen. + tipElement.css({top: '-9999px', left: '-9999px', display: 'block', visibility: 'hidden'}); + + // Options: animation + if (options.animation) tipElement.addClass(options.animation); + // Options: type + if (options.type) tipElement.addClass(options.prefixClass + '-' + options.type); + // Options: custom classes + if (options.customClass) tipElement.addClass(options.customClass); + + // Support v1.3+ $animate + // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 + var promise = $animate.enter(tipElement, parent, after, enterAnimateCallback); + if (promise && promise.then) promise.then(enterAnimateCallback); + + $tooltip.$isShown = scope.$isShown = true; + safeDigest(scope); + $$rAF(function () { + $tooltip.$applyPlacement(); + + // Once placed, make the tooltip visible + if (tipElement) tipElement.css({visibility: 'visible'}); + }); // var a = bodyEl.offsetWidth + 1; ? + + // Bind events + if (options.keyboard) { + if (options.trigger !== 'focus') { + $tooltip.focus(); + } + bindKeyboardEvents(); + } + + if (options.autoClose) { + bindAutoCloseEvents(); + } + + }; + + function enterAnimateCallback() { + scope.$emit(options.prefixEvent + '.show', $tooltip); + } + + $tooltip.leave = function () { + + clearTimeout(timeout); + hoverState = 'out'; + if (!options.delay || !options.delay.hide) { + return $tooltip.hide(); + } + timeout = setTimeout(function () { + if (hoverState === 'out') { + $tooltip.hide(); + } + }, options.delay.hide); + + }; + + var _blur; + var _tipToHide; + $tooltip.hide = function (blur) { + + if (!$tooltip.$isShown) return; + scope.$emit(options.prefixEvent + '.hide.before', $tooltip); + + // store blur value for leaveAnimateCallback to use + _blur = blur; + + // store current tipElement reference to use + // in leaveAnimateCallback + _tipToHide = tipElement; + + // Support v1.3+ $animate + // https://github.com/angular/angular.js/commit/bf0f5502b1bbfddc5cdd2f138efd9188b8c652a9 + var promise = $animate.leave(tipElement, leaveAnimateCallback); + if (promise && promise.then) promise.then(leaveAnimateCallback); + + $tooltip.$isShown = scope.$isShown = false; + safeDigest(scope); + + // Unbind events + if (options.keyboard && tipElement !== null) { + unbindKeyboardEvents(); + } + + if (options.autoClose && tipElement !== null) { + unbindAutoCloseEvents(); + } + }; + + function leaveAnimateCallback() { + scope.$emit(options.prefixEvent + '.hide', $tooltip); + + // check if current tipElement still references + // the same element when hide was called + if (tipElement === _tipToHide) { + // Allow to blur the input when hidden, like when pressing enter key + if (_blur && options.trigger === 'focus') { + return element[0].blur(); + } + + // clean up child scopes + destroyTipElement(); + } + } + + $tooltip.toggle = function () { + $tooltip.$isShown ? $tooltip.leave() : $tooltip.enter(); + }; + + $tooltip.focus = function () { + tipElement[0].focus(); + }; + + $tooltip.setEnabled = function (isEnabled) { + options.bsEnabled = isEnabled; + }; + + // Protected methods + + $tooltip.$applyPlacement = function () { + if (!tipElement) return; + + // Determine if we're doing an auto or normal placement + var placement = options.placement, + autoToken = /\s?auto?\s?/i, + autoPlace = autoToken.test(placement); + + if (autoPlace) { + placement = placement.replace(autoToken, '') || defaults.placement; + } + + // Need to add the position class before we get + // the offsets + tipElement.addClass(options.placement); + + // Get the position of the target element + // and the height and width of the tooltip so we can center it. + var elementPosition = getPosition(), + tipWidth = tipElement.prop('offsetWidth'), + tipHeight = tipElement.prop('offsetHeight'); + + // If we're auto placing, we need to check the positioning + if (autoPlace) { + var originalPlacement = placement; + var container = options.container ? angular.element(document.querySelector(options.container)) : element.parent(); + var containerPosition = getPosition(container); + + // Determine if the vertical placement + if (originalPlacement.indexOf('bottom') >= 0 && elementPosition.bottom + tipHeight > containerPosition.bottom) { + placement = originalPlacement.replace('bottom', 'top'); + } else if (originalPlacement.indexOf('top') >= 0 && elementPosition.top - tipHeight < containerPosition.top) { + placement = originalPlacement.replace('top', 'bottom'); + } + + // Determine the horizontal placement + // The exotic placements of left and right are opposite of the standard placements. Their arrows are put on the left/right + // and flow in the opposite direction of their placement. + if ((originalPlacement === 'right' || originalPlacement === 'bottom-left' || originalPlacement === 'top-left') && + elementPosition.right + tipWidth > containerPosition.width) { + + placement = originalPlacement === 'right' ? 'left' : placement.replace('left', 'right'); + } else if ((originalPlacement === 'left' || originalPlacement === 'bottom-right' || originalPlacement === 'top-right') && + elementPosition.left - tipWidth < containerPosition.left) { + + placement = originalPlacement === 'left' ? 'right' : placement.replace('right', 'left'); + } + + tipElement.removeClass(originalPlacement).addClass(placement); + } + + // Get the tooltip's top and left coordinates to center it with this directive. + var tipPosition = getCalculatedOffset(placement, elementPosition, tipWidth, tipHeight); + applyPlacementCss(tipPosition.top, tipPosition.left); + }; + + $tooltip.$onKeyUp = function (evt) { + if (evt.which === 27 && $tooltip.$isShown) { + $tooltip.hide(); + evt.stopPropagation(); + } + }; + + $tooltip.$onFocusKeyUp = function (evt) { + if (evt.which === 27) { + element[0].blur(); + evt.stopPropagation(); + } + }; + + $tooltip.$onFocusElementMouseDown = function (evt) { + evt.preventDefault(); + evt.stopPropagation(); + // Some browsers do not auto-focus buttons (eg. Safari) + $tooltip.$isShown ? element[0].blur() : element[0].focus(); + }; + + // bind/unbind events + function bindTriggerEvents() { + var triggers = options.trigger.split(' '); + angular.forEach(triggers, function (trigger) { + if (trigger === 'click') { + element.on('click', $tooltip.toggle); + } else if (trigger !== 'manual') { + element.on(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); + element.on(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); + nodeName === 'button' && trigger !== 'hover' && element.on(isTouch ? 'touchstart' : 'mousedown', $tooltip.$onFocusElementMouseDown); + } + }); + } + + function unbindTriggerEvents() { + var triggers = options.trigger.split(' '); + for (var i = triggers.length; i--;) { + var trigger = triggers[i]; + if (trigger === 'click') { + element.off('click', $tooltip.toggle); + } else if (trigger !== 'manual') { + element.off(trigger === 'hover' ? 'mouseenter' : 'focus', $tooltip.enter); + element.off(trigger === 'hover' ? 'mouseleave' : 'blur', $tooltip.leave); + nodeName === 'button' && trigger !== 'hover' && element.off(isTouch ? 'touchstart' : 'mousedown', $tooltip.$onFocusElementMouseDown); + } + } + } + + function bindKeyboardEvents() { + if (options.trigger !== 'focus') { + tipElement.on('keyup', $tooltip.$onKeyUp); + } else { + element.on('keyup', $tooltip.$onFocusKeyUp); + } + } + + function unbindKeyboardEvents() { + if (options.trigger !== 'focus') { + tipElement.off('keyup', $tooltip.$onKeyUp); + } else { + element.off('keyup', $tooltip.$onFocusKeyUp); + } + } + + var _autoCloseEventsBinded = false; + + function bindAutoCloseEvents() { + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + // Stop propagation when clicking inside tooltip + tipElement.on('click', stopEventPropagation); + + // Hide when clicking outside tooltip + $body.on('click', $tooltip.hide); + + _autoCloseEventsBinded = true; + }, 0, false); + } + + function unbindAutoCloseEvents() { + if (_autoCloseEventsBinded) { + tipElement.off('click', stopEventPropagation); + $body.off('click', $tooltip.hide); + _autoCloseEventsBinded = false; + } + } + + function stopEventPropagation(event) { + event.stopPropagation(); + } + + // Private methods + + function getPosition($element) { + $element = $element || (options.target || element); + + var el = $element[0]; + + var elRect = el.getBoundingClientRect(); + if (elRect.width === null) { + // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 + elRect = angular.extend({}, elRect, {width: elRect.right - elRect.left, height: elRect.bottom - elRect.top}); + } + + var elPos; + if (options.container === 'body') { + elPos = dimensions.offset(el); + } else { + elPos = dimensions.position(el); + } + + return angular.extend({}, elRect, elPos); + } + + function getCalculatedOffset(placement, position, actualWidth, actualHeight) { + var offset; + var split = placement.split('-'); + + switch (split[0]) { + case 'right': + offset = { + top: position.top + position.height / 2 - actualHeight / 2, + left: position.left + position.width + }; + break; + case 'bottom': + offset = { + top: position.top + position.height, + left: position.left + position.width / 2 - actualWidth / 2 + }; + break; + case 'left': + offset = { + top: position.top + position.height / 2 - actualHeight / 2, + left: position.left - actualWidth + }; + break; + default: + offset = { + top: position.top - actualHeight, + left: position.left + position.width / 2 - actualWidth / 2 + }; + break; + } + + if (!split[1]) { + return offset; + } + + // Add support for corners @todo css + if (split[0] === 'top' || split[0] === 'bottom') { + switch (split[1]) { + case 'left': + offset.left = position.left; + break; + case 'right': + offset.left = position.left + position.width - actualWidth; + } + } else if (split[0] === 'left' || split[0] === 'right') { + switch (split[1]) { + case 'top': + offset.top = position.top - actualHeight; + break; + case 'bottom': + offset.top = position.top + position.height; + } + } + + return offset; + } + + function applyPlacementCss(top, left) { + tipElement.css({top: top + 'px', left: left + 'px'}); + } + + function destroyTipElement() { + // Cancel pending callbacks + clearTimeout(timeout); + + if ($tooltip.$isShown && tipElement !== null) { + if (options.autoClose) { + unbindAutoCloseEvents(); + } + + if (options.keyboard) { + unbindKeyboardEvents(); + } + } + + if (tipScope) { + tipScope.$destroy(); + tipScope = null; + } + + if (tipElement) { + tipElement.remove(); + tipElement = $tooltip.$element = null; + } + } + + return $tooltip; - return { - restrict: 'EAC', - scope: true, - link: function postLink(scope, element, attr, transclusion) { + } - // Directive options - var options = {scope: scope}; - angular.forEach(['template', 'contentTemplate', 'placement', 'container', 'target', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'backdropAnimation', 'type', 'customClass', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + // Helper functions - // overwrite inherited title value when no value specified - // fix for angular 1.3.1 531a8de72c439d8ddd064874bf364c00cedabb11 - if (!scope.hasOwnProperty('title')){ - scope.title = ''; - } - - // Observe scope attributes for change - attr.$observe('title', function(newValue) { - if (angular.isDefined(newValue) || !scope.hasOwnProperty('title')) { - var oldValue = scope.title; - scope.title = $sce.trustAsHtml(newValue); - angular.isDefined(oldValue) && $$rAF(function() { - tooltip && tooltip.$applyPlacement(); - }); - } - }); + function safeDigest(scope) { + scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest(); + } - // Support scope as an object - attr.bsTooltip && scope.$watch(attr.bsTooltip, function(newValue, oldValue) { - if(angular.isObject(newValue)) { - angular.extend(scope, newValue); - } else { - scope.title = newValue; - } - angular.isDefined(oldValue) && $$rAF(function() { - tooltip && tooltip.$applyPlacement(); - }); - }, true); - - // Visibility binding support - attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) { - if(!tooltip || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(tooltip),?/i); - newValue === true ? tooltip.show() : tooltip.hide(); - }); + function findElement(query, element) { + return angular.element((element || document).querySelectorAll(query)); + } - // Enabled binding support - attr.bsEnabled && scope.$watch(attr.bsEnabled, function(newValue, oldValue) { - // console.warn('scope.$watch(%s)', attr.bsEnabled, newValue, oldValue); - if(!tooltip || !angular.isDefined(newValue)) return; - if(angular.isString(newValue)) newValue = !!newValue.match(/true|1|,?(tooltip),?/i); - newValue === false ? tooltip.setEnabled(false) : tooltip.setEnabled(true); - }); + var fetchPromises = {}; + + function fetchTemplate(template) { + if (fetchPromises[template]) return fetchPromises[template]; + return (fetchPromises[template] = $q.when($templateCache.get(template) || $http.get(template)) + .then(function (res) { + if (angular.isObject(res)) { + $templateCache.put(template, res.data); + return res.data; + } + return res; + })); + } - // Initialize popover - var tooltip = $tooltip(element, options); + return TooltipFactory; + + }]; + + }) + + .directive('bsTooltip', ["$window", "$location", "$sce", "$tooltip", "$$rAF", function ($window, $location, $sce, $tooltip, $$rAF) { + + return { + restrict: 'EAC', + scope: true, + link: function postLink(scope, element, attr, transclusion) { + + // Directive options + var options = {scope: scope}; + angular.forEach(['template', 'contentTemplate', 'placement', 'container', 'target', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'backdropAnimation', 'type', 'customClass', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // overwrite inherited title value when no value specified + // fix for angular 1.3.1 531a8de72c439d8ddd064874bf364c00cedabb11 + if (!scope.hasOwnProperty('title')) { + scope.title = ''; + } + + // Observe scope attributes for change + attr.$observe('title', function (newValue) { + if (angular.isDefined(newValue) || !scope.hasOwnProperty('title')) { + var oldValue = scope.title; + scope.title = $sce.trustAsHtml(newValue); + angular.isDefined(oldValue) && $$rAF(function () { + tooltip && tooltip.$applyPlacement(); + }); + } + }); + + // Support scope as an object + attr.bsTooltip && scope.$watch(attr.bsTooltip, function (newValue, oldValue) { + if (angular.isObject(newValue)) { + angular.extend(scope, newValue); + } else { + scope.title = newValue; + } + angular.isDefined(oldValue) && $$rAF(function () { + tooltip && tooltip.$applyPlacement(); + }); + }, true); + + // Visibility binding support + attr.bsShow && scope.$watch(attr.bsShow, function (newValue, oldValue) { + if (!tooltip || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(tooltip),?/i); + newValue === true ? tooltip.show() : tooltip.hide(); + }); + + // Enabled binding support + attr.bsEnabled && scope.$watch(attr.bsEnabled, function (newValue, oldValue) { + // console.warn('scope.$watch(%s)', attr.bsEnabled, newValue, oldValue); + if (!tooltip || !angular.isDefined(newValue)) return; + if (angular.isString(newValue)) newValue = !!newValue.match(/true|1|,?(tooltip),?/i); + newValue === false ? tooltip.setEnabled(false) : tooltip.setEnabled(true); + }); + + // Initialize popover + var tooltip = $tooltip(element, options); + + // Garbage collection + scope.$on('$destroy', function () { + if (tooltip) tooltip.destroy(); + options = null; + tooltip = null; + }); - // Garbage collection - scope.$on('$destroy', function() { - if(tooltip) tooltip.destroy(); - options = null; - tooltip = null; - }); - - } - }; + } + }; - }]); + }]); // Source: typeahead.js -angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) - - .provider('$typeahead', function() { - - var defaults = this.defaults = { - animation: 'am-fade', - prefixClass: 'typeahead', - prefixEvent: '$typeahead', - placement: 'bottom-left', - template: 'typeahead/typeahead.tpl.html', - trigger: 'focus', - container: false, - keyboard: true, - html: false, - delay: 0, - minLength: 1, - filter: 'filter', - limit: 6, - comparator: '' - }; - - this.$get = ["$window", "$rootScope", "$tooltip", "$timeout", function($window, $rootScope, $tooltip, $timeout) { - - var bodyEl = angular.element($window.document.body); - - function TypeaheadFactory(element, controller, config) { - - var $typeahead = {}; - - // Common vars - var options = angular.extend({}, defaults, config); - - $typeahead = $tooltip(element, options); - var parentScope = config.scope; - var scope = $typeahead.$scope; - - scope.$resetMatches = function(){ - scope.$matches = []; - scope.$activeIndex = 0; - }; - scope.$resetMatches(); - - scope.$activate = function(index) { - scope.$$postDigest(function() { - $typeahead.activate(index); - }); - }; - - scope.$select = function(index, evt) { - scope.$$postDigest(function() { - $typeahead.select(index); - }); - }; - - scope.$isVisible = function() { - return $typeahead.$isVisible(); - }; - - // Public methods - - $typeahead.update = function(matches) { - scope.$matches = matches; - if(scope.$activeIndex >= matches.length) { - scope.$activeIndex = 0; - } - }; - - $typeahead.activate = function(index) { - scope.$activeIndex = index; - }; - - $typeahead.select = function(index) { - var value = scope.$matches[index].value; - // console.log('$setViewValue', value); - controller.$setViewValue(value); - controller.$render(); - scope.$resetMatches(); - if(parentScope) parentScope.$digest(); - // Emit event - scope.$emit(options.prefixEvent + '.select', value, index, $typeahead); - }; - - // Protected methods - - $typeahead.$isVisible = function() { - if(!options.minLength || !controller) { - return !!scope.$matches.length; - } - // minLength support - return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; - }; - - $typeahead.$getIndex = function(value) { - var l = scope.$matches.length, i = l; - if(!l) return; - for(i = l; i--;) { - if(scope.$matches[i].value === value) break; - } - if(i < 0) return; - return i; - }; - - $typeahead.$onMouseDown = function(evt) { - // Prevent blur on mousedown - evt.preventDefault(); - evt.stopPropagation(); - }; - - $typeahead.$onKeyDown = function(evt) { - if(!/(38|40|13)/.test(evt.keyCode)) return; - - // Let ngSubmit pass if the typeahead tip is hidden - if($typeahead.$isVisible()) { - evt.preventDefault(); - evt.stopPropagation(); - } - - // Select with enter - if(evt.keyCode === 13 && scope.$matches.length) { - $typeahead.select(scope.$activeIndex); - } - - // Navigate with keyboard - else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; - else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; - else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; - scope.$digest(); - }; - - // Overrides - - var show = $typeahead.show; - $typeahead.show = function() { - show(); - // use timeout to hookup the events to prevent - // event bubbling from being processed imediately. - $timeout(function() { - $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); - if(options.keyboard) { - element.on('keydown', $typeahead.$onKeyDown); - } - }, 0, false); - }; - - var hide = $typeahead.hide; - $typeahead.hide = function() { - $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); - if(options.keyboard) { - element.off('keydown', $typeahead.$onKeyDown); - } - hide(); - }; - - return $typeahead; - - } - - TypeaheadFactory.defaults = defaults; - return TypeaheadFactory; - - }]; - - }) - - .directive('bsTypeahead', ["$window", "$parse", "$q", "$typeahead", "$parseOptions", function($window, $parse, $q, $typeahead, $parseOptions) { - - var defaults = $typeahead.defaults; - - return { - restrict: 'EAC', - require: 'ngModel', - link: function postLink(scope, element, attr, controller) { - - // Directive options - var options = {scope: scope}; - angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode', 'comparator', 'id'], function(key) { - if(angular.isDefined(attr[key])) options[key] = attr[key]; - }); + angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) + + .provider('$typeahead', function () { + + var defaults = this.defaults = { + animation: 'am-fade', + prefixClass: 'typeahead', + prefixEvent: '$typeahead', + placement: 'bottom-left', + template: 'typeahead/typeahead.tpl.html', + trigger: 'focus', + container: false, + keyboard: true, + html: false, + delay: 0, + minLength: 1, + filter: 'filter', + limit: 6, + comparator: '' + }; - // Build proper ngOptions - var filter = options.filter || defaults.filter; - var limit = options.limit || defaults.limit; - var comparator = options.comparator || defaults.comparator; - - var ngOptions = attr.ngOptions; - if(filter) ngOptions += ' | ' + filter + ':$viewValue'; - if (comparator) ngOptions += ':' + comparator; - if(limit) ngOptions += ' | limitTo:' + limit; - var parsedOptions = $parseOptions(ngOptions); - - // Initialize typeahead - var typeahead = $typeahead(element, controller, options); - - // Watch options on demand - if(options.watchOptions) { - // Watch ngOptions values before filtering for changes, drop function calls - var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); - scope.$watch(watchedOptions, function (newValue, oldValue) { - // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); - parsedOptions.valuesFn(scope, controller).then(function (values) { - typeahead.update(values); - controller.$render(); - }); - }, true); - } - - // Watch model for changes - scope.$watch(attr.ngModel, function(newValue, oldValue) { - // console.warn('$watch', element.attr('ng-model'), newValue); - scope.$modelValue = newValue; // Publish modelValue on scope for custom templates - parsedOptions.valuesFn(scope, controller) - .then(function(values) { - // Prevent input with no future prospect if selectMode is truthy - // @TODO test selectMode - if(options.selectMode && !values.length && newValue.length > 0) { - controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); - return; - } - if(values.length > limit) values = values.slice(0, limit); - var isVisible = typeahead.$isVisible(); - isVisible && typeahead.update(values); - // Do not re-queue an update if a correct value has been selected - if(values.length === 1 && values[0].value === newValue) return; - !isVisible && typeahead.update(values); - // Queue a new rendering that will leverage collection loading - controller.$render(); - }); - }); + this.$get = ["$window", "$rootScope", "$tooltip", "$timeout", function ($window, $rootScope, $tooltip, $timeout) { + + var bodyEl = angular.element($window.document.body); + + function TypeaheadFactory(element, controller, config) { + + var $typeahead = {}; + + // Common vars + var options = angular.extend({}, defaults, config); + + $typeahead = $tooltip(element, options); + var parentScope = config.scope; + var scope = $typeahead.$scope; + + scope.$resetMatches = function () { + scope.$matches = []; + scope.$activeIndex = 0; + }; + scope.$resetMatches(); + + scope.$activate = function (index) { + scope.$$postDigest(function () { + $typeahead.activate(index); + }); + }; + + scope.$select = function (index, evt) { + scope.$$postDigest(function () { + $typeahead.select(index); + }); + }; + + scope.$isVisible = function () { + return $typeahead.$isVisible(); + }; + + // Public methods + + $typeahead.update = function (matches) { + scope.$matches = matches; + if (scope.$activeIndex >= matches.length) { + scope.$activeIndex = 0; + } + }; + + $typeahead.activate = function (index) { + scope.$activeIndex = index; + }; + + $typeahead.select = function (index) { + var value = scope.$matches[index].value; + // console.log('$setViewValue', value); + controller.$setViewValue(value); + controller.$render(); + scope.$resetMatches(); + if (parentScope) parentScope.$digest(); + // Emit event + scope.$emit(options.prefixEvent + '.select', value, index, $typeahead); + }; + + // Protected methods + + $typeahead.$isVisible = function () { + if (!options.minLength || !controller) { + return !!scope.$matches.length; + } + // minLength support + return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; + }; + + $typeahead.$getIndex = function (value) { + var l = scope.$matches.length, i = l; + if (!l) return; + for (i = l; i--;) { + if (scope.$matches[i].value === value) break; + } + if (i < 0) return; + return i; + }; + + $typeahead.$onMouseDown = function (evt) { + // Prevent blur on mousedown + evt.preventDefault(); + evt.stopPropagation(); + }; + + $typeahead.$onKeyDown = function (evt) { + if (!/(38|40|13)/.test(evt.keyCode)) return; + + // Let ngSubmit pass if the typeahead tip is hidden + if ($typeahead.$isVisible()) { + evt.preventDefault(); + evt.stopPropagation(); + } + + // Select with enter + if (evt.keyCode === 13 && scope.$matches.length) { + $typeahead.select(scope.$activeIndex); + } + + // Navigate with keyboard + else if (evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; + else if (evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; + else if (angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; + scope.$digest(); + }; + + // Overrides + + var show = $typeahead.show; + $typeahead.show = function () { + show(); + // use timeout to hookup the events to prevent + // event bubbling from being processed imediately. + $timeout(function () { + $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); + if (options.keyboard) { + element.on('keydown', $typeahead.$onKeyDown); + } + }, 0, false); + }; + + var hide = $typeahead.hide; + $typeahead.hide = function () { + $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); + if (options.keyboard) { + element.off('keydown', $typeahead.$onKeyDown); + } + hide(); + }; + + return $typeahead; - // modelValue -> $formatters -> viewValue - controller.$formatters.push(function(modelValue) { - // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); - var displayValue = parsedOptions.displayValue(modelValue); - return displayValue === undefined ? '' : displayValue; - }); + } - // Model rendering in view - controller.$render = function () { - // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); - if(controller.$isEmpty(controller.$viewValue)) return element.val(''); - var index = typeahead.$getIndex(controller.$modelValue); - var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; - selected = angular.isObject(selected) ? parsedOptions.displayValue(selected) : selected; - element.val(selected ? selected.toString().replace(/<(?:.|\n)*?>/gm, '').trim() : ''); - }; - - // Garbage collection - scope.$on('$destroy', function() { - if (typeahead) typeahead.destroy(); - options = null; - typeahead = null; - }); + TypeaheadFactory.defaults = defaults; + return TypeaheadFactory; + + }]; + + }) + + .directive('bsTypeahead', ["$window", "$parse", "$q", "$typeahead", "$parseOptions", function ($window, $parse, $q, $typeahead, $parseOptions) { + + var defaults = $typeahead.defaults; + + return { + restrict: 'EAC', + require: 'ngModel', + link: function postLink(scope, element, attr, controller) { + + // Directive options + var options = {scope: scope}; + angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode', 'comparator', 'id'], function (key) { + if (angular.isDefined(attr[key])) options[key] = attr[key]; + }); + + // Build proper ngOptions + var filter = options.filter || defaults.filter; + var limit = options.limit || defaults.limit; + var comparator = options.comparator || defaults.comparator; + + var ngOptions = attr.ngOptions; + if (filter) ngOptions += ' | ' + filter + ':$viewValue'; + if (comparator) ngOptions += ':' + comparator; + if (limit) ngOptions += ' | limitTo:' + limit; + var parsedOptions = $parseOptions(ngOptions); + + // Initialize typeahead + var typeahead = $typeahead(element, controller, options); + + // Watch options on demand + if (options.watchOptions) { + // Watch ngOptions values before filtering for changes, drop function calls + var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); + scope.$watch(watchedOptions, function (newValue, oldValue) { + // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); + parsedOptions.valuesFn(scope, controller).then(function (values) { + typeahead.update(values); + controller.$render(); + }); + }, true); + } + + // Watch model for changes + scope.$watch(attr.ngModel, function (newValue, oldValue) { + // console.warn('$watch', element.attr('ng-model'), newValue); + scope.$modelValue = newValue; // Publish modelValue on scope for custom templates + parsedOptions.valuesFn(scope, controller) + .then(function (values) { + // Prevent input with no future prospect if selectMode is truthy + // @TODO test selectMode + if (options.selectMode && !values.length && newValue.length > 0) { + controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); + return; + } + if (values.length > limit) values = values.slice(0, limit); + var isVisible = typeahead.$isVisible(); + isVisible && typeahead.update(values); + // Do not re-queue an update if a correct value has been selected + if (values.length === 1 && values[0].value === newValue) return; + !isVisible && typeahead.update(values); + // Queue a new rendering that will leverage collection loading + controller.$render(); + }); + }); + + // modelValue -> $formatters -> viewValue + controller.$formatters.push(function (modelValue) { + // console.warn('$formatter("%s"): modelValue=%o (%o)', element.attr('ng-model'), modelValue, typeof modelValue); + var displayValue = parsedOptions.displayValue(modelValue); + return displayValue === undefined ? '' : displayValue; + }); + + // Model rendering in view + controller.$render = function () { + // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); + if (controller.$isEmpty(controller.$viewValue)) return element.val(''); + var index = typeahead.$getIndex(controller.$modelValue); + var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; + selected = angular.isObject(selected) ? parsedOptions.displayValue(selected) : selected; + element.val(selected ? selected.toString().replace(/<(?:.|\n)*?>/gm, '').trim() : ''); + }; + + // Garbage collection + scope.$on('$destroy', function () { + if (typeahead) typeahead.destroy(); + options = null; + typeahead = null; + }); - } - }; + } + }; - }]); + }]); })(window, document); diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.tpl.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.tpl.js index a8f9a149..363d691d 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.tpl.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-strap.tpl.js @@ -5,85 +5,85 @@ * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ -(function(window, document, undefined) { -'use strict'; +(function (window, document, undefined) { + 'use strict'; // Source: alert.tpl.js -angular.module('mgcrea.ngStrap.alert').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.alert').run(['$templateCache', function ($templateCache) { - $templateCache.put('alert/alert.tpl.html', '
           
          '); + $templateCache.put('alert/alert.tpl.html', '
           
          '); -}]); + }]); // Source: aside.tpl.js -angular.module('mgcrea.ngStrap.aside').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.aside').run(['$templateCache', function ($templateCache) { - $templateCache.put('aside/aside.tpl.html', ''); + $templateCache.put('aside/aside.tpl.html', ''); -}]); + }]); // Source: dropdown.tpl.js -angular.module('mgcrea.ngStrap.dropdown').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.dropdown').run(['$templateCache', function ($templateCache) { - $templateCache.put('dropdown/dropdown.tpl.html', ''); + $templateCache.put('dropdown/dropdown.tpl.html', ''); -}]); + }]); // Source: datepicker.tpl.js -angular.module('mgcrea.ngStrap.datepicker').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.datepicker').run(['$templateCache', function ($templateCache) { - $templateCache.put('datepicker/datepicker.tpl.html', ''); + $templateCache.put('datepicker/datepicker.tpl.html', ''); -}]); + }]); // Source: modal.tpl.js -angular.module('mgcrea.ngStrap.modal').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.modal').run(['$templateCache', function ($templateCache) { - $templateCache.put('modal/modal.tpl.html', ''); + $templateCache.put('modal/modal.tpl.html', ''); -}]); + }]); // Source: popover.tpl.js -angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function ($templateCache) { - $templateCache.put('popover/popover.tpl.html', '

          '); + $templateCache.put('popover/popover.tpl.html', '

          '); -}]); + }]); // Source: select.tpl.js -angular.module('mgcrea.ngStrap.select').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.select').run(['$templateCache', function ($templateCache) { - $templateCache.put('select/select.tpl.html', ''); + $templateCache.put('select/select.tpl.html', ''); -}]); + }]); // Source: tab.tpl.js -angular.module('mgcrea.ngStrap.tab').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.tab').run(['$templateCache', function ($templateCache) { - $templateCache.put('tab/tab.tpl.html', '
          '); + $templateCache.put('tab/tab.tpl.html', '
          '); -}]); + }]); // Source: timepicker.tpl.js -angular.module('mgcrea.ngStrap.timepicker').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.timepicker').run(['$templateCache', function ($templateCache) { - $templateCache.put('timepicker/timepicker.tpl.html', ''); + $templateCache.put('timepicker/timepicker.tpl.html', ''); -}]); + }]); // Source: tooltip.tpl.js -angular.module('mgcrea.ngStrap.tooltip').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.tooltip').run(['$templateCache', function ($templateCache) { - $templateCache.put('tooltip/tooltip.tpl.html', '
          '); + $templateCache.put('tooltip/tooltip.tpl.html', '
          '); -}]); + }]); // Source: typeahead.tpl.js -angular.module('mgcrea.ngStrap.typeahead').run(['$templateCache', function($templateCache) { + angular.module('mgcrea.ngStrap.typeahead').run(['$templateCache', function ($templateCache) { - $templateCache.put('typeahead/typeahead.tpl.html', ''); + $templateCache.put('typeahead/typeahead.tpl.html', ''); -}]); + }]); })(window, document); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate-storage-cookie.min.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate-storage-cookie.min.js index b2f446cc..54b12937 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate-storage-cookie.min.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate-storage-cookie.min.js @@ -3,4 +3,15 @@ * http://github.com/angular-translate/angular-translate * Copyright (c) 2014 ; Licensed MIT */ -angular.module("pascalprecht.translate").factory("$translateCookieStorage",["$cookieStore",function(a){var b={get:function(b){return a.get(b)},set:function(b,c){a.put(b,c)},put:function(b,c){a.put(b,c)}};return b}]); \ No newline at end of file +angular.module("pascalprecht.translate").factory("$translateCookieStorage", ["$cookieStore", function (a) { + var b = { + get: function (b) { + return a.get(b) + }, set: function (b, c) { + a.put(b, c) + }, put: function (b, c) { + a.put(b, c) + } + }; + return b +}]); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate.js index ae080918..cad36357 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-translate.js @@ -12,32 +12,32 @@ */ angular.module('pascalprecht.translate', ['ng']) -.run(['$translate', function ($translate) { - - var key = $translate.storageKey(), - storage = $translate.storage(); - - var fallbackFromIncorrectStorageValue = function() { - var preferred = $translate.preferredLanguage(); - if (angular.isString(preferred)) { - $translate.use(preferred); - // $translate.use() will also remember the language. - // So, we don't need to call storage.put() here. - } else { - storage.put(key, $translate.use()); - } - }; - - if (storage) { - if (!storage.get(key)) { - fallbackFromIncorrectStorageValue(); - } else { - $translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue); - } - } else if (angular.isString($translate.preferredLanguage())) { - $translate.use($translate.preferredLanguage()); - } -}]); + .run(['$translate', function ($translate) { + + var key = $translate.storageKey(), + storage = $translate.storage(); + + var fallbackFromIncorrectStorageValue = function () { + var preferred = $translate.preferredLanguage(); + if (angular.isString(preferred)) { + $translate.use(preferred); + // $translate.use() will also remember the language. + // So, we don't need to call storage.put() here. + } else { + storage.put(key, $translate.use()); + } + }; + + if (storage) { + if (!storage.get(key)) { + fallbackFromIncorrectStorageValue(); + } else { + $translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue); + } + } else if (angular.isString($translate.preferredLanguage())) { + $translate.use($translate.preferredLanguage()); + } + }]); /** * @ngdoc object @@ -50,1753 +50,1753 @@ angular.module('pascalprecht.translate', ['ng']) */ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', function ($STORAGE_KEY) { - var $translationTable = {}, - $preferredLanguage, - $availableLanguageKeys = [], - $languageKeyAliases, - $fallbackLanguage, - $fallbackWasString, - $uses, - $nextLang, - $storageFactory, - $storageKey = $STORAGE_KEY, - $storagePrefix, - $missingTranslationHandlerFactory, - $interpolationFactory, - $interpolatorFactories = [], - $interpolationSanitizationStrategy = false, - $loaderFactory, - $cloakClassName = 'translate-cloak', - $loaderOptions, - $notFoundIndicatorLeft, - $notFoundIndicatorRight, - $postCompilingEnabled = false, - NESTED_OBJECT_DELIMITER = '.', - loaderCache; - - var version = '2.5.2'; - - // tries to determine the browsers language - var getFirstBrowserLanguage = function () { - var nav = window.navigator, - browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'], - i, - language; - - // support for HTML 5.1 "navigator.languages" - if (angular.isArray(nav.languages)) { - for (i = 0; i < nav.languages.length; i++) { - language = nav.languages[i]; - if (language && language.length) { - return language; + var $translationTable = {}, + $preferredLanguage, + $availableLanguageKeys = [], + $languageKeyAliases, + $fallbackLanguage, + $fallbackWasString, + $uses, + $nextLang, + $storageFactory, + $storageKey = $STORAGE_KEY, + $storagePrefix, + $missingTranslationHandlerFactory, + $interpolationFactory, + $interpolatorFactories = [], + $interpolationSanitizationStrategy = false, + $loaderFactory, + $cloakClassName = 'translate-cloak', + $loaderOptions, + $notFoundIndicatorLeft, + $notFoundIndicatorRight, + $postCompilingEnabled = false, + NESTED_OBJECT_DELIMITER = '.', + loaderCache; + + var version = '2.5.2'; + + // tries to determine the browsers language + var getFirstBrowserLanguage = function () { + var nav = window.navigator, + browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'], + i, + language; + + // support for HTML 5.1 "navigator.languages" + if (angular.isArray(nav.languages)) { + for (i = 0; i < nav.languages.length; i++) { + language = nav.languages[i]; + if (language && language.length) { + return language; + } + } + } + + // support for other well known properties in browsers + for (i = 0; i < browserLanguagePropertyKeys.length; i++) { + language = nav[browserLanguagePropertyKeys[i]]; + if (language && language.length) { + return language; + } + } + + return null; + }; + getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage'; + + // tries to determine the browsers locale + var getLocale = function () { + return (getFirstBrowserLanguage() || '').split('-').join('_'); + }; + getLocale.displayName = 'angular-translate/service: getLocale'; + + /** + * @name indexOf + * @private + * + * @description + * indexOf polyfill. Kinda sorta. + * + * @param {array} array Array to search in. + * @param {string} searchElement Element to search for. + * + * @returns {int} Index of search element. + */ + var indexOf = function (array, searchElement) { + for (var i = 0, len = array.length; i < len; i++) { + if (array[i] === searchElement) { + return i; + } } - } - } - - // support for other well known properties in browsers - for (i = 0; i < browserLanguagePropertyKeys.length; i++) { - language = nav[browserLanguagePropertyKeys[i]]; - if (language && language.length) { - return language; - } - } - - return null; - }; - getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage'; - - // tries to determine the browsers locale - var getLocale = function () { - return (getFirstBrowserLanguage() || '').split('-').join('_'); - }; - getLocale.displayName = 'angular-translate/service: getLocale'; - - /** - * @name indexOf - * @private - * - * @description - * indexOf polyfill. Kinda sorta. - * - * @param {array} array Array to search in. - * @param {string} searchElement Element to search for. - * - * @returns {int} Index of search element. - */ - var indexOf = function(array, searchElement) { - for (var i = 0, len = array.length; i < len; i++) { - if (array[i] === searchElement) { - return i; - } - } - return -1; - }; - - /** - * @name trim - * @private - * - * @description - * trim polyfill - * - * @returns {string} The string stripped of whitespace from both ends - */ - var trim = function() { - return this.replace(/^\s+|\s+$/g, ''); - }; - - var negotiateLocale = function (preferred) { - - var avail = [], - locale = angular.lowercase(preferred), - i = 0, - n = $availableLanguageKeys.length; - - for (; i < n; i++) { - avail.push(angular.lowercase($availableLanguageKeys[i])); - } - - if (indexOf(avail, locale) > -1) { - return preferred; - } - - if ($languageKeyAliases) { - var alias; - for (var langKeyAlias in $languageKeyAliases) { - var hasWildcardKey = false; - var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) && - angular.lowercase(langKeyAlias) === angular.lowercase(preferred); - - if (langKeyAlias.slice(-1) === '*') { - hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length-1); + return -1; + }; + + /** + * @name trim + * @private + * + * @description + * trim polyfill + * + * @returns {string} The string stripped of whitespace from both ends + */ + var trim = function () { + return this.replace(/^\s+|\s+$/g, ''); + }; + + var negotiateLocale = function (preferred) { + + var avail = [], + locale = angular.lowercase(preferred), + i = 0, + n = $availableLanguageKeys.length; + + for (; i < n; i++) { + avail.push(angular.lowercase($availableLanguageKeys[i])); } - if (hasExactKey || hasWildcardKey) { - alias = $languageKeyAliases[langKeyAlias]; - if (indexOf(avail, angular.lowercase(alias)) > -1) { - return alias; - } + + if (indexOf(avail, locale) > -1) { + return preferred; } - } - } - - var parts = preferred.split('_'); - - if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) { - return parts[0]; - } - - // If everything fails, just return the preferred, unchanged. - return preferred; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#translations - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Registers a new translation table for specific language key. - * - * To register a translation table for specific language, pass a defined language - * key as first parameter. - * - *
          -   *  // register translation table for language: 'de_DE'
          -   *  $translateProvider.translations('de_DE', {
          +
          +        if ($languageKeyAliases) {
          +            var alias;
          +            for (var langKeyAlias in $languageKeyAliases) {
          +                var hasWildcardKey = false;
          +                var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) &&
          +                    angular.lowercase(langKeyAlias) === angular.lowercase(preferred);
          +
          +                if (langKeyAlias.slice(-1) === '*') {
          +                    hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length - 1);
          +                }
          +                if (hasExactKey || hasWildcardKey) {
          +                    alias = $languageKeyAliases[langKeyAlias];
          +                    if (indexOf(avail, angular.lowercase(alias)) > -1) {
          +                        return alias;
          +                    }
          +                }
          +            }
          +        }
          +
          +        var parts = preferred.split('_');
          +
          +        if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) {
          +            return parts[0];
          +        }
          +
          +        // If everything fails, just return the preferred, unchanged.
          +        return preferred;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#translations
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Registers a new translation table for specific language key.
          +     *
          +     * To register a translation table for specific language, pass a defined language
          +     * key as first parameter.
          +     *
          +     * 
          +     *  // register translation table for language: 'de_DE'
          +     *  $translateProvider.translations('de_DE', {
              *    'GREETING': 'Hallo Welt!'
              *  });
          -   *
          -   *  // register another one
          -   *  $translateProvider.translations('en_US', {
          +     *
          +     *  // register another one
          +     *  $translateProvider.translations('en_US', {
              *    'GREETING': 'Hello world!'
              *  });
          -   * 
          - * - * When registering multiple translation tables for for the same language key, - * the actual translation table gets extended. This allows you to define module - * specific translation which only get added, once a specific module is loaded in - * your app. - * - * Invoking this method with no arguments returns the translation table which was - * registered with no language key. Invoking it with a language key returns the - * related translation table. - * - * @param {string} key A language key. - * @param {object} translationTable A plain old JavaScript object that represents a translation table. - * - */ - var translations = function (langKey, translationTable) { - - if (!langKey && !translationTable) { - return $translationTable; - } - - if (langKey && !translationTable) { - if (angular.isString(langKey)) { - return $translationTable[langKey]; - } - } else { - if (!angular.isObject($translationTable[langKey])) { - $translationTable[langKey] = {}; - } - angular.extend($translationTable[langKey], flatObject(translationTable)); - } - return this; - }; - - this.translations = translations; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#cloakClassName - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * - * Let's you change the class name for `translate-cloak` directive. - * Default class name is `translate-cloak`. - * - * @param {string} name translate-cloak class name - */ - this.cloakClassName = function (name) { - if (!name) { - return $cloakClassName; - } - $cloakClassName = name; - return this; - }; - - /** - * @name flatObject - * @private - * - * @description - * Flats an object. This function is used to flatten given translation data with - * namespaces, so they are later accessible via dot notation. - */ - var flatObject = function (data, path, result, prevKey) { - var key, keyWithPath, keyWithShortPath, val; - - if (!path) { - path = []; - } - if (!result) { - result = {}; - } - for (key in data) { - if (!Object.prototype.hasOwnProperty.call(data, key)) { - continue; - } - val = data[key]; - if (angular.isObject(val)) { - flatObject(val, path.concat(key), result, key); - } else { - keyWithPath = path.length ? ('' + path.join(NESTED_OBJECT_DELIMITER) + NESTED_OBJECT_DELIMITER + key) : key; - if(path.length && key === prevKey){ - // Create shortcut path (foo.bar == foo.bar.bar) - keyWithShortPath = '' + path.join(NESTED_OBJECT_DELIMITER); - // Link it to original path - result[keyWithShortPath] = '@:' + keyWithPath; + *
          + * + * When registering multiple translation tables for for the same language key, + * the actual translation table gets extended. This allows you to define module + * specific translation which only get added, once a specific module is loaded in + * your app. + * + * Invoking this method with no arguments returns the translation table which was + * registered with no language key. Invoking it with a language key returns the + * related translation table. + * + * @param {string} key A language key. + * @param {object} translationTable A plain old JavaScript object that represents a translation table. + * + */ + var translations = function (langKey, translationTable) { + + if (!langKey && !translationTable) { + return $translationTable; + } + + if (langKey && !translationTable) { + if (angular.isString(langKey)) { + return $translationTable[langKey]; + } + } else { + if (!angular.isObject($translationTable[langKey])) { + $translationTable[langKey] = {}; + } + angular.extend($translationTable[langKey], flatObject(translationTable)); } - result[keyWithPath] = val; - } - } - return result; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#addInterpolation - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Adds interpolation services to angular-translate, so it can manage them. - * - * @param {object} factory Interpolation service factory - */ - this.addInterpolation = function (factory) { - $interpolatorFactories.push(factory); - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use interpolation functionality of messageformat.js. - * This is useful when having high level pluralization and gender selection. - */ - this.useMessageFormatInterpolation = function () { - return this.useInterpolation('$translateMessageFormatInterpolation'); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useInterpolation - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate which interpolation style to use as default, application-wide. - * Simply pass a factory/service name. The interpolation service has to implement - * the correct interface. - * - * @param {string} factory Interpolation service name. - */ - this.useInterpolation = function (factory) { - $interpolationFactory = factory; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useSanitizeStrategy - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Simply sets a sanitation strategy type. - * - * @param {string} value Strategy type. - */ - this.useSanitizeValueStrategy = function (value) { - $interpolationSanitizationStrategy = value; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#preferredLanguage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells the module which of the registered translation tables to use for translation - * at initial startup by passing a language key. Similar to `$translateProvider#use` - * only that it says which language to **prefer**. - * - * @param {string} langKey A language key. - * - */ - this.preferredLanguage = function(langKey) { - setupPreferredLanguage(langKey); - return this; - - }; - var setupPreferredLanguage = function (langKey) { - if (langKey) { - $preferredLanguage = langKey; - } - return $preferredLanguage; - }; - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Sets an indicator which is used when a translation isn't found. E.g. when - * setting the indicator as 'X' and one tries to translate a translation id - * called `NOT_FOUND`, this will result in `X NOT_FOUND X`. - * - * Internally this methods sets a left indicator and a right indicator using - * `$translateProvider.translationNotFoundIndicatorLeft()` and - * `$translateProvider.translationNotFoundIndicatorRight()`. - * - * **Note**: These methods automatically add a whitespace between the indicators - * and the translation id. - * - * @param {string} indicator An indicator, could be any string. - */ - this.translationNotFoundIndicator = function (indicator) { - this.translationNotFoundIndicatorLeft(indicator); - this.translationNotFoundIndicatorRight(indicator); - return this; - }; - - /** - * ngdoc function - * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Sets an indicator which is used when a translation isn't found left to the - * translation id. - * - * @param {string} indicator An indicator. - */ - this.translationNotFoundIndicatorLeft = function (indicator) { - if (!indicator) { - return $notFoundIndicatorLeft; - } - $notFoundIndicatorLeft = indicator; - return this; - }; - - /** - * ngdoc function - * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Sets an indicator which is used when a translation isn't found right to the - * translation id. - * - * @param {string} indicator An indicator. - */ - this.translationNotFoundIndicatorRight = function (indicator) { - if (!indicator) { - return $notFoundIndicatorRight; - } - $notFoundIndicatorRight = indicator; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#fallbackLanguage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells the module which of the registered translation tables to use when missing translations - * at initial startup by passing a language key. Similar to `$translateProvider#use` - * only that it says which language to **fallback**. - * - * @param {string||array} langKey A language key. - * - */ - this.fallbackLanguage = function (langKey) { - fallbackStack(langKey); - return this; - }; - - var fallbackStack = function (langKey) { - if (langKey) { - if (angular.isString(langKey)) { - $fallbackWasString = true; - $fallbackLanguage = [ langKey ]; - } else if (angular.isArray(langKey)) { - $fallbackWasString = false; - $fallbackLanguage = langKey; - } - if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) { - $fallbackLanguage.push($preferredLanguage); - } - - return this; - } else { - if ($fallbackWasString) { - return $fallbackLanguage[0]; - } else { - return $fallbackLanguage; - } - } - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#use - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Set which translation table to use for translation by given language key. When - * trying to 'use' a language which isn't provided, it'll throw an error. - * - * You actually don't have to use this method since `$translateProvider#preferredLanguage` - * does the job too. - * - * @param {string} langKey A language key. - */ - this.use = function (langKey) { - if (langKey) { - if (!$translationTable[langKey] && (!$loaderFactory)) { - // only throw an error, when not loading translation data asynchronously - throw new Error("$translateProvider couldn't find translationTable for langKey: '" + langKey + "'"); - } - $uses = langKey; - return this; - } - return $uses; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#storageKey - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells the module which key must represent the choosed language by a user in the storage. - * - * @param {string} key A key for the storage. - */ - var storageKey = function(key) { - if (!key) { - if ($storagePrefix) { - return $storagePrefix + $storageKey; - } - return $storageKey; - } - $storageKey = key; - }; - - this.storageKey = storageKey; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useUrlLoader - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use `$translateUrlLoader` extension service as loader. - * - * @param {string} url Url - * @param {Object=} options Optional configuration object - */ - this.useUrlLoader = function (url, options) { - return this.useLoader('$translateUrlLoader', angular.extend({ url: url }, options)); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useStaticFilesLoader - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader. - * - * @param {Object=} options Optional configuration object - */ - this.useStaticFilesLoader = function (options) { - return this.useLoader('$translateStaticFilesLoader', options); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useLoader - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use any other service as loader. - * - * @param {string} loaderFactory Factory name to use - * @param {Object=} options Optional configuration object - */ - this.useLoader = function (loaderFactory, options) { - $loaderFactory = loaderFactory; - $loaderOptions = options || {}; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useLocalStorage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use `$translateLocalStorage` service as storage layer. - * - */ - this.useLocalStorage = function () { - return this.useStorage('$translateLocalStorage'); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useCookieStorage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use `$translateCookieStorage` service as storage layer. - */ - this.useCookieStorage = function () { - return this.useStorage('$translateCookieStorage'); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useStorage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use custom service as storage layer. - */ - this.useStorage = function (storageFactory) { - $storageFactory = storageFactory; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#storagePrefix - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Sets prefix for storage key. - * - * @param {string} prefix Storage key prefix - */ - this.storagePrefix = function (prefix) { - if (!prefix) { - return prefix; - } - $storagePrefix = prefix; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to use built-in log handler when trying to translate - * a translation Id which doesn't exist. - * - * This is actually a shortcut method for `useMissingTranslationHandler()`. - * - */ - this.useMissingTranslationHandlerLog = function () { - return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog'); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Expects a factory name which later gets instantiated with `$injector`. - * This method can be used to tell angular-translate to use a custom - * missingTranslationHandler. Just build a factory which returns a function - * and expects a translation id as argument. - * - * Example: - *
          -   *  app.config(function ($translateProvider) {
          +        return this;
          +    };
          +
          +    this.translations = translations;
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#cloakClassName
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     *
          +     * Let's you change the class name for `translate-cloak` directive.
          +     * Default class name is `translate-cloak`.
          +     *
          +     * @param {string} name translate-cloak class name
          +     */
          +    this.cloakClassName = function (name) {
          +        if (!name) {
          +            return $cloakClassName;
          +        }
          +        $cloakClassName = name;
          +        return this;
          +    };
          +
          +    /**
          +     * @name flatObject
          +     * @private
          +     *
          +     * @description
          +     * Flats an object. This function is used to flatten given translation data with
          +     * namespaces, so they are later accessible via dot notation.
          +     */
          +    var flatObject = function (data, path, result, prevKey) {
          +        var key, keyWithPath, keyWithShortPath, val;
          +
          +        if (!path) {
          +            path = [];
          +        }
          +        if (!result) {
          +            result = {};
          +        }
          +        for (key in data) {
          +            if (!Object.prototype.hasOwnProperty.call(data, key)) {
          +                continue;
          +            }
          +            val = data[key];
          +            if (angular.isObject(val)) {
          +                flatObject(val, path.concat(key), result, key);
          +            } else {
          +                keyWithPath = path.length ? ('' + path.join(NESTED_OBJECT_DELIMITER) + NESTED_OBJECT_DELIMITER + key) : key;
          +                if (path.length && key === prevKey) {
          +                    // Create shortcut path (foo.bar == foo.bar.bar)
          +                    keyWithShortPath = '' + path.join(NESTED_OBJECT_DELIMITER);
          +                    // Link it to original path
          +                    result[keyWithShortPath] = '@:' + keyWithPath;
          +                }
          +                result[keyWithPath] = val;
          +            }
          +        }
          +        return result;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#addInterpolation
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Adds interpolation services to angular-translate, so it can manage them.
          +     *
          +     * @param {object} factory Interpolation service factory
          +     */
          +    this.addInterpolation = function (factory) {
          +        $interpolatorFactories.push(factory);
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use interpolation functionality of messageformat.js.
          +     * This is useful when having high level pluralization and gender selection.
          +     */
          +    this.useMessageFormatInterpolation = function () {
          +        return this.useInterpolation('$translateMessageFormatInterpolation');
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useInterpolation
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate which interpolation style to use as default, application-wide.
          +     * Simply pass a factory/service name. The interpolation service has to implement
          +     * the correct interface.
          +     *
          +     * @param {string} factory Interpolation service name.
          +     */
          +    this.useInterpolation = function (factory) {
          +        $interpolationFactory = factory;
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useSanitizeStrategy
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Simply sets a sanitation strategy type.
          +     *
          +     * @param {string} value Strategy type.
          +     */
          +    this.useSanitizeValueStrategy = function (value) {
          +        $interpolationSanitizationStrategy = value;
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#preferredLanguage
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells the module which of the registered translation tables to use for translation
          +     * at initial startup by passing a language key. Similar to `$translateProvider#use`
          +     * only that it says which language to **prefer**.
          +     *
          +     * @param {string} langKey A language key.
          +     *
          +     */
          +    this.preferredLanguage = function (langKey) {
          +        setupPreferredLanguage(langKey);
          +        return this;
          +
          +    };
          +    var setupPreferredLanguage = function (langKey) {
          +        if (langKey) {
          +            $preferredLanguage = langKey;
          +        }
          +        return $preferredLanguage;
          +    };
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Sets an indicator which is used when a translation isn't found. E.g. when
          +     * setting the indicator as 'X' and one tries to translate a translation id
          +     * called `NOT_FOUND`, this will result in `X NOT_FOUND X`.
          +     *
          +     * Internally this methods sets a left indicator and a right indicator using
          +     * `$translateProvider.translationNotFoundIndicatorLeft()` and
          +     * `$translateProvider.translationNotFoundIndicatorRight()`.
          +     *
          +     * **Note**: These methods automatically add a whitespace between the indicators
          +     * and the translation id.
          +     *
          +     * @param {string} indicator An indicator, could be any string.
          +     */
          +    this.translationNotFoundIndicator = function (indicator) {
          +        this.translationNotFoundIndicatorLeft(indicator);
          +        this.translationNotFoundIndicatorRight(indicator);
          +        return this;
          +    };
          +
          +    /**
          +     * ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Sets an indicator which is used when a translation isn't found left to the
          +     * translation id.
          +     *
          +     * @param {string} indicator An indicator.
          +     */
          +    this.translationNotFoundIndicatorLeft = function (indicator) {
          +        if (!indicator) {
          +            return $notFoundIndicatorLeft;
          +        }
          +        $notFoundIndicatorLeft = indicator;
          +        return this;
          +    };
          +
          +    /**
          +     * ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Sets an indicator which is used when a translation isn't found right to the
          +     * translation id.
          +     *
          +     * @param {string} indicator An indicator.
          +     */
          +    this.translationNotFoundIndicatorRight = function (indicator) {
          +        if (!indicator) {
          +            return $notFoundIndicatorRight;
          +        }
          +        $notFoundIndicatorRight = indicator;
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#fallbackLanguage
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells the module which of the registered translation tables to use when missing translations
          +     * at initial startup by passing a language key. Similar to `$translateProvider#use`
          +     * only that it says which language to **fallback**.
          +     *
          +     * @param {string||array} langKey A language key.
          +     *
          +     */
          +    this.fallbackLanguage = function (langKey) {
          +        fallbackStack(langKey);
          +        return this;
          +    };
          +
          +    var fallbackStack = function (langKey) {
          +        if (langKey) {
          +            if (angular.isString(langKey)) {
          +                $fallbackWasString = true;
          +                $fallbackLanguage = [langKey];
          +            } else if (angular.isArray(langKey)) {
          +                $fallbackWasString = false;
          +                $fallbackLanguage = langKey;
          +            }
          +            if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) {
          +                $fallbackLanguage.push($preferredLanguage);
          +            }
          +
          +            return this;
          +        } else {
          +            if ($fallbackWasString) {
          +                return $fallbackLanguage[0];
          +            } else {
          +                return $fallbackLanguage;
          +            }
          +        }
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#use
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Set which translation table to use for translation by given language key. When
          +     * trying to 'use' a language which isn't provided, it'll throw an error.
          +     *
          +     * You actually don't have to use this method since `$translateProvider#preferredLanguage`
          +     * does the job too.
          +     *
          +     * @param {string} langKey A language key.
          +     */
          +    this.use = function (langKey) {
          +        if (langKey) {
          +            if (!$translationTable[langKey] && (!$loaderFactory)) {
          +                // only throw an error, when not loading translation data asynchronously
          +                throw new Error("$translateProvider couldn't find translationTable for langKey: '" + langKey + "'");
          +            }
          +            $uses = langKey;
          +            return this;
          +        }
          +        return $uses;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#storageKey
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells the module which key must represent the choosed language by a user in the storage.
          +     *
          +     * @param {string} key A key for the storage.
          +     */
          +    var storageKey = function (key) {
          +        if (!key) {
          +            if ($storagePrefix) {
          +                return $storagePrefix + $storageKey;
          +            }
          +            return $storageKey;
          +        }
          +        $storageKey = key;
          +    };
          +
          +    this.storageKey = storageKey;
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useUrlLoader
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use `$translateUrlLoader` extension service as loader.
          +     *
          +     * @param {string} url Url
          +     * @param {Object=} options Optional configuration object
          +     */
          +    this.useUrlLoader = function (url, options) {
          +        return this.useLoader('$translateUrlLoader', angular.extend({url: url}, options));
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useStaticFilesLoader
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader.
          +     *
          +     * @param {Object=} options Optional configuration object
          +     */
          +    this.useStaticFilesLoader = function (options) {
          +        return this.useLoader('$translateStaticFilesLoader', options);
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useLoader
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use any other service as loader.
          +     *
          +     * @param {string} loaderFactory Factory name to use
          +     * @param {Object=} options Optional configuration object
          +     */
          +    this.useLoader = function (loaderFactory, options) {
          +        $loaderFactory = loaderFactory;
          +        $loaderOptions = options || {};
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useLocalStorage
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use `$translateLocalStorage` service as storage layer.
          +     *
          +     */
          +    this.useLocalStorage = function () {
          +        return this.useStorage('$translateLocalStorage');
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useCookieStorage
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use `$translateCookieStorage` service as storage layer.
          +     */
          +    this.useCookieStorage = function () {
          +        return this.useStorage('$translateCookieStorage');
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useStorage
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use custom service as storage layer.
          +     */
          +    this.useStorage = function (storageFactory) {
          +        $storageFactory = storageFactory;
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#storagePrefix
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Sets prefix for storage key.
          +     *
          +     * @param {string} prefix Storage key prefix
          +     */
          +    this.storagePrefix = function (prefix) {
          +        if (!prefix) {
          +            return prefix;
          +        }
          +        $storagePrefix = prefix;
          +        return this;
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Tells angular-translate to use built-in log handler when trying to translate
          +     * a translation Id which doesn't exist.
          +     *
          +     * This is actually a shortcut method for `useMissingTranslationHandler()`.
          +     *
          +     */
          +    this.useMissingTranslationHandlerLog = function () {
          +        return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog');
          +    };
          +
          +    /**
          +     * @ngdoc function
          +     * @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler
          +     * @methodOf pascalprecht.translate.$translateProvider
          +     *
          +     * @description
          +     * Expects a factory name which later gets instantiated with `$injector`.
          +     * This method can be used to tell angular-translate to use a custom
          +     * missingTranslationHandler. Just build a factory which returns a function
          +     * and expects a translation id as argument.
          +     *
          +     * Example:
          +     * 
          +     *  app.config(function ($translateProvider) {
              *    $translateProvider.useMissingTranslationHandler('customHandler');
              *  });
          -   *
          -   *  app.factory('customHandler', function (dep1, dep2) {
          +     *
          +     *  app.factory('customHandler', function (dep1, dep2) {
              *    return function (translationId) {
              *      // something with translationId and dep1 and dep2
              *    };
              *  });
          -   * 
          - * - * @param {string} factory Factory name - */ - this.useMissingTranslationHandler = function (factory) { - $missingTranslationHandlerFactory = factory; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#usePostCompiling - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * If post compiling is enabled, all translated values will be processed - * again with AngularJS' $compile. - * - * Example: - *
          -   *  app.config(function ($translateProvider) {
          +     * 
          + * + * @param {string} factory Factory name + */ + this.useMissingTranslationHandler = function (factory) { + $missingTranslationHandlerFactory = factory; + return this; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateProvider#usePostCompiling + * @methodOf pascalprecht.translate.$translateProvider + * + * @description + * If post compiling is enabled, all translated values will be processed + * again with AngularJS' $compile. + * + * Example: + *
          +     *  app.config(function ($translateProvider) {
              *    $translateProvider.usePostCompiling(true);
              *  });
          -   * 
          - * - * @param {string} factory Factory name - */ - this.usePostCompiling = function (value) { - $postCompilingEnabled = !(!value); - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#determinePreferredLanguage - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Tells angular-translate to try to determine on its own which language key - * to set as preferred language. When `fn` is given, angular-translate uses it - * to determine a language key, otherwise it uses the built-in `getLocale()` - * method. - * - * The `getLocale()` returns a language key in the format `[lang]_[country]` or - * `[lang]` depending on what the browser provides. - * - * Use this method at your own risk, since not all browsers return a valid - * locale. - * - * @param {object=} fn Function to determine a browser's locale - */ - this.determinePreferredLanguage = function (fn) { - - var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale(); - - if (!$availableLanguageKeys.length) { - $preferredLanguage = locale; - } else { - $preferredLanguage = negotiateLocale(locale); - } - - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Registers a set of language keys the app will work with. Use this method in - * combination with - * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}. - * When available languages keys are registered, angular-translate - * tries to find the best fitting language key depending on the browsers locale, - * considering your language key convention. - * - * @param {object} languageKeys Array of language keys the your app will use - * @param {object=} aliases Alias map. - */ - this.registerAvailableLanguageKeys = function (languageKeys, aliases) { - if (languageKeys) { - $availableLanguageKeys = languageKeys; - if (aliases) { - $languageKeyAliases = aliases; - } - return this; - } - return $availableLanguageKeys; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateProvider#useLoaderCache - * @methodOf pascalprecht.translate.$translateProvider - * - * @description - * Registers a cache for internal $http based loaders. - * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}. - * When false the cache will be disabled (default). When true or undefined - * the cache will be a default (see $cacheFactory). When an object it will - * be treat as a cache object itself: the usage is $http({cache: cache}) - * - * @param {object} cache boolean, string or cache-object - */ - this.useLoaderCache = function (cache) { - if (cache === false) { - // disable cache - loaderCache = undefined; - } else if (cache === true) { - // enable cache using AJS defaults - loaderCache = true; - } else if (typeof(cache) === 'undefined') { - // enable cache using default - loaderCache = '$translationCache'; - } else if (cache) { - // enable cache using given one (see $cacheFactory) - loaderCache = cache; - } - return this; - }; - - /** - * @ngdoc object - * @name pascalprecht.translate.$translate - * @requires $interpolate - * @requires $log - * @requires $rootScope - * @requires $q - * - * @description - * The `$translate` service is the actual core of angular-translate. It expects a translation id - * and optional interpolate parameters to translate contents. - * - *
          -   *  $translate('HEADLINE_TEXT').then(function (translation) {
          +     * 
          + * + * @param {string} factory Factory name + */ + this.usePostCompiling = function (value) { + $postCompilingEnabled = !(!value); + return this; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateProvider#determinePreferredLanguage + * @methodOf pascalprecht.translate.$translateProvider + * + * @description + * Tells angular-translate to try to determine on its own which language key + * to set as preferred language. When `fn` is given, angular-translate uses it + * to determine a language key, otherwise it uses the built-in `getLocale()` + * method. + * + * The `getLocale()` returns a language key in the format `[lang]_[country]` or + * `[lang]` depending on what the browser provides. + * + * Use this method at your own risk, since not all browsers return a valid + * locale. + * + * @param {object=} fn Function to determine a browser's locale + */ + this.determinePreferredLanguage = function (fn) { + + var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale(); + + if (!$availableLanguageKeys.length) { + $preferredLanguage = locale; + } else { + $preferredLanguage = negotiateLocale(locale); + } + + return this; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys + * @methodOf pascalprecht.translate.$translateProvider + * + * @description + * Registers a set of language keys the app will work with. Use this method in + * combination with + * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}. + * When available languages keys are registered, angular-translate + * tries to find the best fitting language key depending on the browsers locale, + * considering your language key convention. + * + * @param {object} languageKeys Array of language keys the your app will use + * @param {object=} aliases Alias map. + */ + this.registerAvailableLanguageKeys = function (languageKeys, aliases) { + if (languageKeys) { + $availableLanguageKeys = languageKeys; + if (aliases) { + $languageKeyAliases = aliases; + } + return this; + } + return $availableLanguageKeys; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateProvider#useLoaderCache + * @methodOf pascalprecht.translate.$translateProvider + * + * @description + * Registers a cache for internal $http based loaders. + * {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}. + * When false the cache will be disabled (default). When true or undefined + * the cache will be a default (see $cacheFactory). When an object it will + * be treat as a cache object itself: the usage is $http({cache: cache}) + * + * @param {object} cache boolean, string or cache-object + */ + this.useLoaderCache = function (cache) { + if (cache === false) { + // disable cache + loaderCache = undefined; + } else if (cache === true) { + // enable cache using AJS defaults + loaderCache = true; + } else if (typeof(cache) === 'undefined') { + // enable cache using default + loaderCache = '$translationCache'; + } else if (cache) { + // enable cache using given one (see $cacheFactory) + loaderCache = cache; + } + return this; + }; + + /** + * @ngdoc object + * @name pascalprecht.translate.$translate + * @requires $interpolate + * @requires $log + * @requires $rootScope + * @requires $q + * + * @description + * The `$translate` service is the actual core of angular-translate. It expects a translation id + * and optional interpolate parameters to translate contents. + * + *
          +     *  $translate('HEADLINE_TEXT').then(function (translation) {
              *    $scope.translatedText = translation;
              *  });
          -   * 
          - * - * @param {string|array} translationId A token which represents a translation id - * This can be optionally an array of translation ids which - * results that the function returns an object where each key - * is the translation id and the value the translation. - * @param {object=} interpolateParams An object hash for dynamic values - * @param {string} interpolationId The id of the interpolation to use - * @returns {object} promise - */ - this.$get = [ - '$log', - '$injector', - '$rootScope', - '$q', - function ($log, $injector, $rootScope, $q) { - - var Storage, - defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'), - pendingLoader = false, - interpolatorHashMap = {}, - langPromises = {}, - fallbackIndex, - startFallbackIteration; - - var $translate = function (translationId, interpolateParams, interpolationId) { - - // Duck detection: If the first argument is an array, a bunch of translations was requested. - // The result is an object. - if (angular.isArray(translationId)) { - // Inspired by Q.allSettled by Kris Kowal - // https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563 - // This transforms all promises regardless resolved or rejected - var translateAll = function (translationIds) { - var results = {}; // storing the actual results - var promises = []; // promises to wait for - // Wraps the promise a) being always resolved and b) storing the link id->value - var translate = function (translationId) { - var deferred = $q.defer(); - var regardless = function (value) { - results[translationId] = value; - deferred.resolve([translationId, value]); - }; - // we don't care whether the promise was resolved or rejected; just store the values - $translate(translationId, interpolateParams, interpolationId).then(regardless, regardless); - return deferred.promise; + *
          + * + * @param {string|array} translationId A token which represents a translation id + * This can be optionally an array of translation ids which + * results that the function returns an object where each key + * is the translation id and the value the translation. + * @param {object=} interpolateParams An object hash for dynamic values + * @param {string} interpolationId The id of the interpolation to use + * @returns {object} promise + */ + this.$get = [ + '$log', + '$injector', + '$rootScope', + '$q', + function ($log, $injector, $rootScope, $q) { + + var Storage, + defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'), + pendingLoader = false, + interpolatorHashMap = {}, + langPromises = {}, + fallbackIndex, + startFallbackIteration; + + var $translate = function (translationId, interpolateParams, interpolationId) { + + // Duck detection: If the first argument is an array, a bunch of translations was requested. + // The result is an object. + if (angular.isArray(translationId)) { + // Inspired by Q.allSettled by Kris Kowal + // https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563 + // This transforms all promises regardless resolved or rejected + var translateAll = function (translationIds) { + var results = {}; // storing the actual results + var promises = []; // promises to wait for + // Wraps the promise a) being always resolved and b) storing the link id->value + var translate = function (translationId) { + var deferred = $q.defer(); + var regardless = function (value) { + results[translationId] = value; + deferred.resolve([translationId, value]); + }; + // we don't care whether the promise was resolved or rejected; just store the values + $translate(translationId, interpolateParams, interpolationId).then(regardless, regardless); + return deferred.promise; + }; + for (var i = 0, c = translationIds.length; i < c; i++) { + promises.push(translate(translationIds[i])); + } + // wait for all (including storing to results) + return $q.all(promises).then(function () { + // return the results + return results; + }); + }; + return translateAll(translationId); + } + + var deferred = $q.defer(); + + // trim off any whitespace + if (translationId) { + translationId = trim.apply(translationId); + } + + var promiseToWaitFor = (function () { + var promise = $preferredLanguage ? + langPromises[$preferredLanguage] : + langPromises[$uses]; + + fallbackIndex = 0; + + if ($storageFactory && !promise) { + // looks like there's no pending promise for $preferredLanguage or + // $uses. Maybe there's one pending for a language that comes from + // storage. + var langKey = Storage.get($storageKey); + promise = langPromises[langKey]; + + if ($fallbackLanguage && $fallbackLanguage.length) { + var index = indexOf($fallbackLanguage, langKey); + // maybe the language from storage is also defined as fallback language + // we increase the fallback language index to not search in that language + // as fallback, since it's probably the first used language + // in that case the index starts after the first element + fallbackIndex = (index === 0) ? 1 : 0; + + // but we can make sure to ALWAYS fallback to preferred language at least + if (indexOf($fallbackLanguage, $preferredLanguage) < 0) { + $fallbackLanguage.push($preferredLanguage); + } + } + } + return promise; + }()); + + if (!promiseToWaitFor) { + // no promise to wait for? okay. Then there's no loader registered + // nor is a one pending for language that comes from storage. + // We can just translate. + determineTranslation(translationId, interpolateParams, interpolationId).then(deferred.resolve, deferred.reject); + } else { + promiseToWaitFor.then(function () { + determineTranslation(translationId, interpolateParams, interpolationId).then(deferred.resolve, deferred.reject); + }, deferred.reject); + } + return deferred.promise; }; - for (var i = 0, c = translationIds.length; i < c; i++) { - promises.push(translate(translationIds[i])); - } - // wait for all (including storing to results) - return $q.all(promises).then(function () { - // return the results - return results; - }); - }; - return translateAll(translationId); - } - var deferred = $q.defer(); + /** + * @name applyNotFoundIndicators + * @private + * + * @description + * Applies not fount indicators to given translation id, if needed. + * This function gets only executed, if a translation id doesn't exist, + * which is why a translation id is expected as argument. + * + * @param {string} translationId Translation id. + * @returns {string} Same as given translation id but applied with not found + * indicators. + */ + var applyNotFoundIndicators = function (translationId) { + // applying notFoundIndicators + if ($notFoundIndicatorLeft) { + translationId = [$notFoundIndicatorLeft, translationId].join(' '); + } + if ($notFoundIndicatorRight) { + translationId = [translationId, $notFoundIndicatorRight].join(' '); + } + return translationId; + }; - // trim off any whitespace - if (translationId) { - translationId = trim.apply(translationId); - } + /** + * @name useLanguage + * @private + * + * @description + * Makes actual use of a language by setting a given language key as used + * language and informs registered interpolators to also use the given + * key as locale. + * + * @param {key} Locale key. + */ + var useLanguage = function (key) { + $uses = key; + $rootScope.$emit('$translateChangeSuccess', {language: key}); + + if ($storageFactory) { + Storage.put($translate.storageKey(), $uses); + } + // inform default interpolator + defaultInterpolator.setLocale($uses); + // inform all others too! + angular.forEach(interpolatorHashMap, function (interpolator, id) { + interpolatorHashMap[id].setLocale($uses); + }); + $rootScope.$emit('$translateChangeEnd', {language: key}); + }; - var promiseToWaitFor = (function () { - var promise = $preferredLanguage ? - langPromises[$preferredLanguage] : - langPromises[$uses]; - - fallbackIndex = 0; - - if ($storageFactory && !promise) { - // looks like there's no pending promise for $preferredLanguage or - // $uses. Maybe there's one pending for a language that comes from - // storage. - var langKey = Storage.get($storageKey); - promise = langPromises[langKey]; - - if ($fallbackLanguage && $fallbackLanguage.length) { - var index = indexOf($fallbackLanguage, langKey); - // maybe the language from storage is also defined as fallback language - // we increase the fallback language index to not search in that language - // as fallback, since it's probably the first used language - // in that case the index starts after the first element - fallbackIndex = (index === 0) ? 1 : 0; - - // but we can make sure to ALWAYS fallback to preferred language at least - if (indexOf($fallbackLanguage, $preferredLanguage) < 0) { - $fallbackLanguage.push($preferredLanguage); + /** + * @name loadAsync + * @private + * + * @description + * Kicks of registered async loader using `$injector` and applies existing + * loader options. When resolved, it updates translation tables accordingly + * or rejects with given language key. + * + * @param {string} key Language key. + * @return {Promise} A promise. + */ + var loadAsync = function (key) { + if (!key) { + throw 'No language key specified for loading.'; } - } - } - return promise; - }()); - - if (!promiseToWaitFor) { - // no promise to wait for? okay. Then there's no loader registered - // nor is a one pending for language that comes from storage. - // We can just translate. - determineTranslation(translationId, interpolateParams, interpolationId).then(deferred.resolve, deferred.reject); - } else { - promiseToWaitFor.then(function () { - determineTranslation(translationId, interpolateParams, interpolationId).then(deferred.resolve, deferred.reject); - }, deferred.reject); - } - return deferred.promise; - }; - - /** - * @name applyNotFoundIndicators - * @private - * - * @description - * Applies not fount indicators to given translation id, if needed. - * This function gets only executed, if a translation id doesn't exist, - * which is why a translation id is expected as argument. - * - * @param {string} translationId Translation id. - * @returns {string} Same as given translation id but applied with not found - * indicators. - */ - var applyNotFoundIndicators = function (translationId) { - // applying notFoundIndicators - if ($notFoundIndicatorLeft) { - translationId = [$notFoundIndicatorLeft, translationId].join(' '); - } - if ($notFoundIndicatorRight) { - translationId = [translationId, $notFoundIndicatorRight].join(' '); - } - return translationId; - }; - - /** - * @name useLanguage - * @private - * - * @description - * Makes actual use of a language by setting a given language key as used - * language and informs registered interpolators to also use the given - * key as locale. - * - * @param {key} Locale key. - */ - var useLanguage = function (key) { - $uses = key; - $rootScope.$emit('$translateChangeSuccess', {language: key}); - - if ($storageFactory) { - Storage.put($translate.storageKey(), $uses); - } - // inform default interpolator - defaultInterpolator.setLocale($uses); - // inform all others too! - angular.forEach(interpolatorHashMap, function (interpolator, id) { - interpolatorHashMap[id].setLocale($uses); - }); - $rootScope.$emit('$translateChangeEnd', {language: key}); - }; - - /** - * @name loadAsync - * @private - * - * @description - * Kicks of registered async loader using `$injector` and applies existing - * loader options. When resolved, it updates translation tables accordingly - * or rejects with given language key. - * - * @param {string} key Language key. - * @return {Promise} A promise. - */ - var loadAsync = function (key) { - if (!key) { - throw 'No language key specified for loading.'; - } - var deferred = $q.defer(); + var deferred = $q.defer(); - $rootScope.$emit('$translateLoadingStart', {language: key}); - pendingLoader = true; + $rootScope.$emit('$translateLoadingStart', {language: key}); + pendingLoader = true; - var cache = loaderCache; - if (typeof(cache) === 'string') { - // getting on-demand instance of loader - cache = $injector.get(cache); - } + var cache = loaderCache; + if (typeof(cache) === 'string') { + // getting on-demand instance of loader + cache = $injector.get(cache); + } - var loaderOptions = angular.extend({}, $loaderOptions, { - key: key, - $http: angular.extend({}, { - cache: cache - }, $loaderOptions.$http) - }); + var loaderOptions = angular.extend({}, $loaderOptions, { + key: key, + $http: angular.extend({}, { + cache: cache + }, $loaderOptions.$http) + }); - $injector.get($loaderFactory)(loaderOptions).then(function (data) { - var translationTable = {}; - $rootScope.$emit('$translateLoadingSuccess', {language: key}); - - if (angular.isArray(data)) { - angular.forEach(data, function (table) { - angular.extend(translationTable, flatObject(table)); - }); - } else { - angular.extend(translationTable, flatObject(data)); - } - pendingLoader = false; - deferred.resolve({ - key: key, - table: translationTable - }); - $rootScope.$emit('$translateLoadingEnd', {language: key}); - }, function (key) { - $rootScope.$emit('$translateLoadingError', {language: key}); - deferred.reject(key); - $rootScope.$emit('$translateLoadingEnd', {language: key}); - }); - return deferred.promise; - }; + $injector.get($loaderFactory)(loaderOptions).then(function (data) { + var translationTable = {}; + $rootScope.$emit('$translateLoadingSuccess', {language: key}); + + if (angular.isArray(data)) { + angular.forEach(data, function (table) { + angular.extend(translationTable, flatObject(table)); + }); + } else { + angular.extend(translationTable, flatObject(data)); + } + pendingLoader = false; + deferred.resolve({ + key: key, + table: translationTable + }); + $rootScope.$emit('$translateLoadingEnd', {language: key}); + }, function (key) { + $rootScope.$emit('$translateLoadingError', {language: key}); + deferred.reject(key); + $rootScope.$emit('$translateLoadingEnd', {language: key}); + }); + return deferred.promise; + }; - if ($storageFactory) { - Storage = $injector.get($storageFactory); + if ($storageFactory) { + Storage = $injector.get($storageFactory); - if (!Storage.get || !Storage.put) { - throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or put() method!'); - } - } - - // apply additional settings - if (angular.isFunction(defaultInterpolator.useSanitizeValueStrategy)) { - defaultInterpolator.useSanitizeValueStrategy($interpolationSanitizationStrategy); - } - - // if we have additional interpolations that were added via - // $translateProvider.addInterpolation(), we have to map'em - if ($interpolatorFactories.length) { - angular.forEach($interpolatorFactories, function (interpolatorFactory) { - var interpolator = $injector.get(interpolatorFactory); - // setting initial locale for each interpolation service - interpolator.setLocale($preferredLanguage || $uses); - // apply additional settings - if (angular.isFunction(interpolator.useSanitizeValueStrategy)) { - interpolator.useSanitizeValueStrategy($interpolationSanitizationStrategy); - } - // make'em recognizable through id - interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator; - }); - } - - /** - * @name getTranslationTable - * @private - * - * @description - * Returns a promise that resolves to the translation table - * or is rejected if an error occurred. - * - * @param langKey - * @returns {Q.promise} - */ - var getTranslationTable = function (langKey) { - var deferred = $q.defer(); - if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) { - deferred.resolve($translationTable[langKey]); - } else if (langPromises[langKey]) { - langPromises[langKey].then(function (data) { - translations(data.key, data.table); - deferred.resolve(data.table); - }, deferred.reject); - } else { - deferred.reject(); - } - return deferred.promise; - }; - - /** - * @name getFallbackTranslation - * @private - * - * @description - * Returns a promise that will resolve to the translation - * or be rejected if no translation was found for the language. - * This function is currently only used for fallback language translation. - * - * @param langKey The language to translate to. - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {Q.promise} - */ - var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) { - var deferred = $q.defer(); - - getTranslationTable(langKey).then(function (translationTable) { - if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) { - Interpolator.setLocale(langKey); - deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams)); - Interpolator.setLocale($uses); - } else { - deferred.reject(); - } - }, deferred.reject); - - return deferred.promise; - }; - - /** - * @name getFallbackTranslationInstant - * @private - * - * @description - * Returns a translation - * This function is currently only used for fallback language translation. - * - * @param langKey The language to translate to. - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {string} translation - */ - var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) { - var result, translationTable = $translationTable[langKey]; - - if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) { - Interpolator.setLocale(langKey); - result = Interpolator.interpolate(translationTable[translationId], interpolateParams); - Interpolator.setLocale($uses); - } + if (!Storage.get || !Storage.put) { + throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or put() method!'); + } + } - return result; - }; - - - /** - * @name translateByHandler - * @private - * - * Translate by missing translation handler. - * - * @param translationId - * @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is - * absent - */ - var translateByHandler = function (translationId) { - // If we have a handler factory - we might also call it here to determine if it provides - // a default text for a translationid that can't be found anywhere in our tables - if ($missingTranslationHandlerFactory) { - var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses); - if (resultString !== undefined) { - return resultString; - } else { - return translationId; - } - } else { - return translationId; - } - }; - - /** - * @name resolveForFallbackLanguage - * @private - * - * Recursive helper function for fallbackTranslation that will sequentially look - * for a translation in the fallbackLanguages starting with fallbackLanguageIndex. - * - * @param fallbackLanguageIndex - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {Q.promise} Promise that will resolve to the translation. - */ - var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) { - var deferred = $q.defer(); - - if (fallbackLanguageIndex < $fallbackLanguage.length) { - var langKey = $fallbackLanguage[fallbackLanguageIndex]; - getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then( - deferred.resolve, - function () { - // Look in the next fallback language for a translation. - // It delays the resolving by passing another promise to resolve. - resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator).then(deferred.resolve); + // apply additional settings + if (angular.isFunction(defaultInterpolator.useSanitizeValueStrategy)) { + defaultInterpolator.useSanitizeValueStrategy($interpolationSanitizationStrategy); } - ); - } else { - // No translation found in any fallback language - deferred.resolve(translateByHandler(translationId)); - } - return deferred.promise; - }; - - /** - * @name resolveForFallbackLanguageInstant - * @private - * - * Recursive helper function for fallbackTranslation that will sequentially look - * for a translation in the fallbackLanguages starting with fallbackLanguageIndex. - * - * @param fallbackLanguageIndex - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {string} translation - */ - var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) { - var result; - if (fallbackLanguageIndex < $fallbackLanguage.length) { - var langKey = $fallbackLanguage[fallbackLanguageIndex]; - result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator); - if (!result) { - result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator); - } - } - return result; - }; - - /** - * Translates with the usage of the fallback languages. - * - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {Q.promise} Promise, that resolves to the translation. - */ - var fallbackTranslation = function (translationId, interpolateParams, Interpolator) { - // Start with the fallbackLanguage with index 0 - return resolveForFallbackLanguage((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator); - }; - - /** - * Translates with the usage of the fallback languages. - * - * @param translationId - * @param interpolateParams - * @param Interpolator - * @returns {String} translation - */ - var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) { - // Start with the fallbackLanguage with index 0 - return resolveForFallbackLanguageInstant((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator); - }; - - var determineTranslation = function (translationId, interpolateParams, interpolationId) { - - var deferred = $q.defer(); - - var table = $uses ? $translationTable[$uses] : $translationTable, - Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator; - - // if the translation id exists, we can just interpolate it - if (table && Object.prototype.hasOwnProperty.call(table, translationId)) { - var translation = table[translationId]; - - // If using link, rerun $translate with linked translationId and return it - if (translation.substr(0, 2) === '@:') { - - $translate(translation.substr(2), interpolateParams, interpolationId) - .then(deferred.resolve, deferred.reject); - } else { - deferred.resolve(Interpolator.interpolate(translation, interpolateParams)); - } - } else { - var missingTranslationHandlerTranslation; - // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise - if ($missingTranslationHandlerFactory && !pendingLoader) { - missingTranslationHandlerTranslation = translateByHandler(translationId); - } - - // since we couldn't translate the inital requested translation id, - // we try it now with one or more fallback languages, if fallback language(s) is - // configured. - if ($uses && $fallbackLanguage && $fallbackLanguage.length) { - fallbackTranslation(translationId, interpolateParams, Interpolator) - .then(function (translation) { - deferred.resolve(translation); - }, function (_translationId) { - deferred.reject(applyNotFoundIndicators(_translationId)); + // if we have additional interpolations that were added via + // $translateProvider.addInterpolation(), we have to map'em + if ($interpolatorFactories.length) { + angular.forEach($interpolatorFactories, function (interpolatorFactory) { + var interpolator = $injector.get(interpolatorFactory); + // setting initial locale for each interpolation service + interpolator.setLocale($preferredLanguage || $uses); + // apply additional settings + if (angular.isFunction(interpolator.useSanitizeValueStrategy)) { + interpolator.useSanitizeValueStrategy($interpolationSanitizationStrategy); + } + // make'em recognizable through id + interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator; }); - } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) { - // looks like the requested translation id doesn't exists. - // Now, if there is a registered handler for missing translations and no - // asyncLoader is pending, we execute the handler - deferred.resolve(missingTranslationHandlerTranslation); - } else { - deferred.reject(applyNotFoundIndicators(translationId)); - } - } - return deferred.promise; - }; + } - var determineTranslationInstant = function (translationId, interpolateParams, interpolationId) { + /** + * @name getTranslationTable + * @private + * + * @description + * Returns a promise that resolves to the translation table + * or is rejected if an error occurred. + * + * @param langKey + * @returns {Q.promise} + */ + var getTranslationTable = function (langKey) { + var deferred = $q.defer(); + if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) { + deferred.resolve($translationTable[langKey]); + } else if (langPromises[langKey]) { + langPromises[langKey].then(function (data) { + translations(data.key, data.table); + deferred.resolve(data.table); + }, deferred.reject); + } else { + deferred.reject(); + } + return deferred.promise; + }; + + /** + * @name getFallbackTranslation + * @private + * + * @description + * Returns a promise that will resolve to the translation + * or be rejected if no translation was found for the language. + * This function is currently only used for fallback language translation. + * + * @param langKey The language to translate to. + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {Q.promise} + */ + var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) { + var deferred = $q.defer(); + + getTranslationTable(langKey).then(function (translationTable) { + if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) { + Interpolator.setLocale(langKey); + deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams)); + Interpolator.setLocale($uses); + } else { + deferred.reject(); + } + }, deferred.reject); + + return deferred.promise; + }; - var result, table = $uses ? $translationTable[$uses] : $translationTable, - Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator; + /** + * @name getFallbackTranslationInstant + * @private + * + * @description + * Returns a translation + * This function is currently only used for fallback language translation. + * + * @param langKey The language to translate to. + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {string} translation + */ + var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) { + var result, translationTable = $translationTable[langKey]; + + if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) { + Interpolator.setLocale(langKey); + result = Interpolator.interpolate(translationTable[translationId], interpolateParams); + Interpolator.setLocale($uses); + } - // if the translation id exists, we can just interpolate it - if (table && Object.prototype.hasOwnProperty.call(table, translationId)) { - var translation = table[translationId]; + return result; + }; - // If using link, rerun $translate with linked translationId and return it - if (translation.substr(0, 2) === '@:') { - result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId); - } else { - result = Interpolator.interpolate(translation, interpolateParams); - } - } else { - var missingTranslationHandlerTranslation; - // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise - if ($missingTranslationHandlerFactory && !pendingLoader) { - missingTranslationHandlerTranslation = translateByHandler(translationId); - } - - // since we couldn't translate the inital requested translation id, - // we try it now with one or more fallback languages, if fallback language(s) is - // configured. - if ($uses && $fallbackLanguage && $fallbackLanguage.length) { - fallbackIndex = 0; - result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator); - } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) { - // looks like the requested translation id doesn't exists. - // Now, if there is a registered handler for missing translations and no - // asyncLoader is pending, we execute the handler - result = missingTranslationHandlerTranslation; - } else { - result = applyNotFoundIndicators(translationId); - } - } - return result; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#preferredLanguage - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the language key for the preferred language. - * - * @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime) - * - * @return {string} preferred language key - */ - $translate.preferredLanguage = function (langKey) { - if(langKey) { - setupPreferredLanguage(langKey); - } - return $preferredLanguage; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#cloakClassName - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the configured class name for `translate-cloak` directive. - * - * @return {string} cloakClassName - */ - $translate.cloakClassName = function () { - return $cloakClassName; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#fallbackLanguage - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the language key for the fallback languages or sets a new fallback stack. - * - * @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime) - * - * @return {string||array} fallback language key - */ - $translate.fallbackLanguage = function (langKey) { - if (langKey !== undefined && langKey !== null) { - fallbackStack(langKey); - - // as we might have an async loader initiated and a new translation language might have been defined - // we need to add the promise to the stack also. So - iterate. - if ($loaderFactory) { - if ($fallbackLanguage && $fallbackLanguage.length) { - for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { - if (!langPromises[$fallbackLanguage[i]]) { - langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]); + /** + * @name translateByHandler + * @private + * + * Translate by missing translation handler. + * + * @param translationId + * @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is + * absent + */ + var translateByHandler = function (translationId) { + // If we have a handler factory - we might also call it here to determine if it provides + // a default text for a translationid that can't be found anywhere in our tables + if ($missingTranslationHandlerFactory) { + var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses); + if (resultString !== undefined) { + return resultString; + } else { + return translationId; + } + } else { + return translationId; } - } - } - } - $translate.use($translate.use()); - } - if ($fallbackWasString) { - return $fallbackLanguage[0]; - } else { - return $fallbackLanguage; - } + }; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#useFallbackLanguage - * @methodOf pascalprecht.translate.$translate - * - * @description - * Sets the first key of the fallback language stack to be used for translation. - * Therefore all languages in the fallback array BEFORE this key will be skipped! - * - * @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to - * get back to the whole stack - */ - $translate.useFallbackLanguage = function (langKey) { - if (langKey !== undefined && langKey !== null) { - if (!langKey) { - startFallbackIteration = 0; - } else { - var langKeyPosition = indexOf($fallbackLanguage, langKey); - if (langKeyPosition > -1) { - startFallbackIteration = langKeyPosition; - } - } + /** + * @name resolveForFallbackLanguage + * @private + * + * Recursive helper function for fallbackTranslation that will sequentially look + * for a translation in the fallbackLanguages starting with fallbackLanguageIndex. + * + * @param fallbackLanguageIndex + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {Q.promise} Promise that will resolve to the translation. + */ + var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) { + var deferred = $q.defer(); + + if (fallbackLanguageIndex < $fallbackLanguage.length) { + var langKey = $fallbackLanguage[fallbackLanguageIndex]; + getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then( + deferred.resolve, + function () { + // Look in the next fallback language for a translation. + // It delays the resolving by passing another promise to resolve. + resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator).then(deferred.resolve); + } + ); + } else { + // No translation found in any fallback language + deferred.resolve(translateByHandler(translationId)); + } + return deferred.promise; + }; - } + /** + * @name resolveForFallbackLanguageInstant + * @private + * + * Recursive helper function for fallbackTranslation that will sequentially look + * for a translation in the fallbackLanguages starting with fallbackLanguageIndex. + * + * @param fallbackLanguageIndex + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {string} translation + */ + var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) { + var result; + + if (fallbackLanguageIndex < $fallbackLanguage.length) { + var langKey = $fallbackLanguage[fallbackLanguageIndex]; + result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator); + if (!result) { + result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator); + } + } + return result; + }; + + /** + * Translates with the usage of the fallback languages. + * + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {Q.promise} Promise, that resolves to the translation. + */ + var fallbackTranslation = function (translationId, interpolateParams, Interpolator) { + // Start with the fallbackLanguage with index 0 + return resolveForFallbackLanguage((startFallbackIteration > 0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator); + }; + + /** + * Translates with the usage of the fallback languages. + * + * @param translationId + * @param interpolateParams + * @param Interpolator + * @returns {String} translation + */ + var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) { + // Start with the fallbackLanguage with index 0 + return resolveForFallbackLanguageInstant((startFallbackIteration > 0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator); + }; + + var determineTranslation = function (translationId, interpolateParams, interpolationId) { + + var deferred = $q.defer(); + + var table = $uses ? $translationTable[$uses] : $translationTable, + Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator; + + // if the translation id exists, we can just interpolate it + if (table && Object.prototype.hasOwnProperty.call(table, translationId)) { + var translation = table[translationId]; + + // If using link, rerun $translate with linked translationId and return it + if (translation.substr(0, 2) === '@:') { + + $translate(translation.substr(2), interpolateParams, interpolationId) + .then(deferred.resolve, deferred.reject); + } else { + deferred.resolve(Interpolator.interpolate(translation, interpolateParams)); + } + } else { + var missingTranslationHandlerTranslation; + // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise + if ($missingTranslationHandlerFactory && !pendingLoader) { + missingTranslationHandlerTranslation = translateByHandler(translationId); + } + + // since we couldn't translate the inital requested translation id, + // we try it now with one or more fallback languages, if fallback language(s) is + // configured. + if ($uses && $fallbackLanguage && $fallbackLanguage.length) { + fallbackTranslation(translationId, interpolateParams, Interpolator) + .then(function (translation) { + deferred.resolve(translation); + }, function (_translationId) { + deferred.reject(applyNotFoundIndicators(_translationId)); + }); + } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) { + // looks like the requested translation id doesn't exists. + // Now, if there is a registered handler for missing translations and no + // asyncLoader is pending, we execute the handler + deferred.resolve(missingTranslationHandlerTranslation); + } else { + deferred.reject(applyNotFoundIndicators(translationId)); + } + } + return deferred.promise; + }; + + var determineTranslationInstant = function (translationId, interpolateParams, interpolationId) { + + var result, table = $uses ? $translationTable[$uses] : $translationTable, + Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator; + + // if the translation id exists, we can just interpolate it + if (table && Object.prototype.hasOwnProperty.call(table, translationId)) { + var translation = table[translationId]; + + // If using link, rerun $translate with linked translationId and return it + if (translation.substr(0, 2) === '@:') { + result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId); + } else { + result = Interpolator.interpolate(translation, interpolateParams); + } + } else { + var missingTranslationHandlerTranslation; + // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise + if ($missingTranslationHandlerFactory && !pendingLoader) { + missingTranslationHandlerTranslation = translateByHandler(translationId); + } + + // since we couldn't translate the inital requested translation id, + // we try it now with one or more fallback languages, if fallback language(s) is + // configured. + if ($uses && $fallbackLanguage && $fallbackLanguage.length) { + fallbackIndex = 0; + result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator); + } else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) { + // looks like the requested translation id doesn't exists. + // Now, if there is a registered handler for missing translations and no + // asyncLoader is pending, we execute the handler + result = missingTranslationHandlerTranslation; + } else { + result = applyNotFoundIndicators(translationId); + } + } + + return result; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#preferredLanguage + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the language key for the preferred language. + * + * @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime) + * + * @return {string} preferred language key + */ + $translate.preferredLanguage = function (langKey) { + if (langKey) { + setupPreferredLanguage(langKey); + } + return $preferredLanguage; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#cloakClassName + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the configured class name for `translate-cloak` directive. + * + * @return {string} cloakClassName + */ + $translate.cloakClassName = function () { + return $cloakClassName; + }; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#proposedLanguage - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the language key of language that is currently loaded asynchronously. - * - * @return {string} language key - */ - $translate.proposedLanguage = function () { - return $nextLang; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#storage - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns registered storage. - * - * @return {object} Storage - */ - $translate.storage = function () { - return Storage; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#use - * @methodOf pascalprecht.translate.$translate - * - * @description - * Tells angular-translate which language to use by given language key. This method is - * used to change language at runtime. It also takes care of storing the language - * key in a configured store to let your app remember the choosed language. - * - * When trying to 'use' a language which isn't available it tries to load it - * asynchronously with registered loaders. - * - * Returns promise object with loaded language file data - * @example - * $translate.use("en_US").then(function(data){ + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#fallbackLanguage + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the language key for the fallback languages or sets a new fallback stack. + * + * @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime) + * + * @return {string||array} fallback language key + */ + $translate.fallbackLanguage = function (langKey) { + if (langKey !== undefined && langKey !== null) { + fallbackStack(langKey); + + // as we might have an async loader initiated and a new translation language might have been defined + // we need to add the promise to the stack also. So - iterate. + if ($loaderFactory) { + if ($fallbackLanguage && $fallbackLanguage.length) { + for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { + if (!langPromises[$fallbackLanguage[i]]) { + langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]); + } + } + } + } + $translate.use($translate.use()); + } + if ($fallbackWasString) { + return $fallbackLanguage[0]; + } else { + return $fallbackLanguage; + } + + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#useFallbackLanguage + * @methodOf pascalprecht.translate.$translate + * + * @description + * Sets the first key of the fallback language stack to be used for translation. + * Therefore all languages in the fallback array BEFORE this key will be skipped! + * + * @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to + * get back to the whole stack + */ + $translate.useFallbackLanguage = function (langKey) { + if (langKey !== undefined && langKey !== null) { + if (!langKey) { + startFallbackIteration = 0; + } else { + var langKeyPosition = indexOf($fallbackLanguage, langKey); + if (langKeyPosition > -1) { + startFallbackIteration = langKeyPosition; + } + } + + } + + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#proposedLanguage + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the language key of language that is currently loaded asynchronously. + * + * @return {string} language key + */ + $translate.proposedLanguage = function () { + return $nextLang; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#storage + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns registered storage. + * + * @return {object} Storage + */ + $translate.storage = function () { + return Storage; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#use + * @methodOf pascalprecht.translate.$translate + * + * @description + * Tells angular-translate which language to use by given language key. This method is + * used to change language at runtime. It also takes care of storing the language + * key in a configured store to let your app remember the choosed language. + * + * When trying to 'use' a language which isn't available it tries to load it + * asynchronously with registered loaders. + * + * Returns promise object with loaded language file data + * @example + * $translate.use("en_US").then(function(data){ * $scope.text = $translate("HELLO"); * }); - * - * @param {string} key Language key - * @return {string} Language key - */ - $translate.use = function (key) { - if (!key) { - return $uses; - } + * + * @param {string} key Language key + * @return {string} Language key + */ + $translate.use = function (key) { + if (!key) { + return $uses; + } - var deferred = $q.defer(); + var deferred = $q.defer(); - $rootScope.$emit('$translateChangeStart', {language: key}); + $rootScope.$emit('$translateChangeStart', {language: key}); - // Try to get the aliased language key - var aliasedKey = negotiateLocale(key); - if (aliasedKey) { - key = aliasedKey; - } + // Try to get the aliased language key + var aliasedKey = negotiateLocale(key); + if (aliasedKey) { + key = aliasedKey; + } - // if there isn't a translation table for the language we've requested, - // we load it asynchronously - if (!$translationTable[key] && $loaderFactory && !langPromises[key]) { - $nextLang = key; - langPromises[key] = loadAsync(key).then(function (translation) { - translations(translation.key, translation.table); - deferred.resolve(translation.key); - - useLanguage(translation.key); - if ($nextLang === key) { - $nextLang = undefined; - } - return translation; - }, function (key) { - if ($nextLang === key) { - $nextLang = undefined; - } - $rootScope.$emit('$translateChangeError', {language: key}); - deferred.reject(key); - $rootScope.$emit('$translateChangeEnd', {language: key}); - }); - } else { - deferred.resolve(key); - useLanguage(key); - } + // if there isn't a translation table for the language we've requested, + // we load it asynchronously + if (!$translationTable[key] && $loaderFactory && !langPromises[key]) { + $nextLang = key; + langPromises[key] = loadAsync(key).then(function (translation) { + translations(translation.key, translation.table); + deferred.resolve(translation.key); + + useLanguage(translation.key); + if ($nextLang === key) { + $nextLang = undefined; + } + return translation; + }, function (key) { + if ($nextLang === key) { + $nextLang = undefined; + } + $rootScope.$emit('$translateChangeError', {language: key}); + deferred.reject(key); + $rootScope.$emit('$translateChangeEnd', {language: key}); + }); + } else { + deferred.resolve(key); + useLanguage(key); + } - return deferred.promise; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#storageKey - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the key for the storage. - * - * @return {string} storage key - */ - $translate.storageKey = function () { - return storageKey(); - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#isPostCompilingEnabled - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns whether post compiling is enabled or not - * - * @return {bool} storage key - */ - $translate.isPostCompilingEnabled = function () { - return $postCompilingEnabled; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#refresh - * @methodOf pascalprecht.translate.$translate - * - * @description - * Refreshes a translation table pointed by the given langKey. If langKey is not specified, - * the module will drop all existent translation tables and load new version of those which - * are currently in use. - * - * Refresh means that the module will drop target translation table and try to load it again. - * - * In case there are no loaders registered the refresh() method will throw an Error. - * - * If the module is able to refresh translation tables refresh() method will broadcast - * $translateRefreshStart and $translateRefreshEnd events. - * - * @example - * // this will drop all currently existent translation tables and reload those which are - * // currently in use - * $translate.refresh(); - * // this will refresh a translation table for the en_US language - * $translate.refresh('en_US'); - * - * @param {string} langKey A language key of the table, which has to be refreshed - * - * @return {promise} Promise, which will be resolved in case a translation tables refreshing - * process is finished successfully, and reject if not. - */ - $translate.refresh = function (langKey) { - if (!$loaderFactory) { - throw new Error('Couldn\'t refresh translation table, no loader registered!'); - } + return deferred.promise; + }; - var deferred = $q.defer(); + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#storageKey + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the key for the storage. + * + * @return {string} storage key + */ + $translate.storageKey = function () { + return storageKey(); + }; - function resolve() { - deferred.resolve(); - $rootScope.$emit('$translateRefreshEnd', {language: langKey}); - } + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#isPostCompilingEnabled + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns whether post compiling is enabled or not + * + * @return {bool} storage key + */ + $translate.isPostCompilingEnabled = function () { + return $postCompilingEnabled; + }; - function reject() { - deferred.reject(); - $rootScope.$emit('$translateRefreshEnd', {language: langKey}); - } + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#refresh + * @methodOf pascalprecht.translate.$translate + * + * @description + * Refreshes a translation table pointed by the given langKey. If langKey is not specified, + * the module will drop all existent translation tables and load new version of those which + * are currently in use. + * + * Refresh means that the module will drop target translation table and try to load it again. + * + * In case there are no loaders registered the refresh() method will throw an Error. + * + * If the module is able to refresh translation tables refresh() method will broadcast + * $translateRefreshStart and $translateRefreshEnd events. + * + * @example + * // this will drop all currently existent translation tables and reload those which are + * // currently in use + * $translate.refresh(); + * // this will refresh a translation table for the en_US language + * $translate.refresh('en_US'); + * + * @param {string} langKey A language key of the table, which has to be refreshed + * + * @return {promise} Promise, which will be resolved in case a translation tables refreshing + * process is finished successfully, and reject if not. + */ + $translate.refresh = function (langKey) { + if (!$loaderFactory) { + throw new Error('Couldn\'t refresh translation table, no loader registered!'); + } - $rootScope.$emit('$translateRefreshStart', {language: langKey}); + var deferred = $q.defer(); - if (!langKey) { - // if there's no language key specified we refresh ALL THE THINGS! - var tables = [], loadingKeys = {}; + function resolve() { + deferred.resolve(); + $rootScope.$emit('$translateRefreshEnd', {language: langKey}); + } - // reload registered fallback languages - if ($fallbackLanguage && $fallbackLanguage.length) { - for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { - tables.push(loadAsync($fallbackLanguage[i])); - loadingKeys[$fallbackLanguage[i]] = true; - } - } - - // reload currently used language - if ($uses && !loadingKeys[$uses]) { - tables.push(loadAsync($uses)); - } - - $q.all(tables).then(function (tableData) { - angular.forEach(tableData, function (data) { - if ($translationTable[data.key]) { - delete $translationTable[data.key]; - } - translations(data.key, data.table); - }); - if ($uses) { - useLanguage($uses); - } - resolve(); - }); + function reject() { + deferred.reject(); + $rootScope.$emit('$translateRefreshEnd', {language: langKey}); + } - } else if ($translationTable[langKey]) { + $rootScope.$emit('$translateRefreshStart', {language: langKey}); + + if (!langKey) { + // if there's no language key specified we refresh ALL THE THINGS! + var tables = [], loadingKeys = {}; + + // reload registered fallback languages + if ($fallbackLanguage && $fallbackLanguage.length) { + for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { + tables.push(loadAsync($fallbackLanguage[i])); + loadingKeys[$fallbackLanguage[i]] = true; + } + } + + // reload currently used language + if ($uses && !loadingKeys[$uses]) { + tables.push(loadAsync($uses)); + } + + $q.all(tables).then(function (tableData) { + angular.forEach(tableData, function (data) { + if ($translationTable[data.key]) { + delete $translationTable[data.key]; + } + translations(data.key, data.table); + }); + if ($uses) { + useLanguage($uses); + } + resolve(); + }); + + } else if ($translationTable[langKey]) { + + loadAsync(langKey).then(function (data) { + translations(data.key, data.table); + if (langKey === $uses) { + useLanguage($uses); + } + resolve(); + }, reject); + + } else { + reject(); + } + return deferred.promise; + }; - loadAsync(langKey).then(function (data) { - translations(data.key, data.table); - if (langKey === $uses) { - useLanguage($uses); - } - resolve(); - }, reject); + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#instant + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns a translation instantly from the internal state of loaded translation. All rules + * regarding the current language, the preferred language of even fallback languages will be + * used except any promise handling. If a language was not found, an asynchronous loading + * will be invoked in the background. + * + * @param {string|array} translationId A token which represents a translation id + * This can be optionally an array of translation ids which + * results that the function's promise returns an object where + * each key is the translation id and the value the translation. + * @param {object} interpolateParams Params + * @param {string} interpolationId The id of the interpolation to use + * + * @return {string} translation + */ + $translate.instant = function (translationId, interpolateParams, interpolationId) { + + // Detect undefined and null values to shorten the execution and prevent exceptions + if (translationId === null || angular.isUndefined(translationId)) { + return translationId; + } - } else { - reject(); - } - return deferred.promise; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#instant - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns a translation instantly from the internal state of loaded translation. All rules - * regarding the current language, the preferred language of even fallback languages will be - * used except any promise handling. If a language was not found, an asynchronous loading - * will be invoked in the background. - * - * @param {string|array} translationId A token which represents a translation id - * This can be optionally an array of translation ids which - * results that the function's promise returns an object where - * each key is the translation id and the value the translation. - * @param {object} interpolateParams Params - * @param {string} interpolationId The id of the interpolation to use - * - * @return {string} translation - */ - $translate.instant = function (translationId, interpolateParams, interpolationId) { - - // Detect undefined and null values to shorten the execution and prevent exceptions - if (translationId === null || angular.isUndefined(translationId)) { - return translationId; - } + // Duck detection: If the first argument is an array, a bunch of translations was requested. + // The result is an object. + if (angular.isArray(translationId)) { + var results = {}; + for (var i = 0, c = translationId.length; i < c; i++) { + results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId); + } + return results; + } - // Duck detection: If the first argument is an array, a bunch of translations was requested. - // The result is an object. - if (angular.isArray(translationId)) { - var results = {}; - for (var i = 0, c = translationId.length; i < c; i++) { - results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId); - } - return results; - } + // We discarded unacceptable values. So we just need to verify if translationId is empty String + if (angular.isString(translationId) && translationId.length < 1) { + return translationId; + } - // We discarded unacceptable values. So we just need to verify if translationId is empty String - if (angular.isString(translationId) && translationId.length < 1) { - return translationId; - } + // trim off any whitespace + if (translationId) { + translationId = trim.apply(translationId); + } - // trim off any whitespace - if (translationId) { - translationId = trim.apply(translationId); - } + var result, possibleLangKeys = []; + if ($preferredLanguage) { + possibleLangKeys.push($preferredLanguage); + } + if ($uses) { + possibleLangKeys.push($uses); + } + if ($fallbackLanguage && $fallbackLanguage.length) { + possibleLangKeys = possibleLangKeys.concat($fallbackLanguage); + } + for (var j = 0, d = possibleLangKeys.length; j < d; j++) { + var possibleLangKey = possibleLangKeys[j]; + if ($translationTable[possibleLangKey]) { + if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') { + result = determineTranslationInstant(translationId, interpolateParams, interpolationId); + } + } + if (typeof result !== 'undefined') { + break; + } + } - var result, possibleLangKeys = []; - if ($preferredLanguage) { - possibleLangKeys.push($preferredLanguage); - } - if ($uses) { - possibleLangKeys.push($uses); - } - if ($fallbackLanguage && $fallbackLanguage.length) { - possibleLangKeys = possibleLangKeys.concat($fallbackLanguage); - } - for (var j = 0, d = possibleLangKeys.length; j < d; j++) { - var possibleLangKey = possibleLangKeys[j]; - if ($translationTable[possibleLangKey]) { - if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') { - result = determineTranslationInstant(translationId, interpolateParams, interpolationId); - } - } - if (typeof result !== 'undefined') { - break; - } - } + if (!result && result !== '') { + // Return translation of default interpolator if not found anything. + result = defaultInterpolator.interpolate(translationId, interpolateParams); + if ($missingTranslationHandlerFactory && !pendingLoader) { + result = translateByHandler(translationId); + } + } - if (!result && result !== '') { - // Return translation of default interpolator if not found anything. - result = defaultInterpolator.interpolate(translationId, interpolateParams); - if ($missingTranslationHandlerFactory && !pendingLoader) { - result = translateByHandler(translationId); - } - } + return result; + }; - return result; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#versionInfo - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the current version information for the angular-translate library - * - * @return {string} angular-translate version - */ - $translate.versionInfo = function () { - return version; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translate#loaderCache - * @methodOf pascalprecht.translate.$translate - * - * @description - * Returns the defined loaderCache. - * - * @return {boolean|string|object} current value of loaderCache - */ - $translate.loaderCache = function () { - return loaderCache; - }; - - if ($loaderFactory) { - - // If at least one async loader is defined and there are no - // (default) translations available we should try to load them. - if (angular.equals($translationTable, {})) { - $translate.use($translate.use()); - } + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#versionInfo + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the current version information for the angular-translate library + * + * @return {string} angular-translate version + */ + $translate.versionInfo = function () { + return version; + }; - // Also, if there are any fallback language registered, we start - // loading them asynchronously as soon as we can. - if ($fallbackLanguage && $fallbackLanguage.length) { - var processAsyncResult = function (translation) { - translations(translation.key, translation.table); - $rootScope.$emit('$translateChangeEnd', { language: translation.key }); - return translation; - }; - for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { - langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]).then(processAsyncResult); - } - } - } + /** + * @ngdoc function + * @name pascalprecht.translate.$translate#loaderCache + * @methodOf pascalprecht.translate.$translate + * + * @description + * Returns the defined loaderCache. + * + * @return {boolean|string|object} current value of loaderCache + */ + $translate.loaderCache = function () { + return loaderCache; + }; + + if ($loaderFactory) { + + // If at least one async loader is defined and there are no + // (default) translations available we should try to load them. + if (angular.equals($translationTable, {})) { + $translate.use($translate.use()); + } - return $translate; - } - ]; + // Also, if there are any fallback language registered, we start + // loading them asynchronously as soon as we can. + if ($fallbackLanguage && $fallbackLanguage.length) { + var processAsyncResult = function (translation) { + translations(translation.key, translation.table); + $rootScope.$emit('$translateChangeEnd', {language: translation.key}); + return translation; + }; + for (var i = 0, len = $fallbackLanguage.length; i < len; i++) { + langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]).then(processAsyncResult); + } + } + } + + return $translate; + } + ]; }]); /** @@ -1811,85 +1811,85 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', */ angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', ['$interpolate', function ($interpolate) { - var $translateInterpolator = {}, - $locale, - $identifier = 'default', - $sanitizeValueStrategy = null, - // map of all sanitize strategies - sanitizeValueStrategies = { - escaped: function (params) { - var result = {}; - for (var key in params) { - if (Object.prototype.hasOwnProperty.call(params, key)) { - result[key] = angular.element('
          ').text(params[key]).html(); + var $translateInterpolator = {}, + $locale, + $identifier = 'default', + $sanitizeValueStrategy = null, + // map of all sanitize strategies + sanitizeValueStrategies = { + escaped: function (params) { + var result = {}; + for (var key in params) { + if (Object.prototype.hasOwnProperty.call(params, key)) { + result[key] = angular.element('
          ').text(params[key]).html(); + } + } + return result; } - } - return result; + }; + + var sanitizeParams = function (params) { + var result; + if (angular.isFunction(sanitizeValueStrategies[$sanitizeValueStrategy])) { + result = sanitizeValueStrategies[$sanitizeValueStrategy](params); + } else { + result = params; } - }; - - var sanitizeParams = function (params) { - var result; - if (angular.isFunction(sanitizeValueStrategies[$sanitizeValueStrategy])) { - result = sanitizeValueStrategies[$sanitizeValueStrategy](params); - } else { - result = params; - } - return result; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale - * @methodOf pascalprecht.translate.$translateDefaultInterpolation - * - * @description - * Sets current locale (this is currently not use in this interpolation). - * - * @param {string} locale Language key or locale. - */ - $translateInterpolator.setLocale = function (locale) { - $locale = locale; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier - * @methodOf pascalprecht.translate.$translateDefaultInterpolation - * - * @description - * Returns an identifier for this interpolation service. - * - * @returns {string} $identifier - */ - $translateInterpolator.getInterpolationIdentifier = function () { - return $identifier; - }; - - $translateInterpolator.useSanitizeValueStrategy = function (value) { - $sanitizeValueStrategy = value; - return this; - }; - - /** - * @ngdoc function - * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate - * @methodOf pascalprecht.translate.$translateDefaultInterpolation - * - * @description - * Interpolates given string agains given interpolate params using angulars - * `$interpolate` service. - * - * @returns {string} interpolated string. - */ - $translateInterpolator.interpolate = function (string, interpolateParams) { - if ($sanitizeValueStrategy) { - interpolateParams = sanitizeParams(interpolateParams); - } - return $interpolate(string)(interpolateParams || {}); - }; - - return $translateInterpolator; + return result; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateDefaultInterpolation#setLocale + * @methodOf pascalprecht.translate.$translateDefaultInterpolation + * + * @description + * Sets current locale (this is currently not use in this interpolation). + * + * @param {string} locale Language key or locale. + */ + $translateInterpolator.setLocale = function (locale) { + $locale = locale; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier + * @methodOf pascalprecht.translate.$translateDefaultInterpolation + * + * @description + * Returns an identifier for this interpolation service. + * + * @returns {string} $identifier + */ + $translateInterpolator.getInterpolationIdentifier = function () { + return $identifier; + }; + + $translateInterpolator.useSanitizeValueStrategy = function (value) { + $sanitizeValueStrategy = value; + return this; + }; + + /** + * @ngdoc function + * @name pascalprecht.translate.$translateDefaultInterpolation#interpolate + * @methodOf pascalprecht.translate.$translateDefaultInterpolation + * + * @description + * Interpolates given string agains given interpolate params using angulars + * `$interpolate` service. + * + * @returns {string} interpolated string. + */ + $translateInterpolator.interpolate = function (string, interpolateParams) { + if ($sanitizeValueStrategy) { + interpolateParams = sanitizeParams(interpolateParams); + } + return $interpolate(string)(interpolateParams || {}); + }; + + return $translateInterpolator; }]); angular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY'); @@ -1915,27 +1915,27 @@ angular.module('pascalprecht.translate') * @param {boolean=} translate-compile (default true if present) defines locally activation of {@link pascalprecht.translate.$translate#usePostCompiling} * * @example - - -
          - -
          
          -        
          TRANSLATION_ID
          -
          
          -        
          
          -        
          {{translationId}}
          -
          
          -        
          WITH_VALUES
          -
          
          -        
          WITH_VALUES
          -
          
          -
          -      
          -
          - - angular.module('ngView', ['pascalprecht.translate']) - - .config(function ($translateProvider) { + + +
          + +
          
          + 
          TRANSLATION_ID
          +
          
          + 
          
          + 
          {{translationId}}
          +
          
          + 
          WITH_VALUES
          +
          
          + 
          WITH_VALUES
          +
          
          +
          + 
          +
          + + angular.module('ngView', ['pascalprecht.translate']) + + .config(function ($translateProvider) { $translateProvider.translations('en',{ 'TRANSLATION_ID': 'Hello there!', @@ -1944,16 +1944,16 @@ angular.module('pascalprecht.translate') }); - angular.module('ngView').controller('TranslateCtrl', function ($scope) { + angular.module('ngView').controller('TranslateCtrl', function ($scope) { $scope.translationId = 'TRANSLATION_ID'; $scope.values = { value: 78 }; }); - - - it('should translate', function () { + + + it('should translate', function () { inject(function ($rootScope, $compile) { $rootScope.translationId = 'TRANSLATION_ID'; @@ -1978,165 +1978,165 @@ angular.module('pascalprecht.translate') expect(element.attr('title')).toBe('Hello there!'); }); }); - -
          +
          +
          */ -.directive('translate', ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope', function ($translate, $q, $interpolate, $compile, $parse, $rootScope) { - - return { - restrict: 'AE', - scope: true, - compile: function (tElement, tAttr) { - - var translateValuesExist = (tAttr.translateValues) ? - tAttr.translateValues : undefined; - - var translateInterpolation = (tAttr.translateInterpolation) ? - tAttr.translateInterpolation : undefined; - - var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i); - - var interpolateRegExp = "^(.*)(" + $interpolate.startSymbol() + ".*" + $interpolate.endSymbol() + ")(.*)", - watcherRegExp = "^(.*)" + $interpolate.startSymbol() + "(.*)" + $interpolate.endSymbol() + "(.*)"; - - return function linkFn(scope, iElement, iAttr) { - - scope.interpolateParams = {}; - scope.preText = ""; - scope.postText = ""; - var translationIds = {}; - - // Ensures any change of the attribute "translate" containing the id will - // be re-stored to the scope's "translationId". - // If the attribute has no content, the element's text value (white spaces trimmed off) will be used. - var observeElementTranslation = function (translationId) { - if (angular.equals(translationId , '') || !angular.isDefined(translationId)) { - // Resolve translation id by inner html if required - var interpolateMatches = iElement.text().match(interpolateRegExp); - // Interpolate translation id if required - if (angular.isArray(interpolateMatches)) { - scope.preText = interpolateMatches[1]; - scope.postText = interpolateMatches[3]; - translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent); - watcherMatches = iElement.text().match(watcherRegExp); - if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) { - scope.$watch(watcherMatches[2], function (newValue) { - translationIds.translate = newValue; - updateTranslations(); - }); - } - } else { - translationIds.translate = iElement.text().replace(/^\s+|\s+$/g,''); + .directive('translate', ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope', function ($translate, $q, $interpolate, $compile, $parse, $rootScope) { + + return { + restrict: 'AE', + scope: true, + compile: function (tElement, tAttr) { + + var translateValuesExist = (tAttr.translateValues) ? + tAttr.translateValues : undefined; + + var translateInterpolation = (tAttr.translateInterpolation) ? + tAttr.translateInterpolation : undefined; + + var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i); + + var interpolateRegExp = "^(.*)(" + $interpolate.startSymbol() + ".*" + $interpolate.endSymbol() + ")(.*)", + watcherRegExp = "^(.*)" + $interpolate.startSymbol() + "(.*)" + $interpolate.endSymbol() + "(.*)"; + + return function linkFn(scope, iElement, iAttr) { + + scope.interpolateParams = {}; + scope.preText = ""; + scope.postText = ""; + var translationIds = {}; + + // Ensures any change of the attribute "translate" containing the id will + // be re-stored to the scope's "translationId". + // If the attribute has no content, the element's text value (white spaces trimmed off) will be used. + var observeElementTranslation = function (translationId) { + if (angular.equals(translationId, '') || !angular.isDefined(translationId)) { + // Resolve translation id by inner html if required + var interpolateMatches = iElement.text().match(interpolateRegExp); + // Interpolate translation id if required + if (angular.isArray(interpolateMatches)) { + scope.preText = interpolateMatches[1]; + scope.postText = interpolateMatches[3]; + translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent); + watcherMatches = iElement.text().match(watcherRegExp); + if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) { + scope.$watch(watcherMatches[2], function (newValue) { + translationIds.translate = newValue; + updateTranslations(); + }); + } + } else { + translationIds.translate = iElement.text().replace(/^\s+|\s+$/g, ''); + } + } else { + translationIds.translate = translationId; + } + updateTranslations(); + }; + + var observeAttributeTranslation = function (translateAttr) { + iAttr.$observe(translateAttr, function (translationId) { + translationIds[translateAttr] = translationId; + updateTranslations(); + }); + }; + + iAttr.$observe('translate', function (translationId) { + observeElementTranslation(translationId); + }); + + for (var translateAttr in iAttr) { + if (iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') { + observeAttributeTranslation(translateAttr); + } + } + + iAttr.$observe('translateDefault', function (value) { + scope.defaultText = value; + }); + + if (translateValuesExist) { + iAttr.$observe('translateValues', function (interpolateParams) { + if (interpolateParams) { + scope.$parent.$watch(function () { + angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent)); + }); + } + }); + } + + if (translateValueExist) { + var observeValueAttribute = function (attrName) { + iAttr.$observe(attrName, function (value) { + var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15); + scope.interpolateParams[attributeName] = value; + }); + }; + for (var attr in iAttr) { + if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') { + observeValueAttribute(attr); + } + } + } + + // Master update function + var updateTranslations = function () { + for (var key in translationIds) { + if (translationIds.hasOwnProperty(key) && translationIds[key]) { + updateTranslation(key, translationIds[key], scope, scope.interpolateParams); + } + } + }; + + // Put translation processing function outside loop + var updateTranslation = function (translateAttr, translationId, scope, interpolateParams) { + $translate(translationId, interpolateParams, translateInterpolation) + .then(function (translation) { + applyTranslation(translation, scope, true, translateAttr); + }, function (translationId) { + applyTranslation(translationId, scope, false, translateAttr); + }); + }; + + var applyTranslation = function (value, scope, successful, translateAttr) { + if (translateAttr === 'translate') { + // default translate into innerHTML + if (!successful && typeof scope.defaultText !== 'undefined') { + value = scope.defaultText; + } + iElement.html(scope.preText + value + scope.postText); + var globallyEnabled = $translate.isPostCompilingEnabled(); + var locallyDefined = typeof tAttr.translateCompile !== 'undefined'; + var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false'; + if ((globallyEnabled && !locallyDefined) || locallyEnabled) { + $compile(iElement.contents())(scope); + } + } else { + // translate attribute + if (!successful && typeof scope.defaultText !== 'undefined') { + value = scope.defaultText; + } + var attributeName = iAttr.$attr[translateAttr].substr(15); + iElement.attr(attributeName, value); + } + }; + + scope.$watch('interpolateParams', updateTranslations, true); + + // Ensures the text will be refreshed after the current language was changed + // w/ $translate.use(...) + var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations); + + // ensure translation will be looked up at least one + if (iElement.text().length) { + observeElementTranslation(''); + } + updateTranslations(); + scope.$on('$destroy', unbind); + }; } - } else { - translationIds.translate = translationId; - } - updateTranslations(); - }; - - var observeAttributeTranslation = function (translateAttr) { - iAttr.$observe(translateAttr, function (translationId) { - translationIds[translateAttr] = translationId; - updateTranslations(); - }); }; - - iAttr.$observe('translate', function (translationId) { - observeElementTranslation(translationId); - }); - - for (var translateAttr in iAttr) { - if(iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') { - observeAttributeTranslation(translateAttr); - } - } - - iAttr.$observe('translateDefault', function (value) { - scope.defaultText = value; - }); - - if (translateValuesExist) { - iAttr.$observe('translateValues', function (interpolateParams) { - if (interpolateParams) { - scope.$parent.$watch(function () { - angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent)); - }); - } - }); - } - - if (translateValueExist) { - var observeValueAttribute = function (attrName) { - iAttr.$observe(attrName, function (value) { - var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15); - scope.interpolateParams[attributeName] = value; - }); - }; - for (var attr in iAttr) { - if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') { - observeValueAttribute(attr); - } - } - } - - // Master update function - var updateTranslations = function () { - for (var key in translationIds) { - if (translationIds.hasOwnProperty(key) && translationIds[key]) { - updateTranslation(key, translationIds[key], scope, scope.interpolateParams); - } - } - }; - - // Put translation processing function outside loop - var updateTranslation = function(translateAttr, translationId, scope, interpolateParams) { - $translate(translationId, interpolateParams, translateInterpolation) - .then(function (translation) { - applyTranslation(translation, scope, true, translateAttr); - }, function (translationId) { - applyTranslation(translationId, scope, false, translateAttr); - }); - }; - - var applyTranslation = function (value, scope, successful, translateAttr) { - if (translateAttr === 'translate') { - // default translate into innerHTML - if (!successful && typeof scope.defaultText !== 'undefined') { - value = scope.defaultText; - } - iElement.html(scope.preText + value + scope.postText); - var globallyEnabled = $translate.isPostCompilingEnabled(); - var locallyDefined = typeof tAttr.translateCompile !== 'undefined'; - var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false'; - if ((globallyEnabled && !locallyDefined) || locallyEnabled) { - $compile(iElement.contents())(scope); - } - } else { - // translate attribute - if (!successful && typeof scope.defaultText !== 'undefined') { - value = scope.defaultText; - } - var attributeName = iAttr.$attr[translateAttr].substr(15); - iElement.attr(attributeName, value); - } - }; - - scope.$watch('interpolateParams', updateTranslations, true); - - // Ensures the text will be refreshed after the current language was changed - // w/ $translate.use(...) - var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations); - - // ensure translation will be looked up at least one - if (iElement.text().length) { - observeElementTranslation(''); - } - updateTranslations(); - scope.$on('$destroy', unbind); - }; - } - }; -}]); + }]); angular.module('pascalprecht.translate') /** @@ -2160,34 +2160,34 @@ angular.module('pascalprecht.translate') * or hiding the cloak. Basically it relies on the translation * resolve. */ -.directive('translateCloak', ['$rootScope', '$translate', function ($rootScope, $translate) { - - return { - compile: function (tElement) { - var applyCloak = function () { - tElement.addClass($translate.cloakClassName()); - }, - removeCloak = function () { - tElement.removeClass($translate.cloakClassName()); - }, - removeListener = $rootScope.$on('$translateChangeEnd', function () { - removeCloak(); - removeListener(); - removeListener = null; - }); - applyCloak(); - - return function linkFn(scope, iElement, iAttr) { - // Register a watcher for the defined translation allowing a fine tuned cloak - if (iAttr.translateCloak && iAttr.translateCloak.length) { - iAttr.$observe('translateCloak', function (translationId) { - $translate(translationId).then(removeCloak, applyCloak); - }); - } - }; - } - }; -}]); + .directive('translateCloak', ['$rootScope', '$translate', function ($rootScope, $translate) { + + return { + compile: function (tElement) { + var applyCloak = function () { + tElement.addClass($translate.cloakClassName()); + }, + removeCloak = function () { + tElement.removeClass($translate.cloakClassName()); + }, + removeListener = $rootScope.$on('$translateChangeEnd', function () { + removeCloak(); + removeListener(); + removeListener = null; + }); + applyCloak(); + + return function linkFn(scope, iElement, iAttr) { + // Register a watcher for the defined translation allowing a fine tuned cloak + if (iAttr.translateCloak && iAttr.translateCloak.length) { + iAttr.$observe('translateCloak', function (translationId) { + $translate(translationId).then(removeCloak, applyCloak); + }); + } + }; + } + }; + }]); angular.module('pascalprecht.translate') /** @@ -2207,21 +2207,21 @@ angular.module('pascalprecht.translate') * @returns {string} Translated text. * * @example - - -
          + + +
          -
          {{ 'TRANSLATION_ID' | translate }}
          -
          {{ translationId | translate }}
          -
          {{ 'WITH_VALUES' | translate:'{value: 5}' }}
          -
          {{ 'WITH_VALUES' | translate:values }}
          +
          {{ 'TRANSLATION_ID' | translate }}
          +
          {{ translationId | translate }}
          +
          {{ 'WITH_VALUES' | translate:'{value: 5}' }}
          +
          {{ 'WITH_VALUES' | translate:values }}
          -
          -
          - - angular.module('ngView', ['pascalprecht.translate']) +
          +
          + + angular.module('ngView', ['pascalprecht.translate']) - .config(function ($translateProvider) { + .config(function ($translateProvider) { $translateProvider.translations('en', { 'TRANSLATION_ID': 'Hello there!', @@ -2231,29 +2231,29 @@ angular.module('pascalprecht.translate') }); - angular.module('ngView').controller('TranslateCtrl', function ($scope) { + angular.module('ngView').controller('TranslateCtrl', function ($scope) { $scope.translationId = 'TRANSLATION_ID'; $scope.values = { value: 78 }; }); - -
          + + */ -.filter('translate', ['$parse', '$translate', function ($parse, $translate) { - var translateFilter = function (translationId, interpolateParams, interpolation) { + .filter('translate', ['$parse', '$translate', function ($parse, $translate) { + var translateFilter = function (translationId, interpolateParams, interpolation) { - if (!angular.isObject(interpolateParams)) { - interpolateParams = $parse(interpolateParams)(this); - } + if (!angular.isObject(interpolateParams)) { + interpolateParams = $parse(interpolateParams)(this); + } - return $translate.instant(translationId, interpolateParams, interpolation); - }; + return $translate.instant(translationId, interpolateParams, interpolation); + }; - // Since AngularJS 1.3, filters which are not stateless (depending at the scope) - // have to explicit define this behavior. - translateFilter.$stateful = true; + // Since AngularJS 1.3, filters which are not stateless (depending at the scope) + // have to explicit define this behavior. + translateFilter.$stateful = true; - return translateFilter; -}]); \ No newline at end of file + return translateFilter; + }]); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-ui-router.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-ui-router.js index d2636f8e..830aac7e 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular-ui-router.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular-ui-router.js @@ -6,1434 +6,1491 @@ */ /* commonjs package manager support (eg componentjs) */ -if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ - module.exports = 'ui.router'; +if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports) { + module.exports = 'ui.router'; } (function (window, angular, undefined) { -/*jshint globalstrict:true*/ -/*global angular:false*/ -'use strict'; - -var isDefined = angular.isDefined, - isFunction = angular.isFunction, - isString = angular.isString, - isObject = angular.isObject, - isArray = angular.isArray, - forEach = angular.forEach, - extend = angular.extend, - copy = angular.copy; - -function inherit(parent, extra) { - return extend(new (extend(function() {}, { prototype: parent }))(), extra); -} + /*jshint globalstrict:true*/ + /*global angular:false*/ + 'use strict'; + + var isDefined = angular.isDefined, + isFunction = angular.isFunction, + isString = angular.isString, + isObject = angular.isObject, + isArray = angular.isArray, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy; + + function inherit(parent, extra) { + return extend(new (extend(function () { + }, {prototype: parent}))(), extra); + } -function merge(dst) { - forEach(arguments, function(obj) { - if (obj !== dst) { - forEach(obj, function(value, key) { - if (!dst.hasOwnProperty(key)) dst[key] = value; - }); + function merge(dst) { + forEach(arguments, function (obj) { + if (obj !== dst) { + forEach(obj, function (value, key) { + if (!dst.hasOwnProperty(key)) dst[key] = value; + }); + } + }); + return dst; } - }); - return dst; -} -/** - * Finds the common ancestor path between two states. - * - * @param {Object} first The first state. - * @param {Object} second The second state. - * @return {Array} Returns an array of state names in descending order, not including the root. - */ -function ancestors(first, second) { - var path = []; - - for (var n in first.path) { - if (first.path[n] !== second.path[n]) break; - path.push(first.path[n]); - } - return path; -} + /** + * Finds the common ancestor path between two states. + * + * @param {Object} first The first state. + * @param {Object} second The second state. + * @return {Array} Returns an array of state names in descending order, not including the root. + */ + function ancestors(first, second) { + var path = []; -/** - * IE8-safe wrapper for `Object.keys()`. - * - * @param {Object} object A JavaScript object. - * @return {Array} Returns the keys of the object as an array. - */ -function objectKeys(object) { - if (Object.keys) { - return Object.keys(object); - } - var result = []; - - angular.forEach(object, function(val, key) { - result.push(key); - }); - return result; -} + for (var n in first.path) { + if (first.path[n] !== second.path[n]) break; + path.push(first.path[n]); + } + return path; + } -/** - * IE8-safe wrapper for `Array.prototype.indexOf()`. - * - * @param {Array} array A JavaScript array. - * @param {*} value A value to search the array for. - * @return {Number} Returns the array index value of `value`, or `-1` if not present. - */ -function indexOf(array, value) { - if (Array.prototype.indexOf) { - return array.indexOf(value, Number(arguments[2]) || 0); - } - var len = array.length >>> 0, from = Number(arguments[2]) || 0; - from = (from < 0) ? Math.ceil(from) : Math.floor(from); - - if (from < 0) from += len; - - for (; from < len; from++) { - if (from in array && array[from] === value) return from; - } - return -1; -} + /** + * IE8-safe wrapper for `Object.keys()`. + * + * @param {Object} object A JavaScript object. + * @return {Array} Returns the keys of the object as an array. + */ + function objectKeys(object) { + if (Object.keys) { + return Object.keys(object); + } + var result = []; -/** - * Merges a set of parameters with all parameters inherited between the common parents of the - * current state and a given destination state. - * - * @param {Object} currentParams The value of the current state parameters ($stateParams). - * @param {Object} newParams The set of parameters which will be composited with inherited params. - * @param {Object} $current Internal definition of object representing the current state. - * @param {Object} $to Internal definition of object representing state to transition to. - */ -function inheritParams(currentParams, newParams, $current, $to) { - var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; - - for (var i in parents) { - if (!parents[i].params) continue; - parentParams = objectKeys(parents[i].params); - if (!parentParams.length) continue; - - for (var j in parentParams) { - if (indexOf(inheritList, parentParams[j]) >= 0) continue; - inheritList.push(parentParams[j]); - inherited[parentParams[j]] = currentParams[parentParams[j]]; + angular.forEach(object, function (val, key) { + result.push(key); + }); + return result; } - } - return extend({}, inherited, newParams); -} -/** - * Performs a non-strict comparison of the subset of two objects, defined by a list of keys. - * - * @param {Object} a The first object. - * @param {Object} b The second object. - * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, - * it defaults to the list of keys in `a`. - * @return {Boolean} Returns `true` if the keys match, otherwise `false`. - */ -function equalForKeys(a, b, keys) { - if (!keys) { - keys = []; - for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility - } - - for (var i=0; i>> 0, from = Number(arguments[2]) || 0; + from = (from < 0) ? Math.ceil(from) : Math.floor(from); -/** - * Returns the subset of an object, based on a list of keys. - * - * @param {Array} keys - * @param {Object} values - * @return {Boolean} Returns a subset of `values`. - */ -function filterByKeys(keys, values) { - var filtered = {}; + if (from < 0) from += len; - forEach(keys, function (name) { - filtered[name] = values[name]; - }); - return filtered; -} + for (; from < len; from++) { + if (from in array && array[from] === value) return from; + } + return -1; + } + + /** + * Merges a set of parameters with all parameters inherited between the common parents of the + * current state and a given destination state. + * + * @param {Object} currentParams The value of the current state parameters ($stateParams). + * @param {Object} newParams The set of parameters which will be composited with inherited params. + * @param {Object} $current Internal definition of object representing the current state. + * @param {Object} $to Internal definition of object representing state to transition to. + */ + function inheritParams(currentParams, newParams, $current, $to) { + var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; + + for (var i in parents) { + if (!parents[i].params) continue; + parentParams = objectKeys(parents[i].params); + if (!parentParams.length) continue; + + for (var j in parentParams) { + if (indexOf(inheritList, parentParams[j]) >= 0) continue; + inheritList.push(parentParams[j]); + inherited[parentParams[j]] = currentParams[parentParams[j]]; + } + } + return extend({}, inherited, newParams); + } + + /** + * Performs a non-strict comparison of the subset of two objects, defined by a list of keys. + * + * @param {Object} a The first object. + * @param {Object} b The second object. + * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, + * it defaults to the list of keys in `a`. + * @return {Boolean} Returns `true` if the keys match, otherwise `false`. + */ + function equalForKeys(a, b, keys) { + if (!keys) { + keys = []; + for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility + } + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized + } + return true; + } + + /** + * Returns the subset of an object, based on a list of keys. + * + * @param {Array} keys + * @param {Object} values + * @return {Boolean} Returns a subset of `values`. + */ + function filterByKeys(keys, values) { + var filtered = {}; + + forEach(keys, function (name) { + filtered[name] = values[name]; + }); + return filtered; + } // like _.indexBy // when you know that your index values will be unique, or you want last-one-in to win -function indexBy(array, propName) { - var result = {}; - forEach(array, function(item) { - result[item[propName]] = item; - }); - return result; -} + function indexBy(array, propName) { + var result = {}; + forEach(array, function (item) { + result[item[propName]] = item; + }); + return result; + } // extracted from underscore.js // Return a copy of the object only containing the whitelisted properties. -function pick(obj) { - var copy = {}; - var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); - forEach(keys, function(key) { - if (key in obj) copy[key] = obj[key]; - }); - return copy; -} + function pick(obj) { + var copy = {}; + var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); + forEach(keys, function (key) { + if (key in obj) copy[key] = obj[key]; + }); + return copy; + } // extracted from underscore.js // Return a copy of the object omitting the blacklisted properties. -function omit(obj) { - var copy = {}; - var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); - for (var key in obj) { - if (indexOf(keys, key) == -1) copy[key] = obj[key]; - } - return copy; -} + function omit(obj) { + var copy = {}; + var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); + for (var key in obj) { + if (indexOf(keys, key) == -1) copy[key] = obj[key]; + } + return copy; + } -function pluck(collection, key) { - var result = isArray(collection) ? [] : {}; + function pluck(collection, key) { + var result = isArray(collection) ? [] : {}; - forEach(collection, function(val, i) { - result[i] = isFunction(key) ? key(val) : val[key]; - }); - return result; -} + forEach(collection, function (val, i) { + result[i] = isFunction(key) ? key(val) : val[key]; + }); + return result; + } -function filter(collection, callback) { - var array = isArray(collection); - var result = array ? [] : {}; - forEach(collection, function(val, i) { - if (callback(val, i)) { - result[array ? result.length : i] = val; + function filter(collection, callback) { + var array = isArray(collection); + var result = array ? [] : {}; + forEach(collection, function (val, i) { + if (callback(val, i)) { + result[array ? result.length : i] = val; + } + }); + return result; } - }); - return result; -} -function map(collection, callback) { - var result = isArray(collection) ? [] : {}; + function map(collection, callback) { + var result = isArray(collection) ? [] : {}; - forEach(collection, function(val, i) { - result[i] = callback(val, i); - }); - return result; -} + forEach(collection, function (val, i) { + result[i] = callback(val, i); + }); + return result; + } -/** - * @ngdoc overview - * @name ui.router.util - * - * @description - * # ui.router.util sub-module - * - * This module is a dependency of other sub-modules. Do not include this module as a dependency - * in your angular app (use {@link ui.router} module instead). - * - */ -angular.module('ui.router.util', ['ng']); + /** + * @ngdoc overview + * @name ui.router.util + * + * @description + * # ui.router.util sub-module + * + * This module is a dependency of other sub-modules. Do not include this module as a dependency + * in your angular app (use {@link ui.router} module instead). + * + */ + angular.module('ui.router.util', ['ng']); -/** - * @ngdoc overview - * @name ui.router.router - * - * @requires ui.router.util - * - * @description - * # ui.router.router sub-module - * - * This module is a dependency of other sub-modules. Do not include this module as a dependency - * in your angular app (use {@link ui.router} module instead). - */ -angular.module('ui.router.router', ['ui.router.util']); + /** + * @ngdoc overview + * @name ui.router.router + * + * @requires ui.router.util + * + * @description + * # ui.router.router sub-module + * + * This module is a dependency of other sub-modules. Do not include this module as a dependency + * in your angular app (use {@link ui.router} module instead). + */ + angular.module('ui.router.router', ['ui.router.util']); -/** - * @ngdoc overview - * @name ui.router.state - * - * @requires ui.router.router - * @requires ui.router.util - * - * @description - * # ui.router.state sub-module - * - * This module is a dependency of the main ui.router module. Do not include this module as a dependency - * in your angular app (use {@link ui.router} module instead). - * - */ -angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']); + /** + * @ngdoc overview + * @name ui.router.state + * + * @requires ui.router.router + * @requires ui.router.util + * + * @description + * # ui.router.state sub-module + * + * This module is a dependency of the main ui.router module. Do not include this module as a dependency + * in your angular app (use {@link ui.router} module instead). + * + */ + angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']); -/** - * @ngdoc overview - * @name ui.router - * - * @requires ui.router.state - * - * @description - * # ui.router - * - * ## The main module for ui.router - * There are several sub-modules included with the ui.router module, however only this module is needed - * as a dependency within your angular app. The other modules are for organization purposes. - * - * The modules are: - * * ui.router - the main "umbrella" module - * * ui.router.router - - * - * *You'll need to include **only** this module as the dependency within your angular app.* - * - *
          - * 
          - * 
          - * 
          - *   
          - *   
          - *   
          - *   
          - * 
          - * 
          - * 
          - * 
          - * 
          - */ -angular.module('ui.router', ['ui.router.state']); + /** + * @ngdoc overview + * @name ui.router + * + * @requires ui.router.state + * + * @description + * # ui.router + * + * ## The main module for ui.router + * There are several sub-modules included with the ui.router module, however only this module is needed + * as a dependency within your angular app. The other modules are for organization purposes. + * + * The modules are: + * * ui.router - the main "umbrella" module + * * ui.router.router - + * + * *You'll need to include **only** this module as the dependency within your angular app.* + * + *
          +     * 
          +     * 
          +     * 
          +     *   
          +     *   
          +     *   
          +     *   
          +     * 
          +     * 
          +     * 
          +     * 
          +     * 
          + */ + angular.module('ui.router', ['ui.router.state']); -angular.module('ui.router.compat', ['ui.router']); + angular.module('ui.router.compat', ['ui.router']); -/** - * @ngdoc object - * @name ui.router.util.$resolve - * - * @requires $q - * @requires $injector - * - * @description - * Manages resolution of (acyclic) graphs of promises. - */ -$Resolve.$inject = ['$q', '$injector']; -function $Resolve( $q, $injector) { - - var VISIT_IN_PROGRESS = 1, - VISIT_DONE = 2, - NOTHING = {}, - NO_DEPENDENCIES = [], - NO_LOCALS = NOTHING, - NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING }); - - - /** - * @ngdoc function - * @name ui.router.util.$resolve#study - * @methodOf ui.router.util.$resolve - * - * @description - * Studies a set of invocables that are likely to be used multiple times. - *
          -   * $resolve.study(invocables)(locals, parent, self)
          -   * 
          - * is equivalent to - *
          -   * $resolve.resolve(invocables, locals, parent, self)
          -   * 
          - * but the former is more efficient (in fact `resolve` just calls `study` - * internally). - * - * @param {object} invocables Invocable objects - * @return {function} a function to pass in locals, parent and self - */ - this.study = function (invocables) { - if (!isObject(invocables)) throw new Error("'invocables' must be an object"); - var invocableKeys = objectKeys(invocables || {}); - - // Perform a topological sort of invocables to build an ordered plan - var plan = [], cycle = [], visited = {}; - function visit(value, key) { - if (visited[key] === VISIT_DONE) return; - - cycle.push(key); - if (visited[key] === VISIT_IN_PROGRESS) { - cycle.splice(0, indexOf(cycle, key)); - throw new Error("Cyclic dependency: " + cycle.join(" -> ")); - } - visited[key] = VISIT_IN_PROGRESS; - - if (isString(value)) { - plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES); - } else { - var params = $injector.annotate(value); - forEach(params, function (param) { - if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); - }); - plan.push(key, value, params); - } - - cycle.pop(); - visited[key] = VISIT_DONE; - } - forEach(invocables, visit); - invocables = cycle = visited = null; // plan is all that's required - - function isResolve(value) { - return isObject(value) && value.then && value.$$promises; - } - - return function (locals, parent, self) { - if (isResolve(locals) && self === undefined) { - self = parent; parent = locals; locals = null; - } - if (!locals) locals = NO_LOCALS; - else if (!isObject(locals)) { - throw new Error("'locals' must be an object"); - } - if (!parent) parent = NO_PARENT; - else if (!isResolve(parent)) { - throw new Error("'parent' must be a promise returned by $resolve.resolve()"); - } - - // To complete the overall resolution, we have to wait for the parent - // promise and for the promise for each invokable in our plan. - var resolution = $q.defer(), - result = resolution.promise, - promises = result.$$promises = {}, - values = extend({}, locals), - wait = 1 + plan.length/3, - merged = false; - - function done() { - // Merge parent values we haven't got yet and publish our own $$values - if (!--wait) { - if (!merged) merge(values, parent.$$values); - result.$$values = values; - result.$$promises = result.$$promises || true; // keep for isResolve() - delete result.$$inheritedValues; - resolution.resolve(values); - } - } - - function fail(reason) { - result.$$failure = reason; - resolution.reject(reason); - } - - // Short-circuit if parent has already failed - if (isDefined(parent.$$failure)) { - fail(parent.$$failure); - return result; - } - - if (parent.$$inheritedValues) { - merge(values, omit(parent.$$inheritedValues, invocableKeys)); - } - - // Merge parent values if the parent has already resolved, or merge - // parent promises and wait if the parent resolve is still in progress. - extend(promises, parent.$$promises); - if (parent.$$values) { - merged = merge(values, omit(parent.$$values, invocableKeys)); - result.$$inheritedValues = omit(parent.$$values, invocableKeys); - done(); - } else { - if (parent.$$inheritedValues) { - result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys); - } - parent.then(done, fail); - } - - // Process each invocable in the plan, but ignore any where a local of the same name exists. - for (var i=0, ii=plan.length; i + * $resolve.study(invocables)(locals, parent, self) + *
          + * is equivalent to + *
          +         * $resolve.resolve(invocables, locals, parent, self)
          +         * 
          + * but the former is more efficient (in fact `resolve` just calls `study` + * internally). + * + * @param {object} invocables Invocable objects + * @return {function} a function to pass in locals, parent and self + */ + this.study = function (invocables) { + if (!isObject(invocables)) throw new Error("'invocables' must be an object"); + var invocableKeys = objectKeys(invocables || {}); + + // Perform a topological sort of invocables to build an ordered plan + var plan = [], cycle = [], visited = {}; + + function visit(value, key) { + if (visited[key] === VISIT_DONE) return; + + cycle.push(key); + if (visited[key] === VISIT_IN_PROGRESS) { + cycle.splice(0, indexOf(cycle, key)); + throw new Error("Cyclic dependency: " + cycle.join(" -> ")); + } + visited[key] = VISIT_IN_PROGRESS; + + if (isString(value)) { + plan.push(key, [function () { + return $injector.get(value); + }], NO_DEPENDENCIES); + } else { + var params = $injector.annotate(value); + forEach(params, function (param) { + if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); + }); + plan.push(key, value, params); + } + + cycle.pop(); + visited[key] = VISIT_DONE; + } + + forEach(invocables, visit); + invocables = cycle = visited = null; // plan is all that's required + + function isResolve(value) { + return isObject(value) && value.then && value.$$promises; + } + + return function (locals, parent, self) { + if (isResolve(locals) && self === undefined) { + self = parent; + parent = locals; + locals = null; + } + if (!locals) locals = NO_LOCALS; + else if (!isObject(locals)) { + throw new Error("'locals' must be an object"); + } + if (!parent) parent = NO_PARENT; + else if (!isResolve(parent)) { + throw new Error("'parent' must be a promise returned by $resolve.resolve()"); + } + + // To complete the overall resolution, we have to wait for the parent + // promise and for the promise for each invokable in our plan. + var resolution = $q.defer(), + result = resolution.promise, + promises = result.$$promises = {}, + values = extend({}, locals), + wait = 1 + plan.length / 3, + merged = false; + + function done() { + // Merge parent values we haven't got yet and publish our own $$values + if (!--wait) { + if (!merged) merge(values, parent.$$values); + result.$$values = values; + result.$$promises = result.$$promises || true; // keep for isResolve() + delete result.$$inheritedValues; + resolution.resolve(values); + } + } + + function fail(reason) { + result.$$failure = reason; + resolution.reject(reason); + } + + // Short-circuit if parent has already failed + if (isDefined(parent.$$failure)) { + fail(parent.$$failure); + return result; + } + + if (parent.$$inheritedValues) { + merge(values, omit(parent.$$inheritedValues, invocableKeys)); + } + + // Merge parent values if the parent has already resolved, or merge + // parent promises and wait if the parent resolve is still in progress. + extend(promises, parent.$$promises); + if (parent.$$values) { + merged = merge(values, omit(parent.$$values, invocableKeys)); + result.$$inheritedValues = omit(parent.$$values, invocableKeys); + done(); + } else { + if (parent.$$inheritedValues) { + result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys); + } + parent.then(done, fail); + } + + // Process each invocable in the plan, but ignore any where a local of the same name exists. + for (var i = 0, ii = plan.length; i < ii; i += 3) { + if (locals.hasOwnProperty(plan[i])) done(); + else invoke(plan[i], plan[i + 1], plan[i + 2]); + } + + function invoke(key, invocable, params) { + // Create a deferred for this invocation. Failures will propagate to the resolution as well. + var invocation = $q.defer(), waitParams = 0; + + function onfailure(reason) { + invocation.reject(reason); + fail(reason); + } + + // Wait for any parameter that we have a promise for (either from parent or from this + // resolve; in that case study() will have made sure it's ordered before us in the plan). + forEach(params, function (dep) { + if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) { + waitParams++; + promises[dep].then(function (result) { + values[dep] = result; + if (!(--waitParams)) proceed(); + }, onfailure); + } + }); + if (!waitParams) proceed(); + function proceed() { + if (isDefined(result.$$failure)) return; + try { + invocation.resolve($injector.invoke(invocable, self, values)); + invocation.promise.then(function (result) { + values[key] = result; + done(); + }, onfailure); + } catch (e) { + onfailure(e); + } + } + + // Publish promise synchronously; invocations further down in the plan may depend on it. + promises[key] = invocation.promise; + } + + return result; + }; + }; - /** - * @ngdoc function - * @name ui.router.util.$templateFactory#fromConfig - * @methodOf ui.router.util.$templateFactory - * - * @description - * Creates a template from a configuration object. - * - * @param {object} config Configuration object for which to load a template. - * The following properties are search in the specified order, and the first one - * that is defined is used to create the template: - * - * @param {string|object} config.template html string template or function to - * load via {@link ui.router.util.$templateFactory#fromString fromString}. - * @param {string|object} config.templateUrl url to load or a function returning - * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}. - * @param {Function} config.templateProvider function to invoke via - * {@link ui.router.util.$templateFactory#fromProvider fromProvider}. - * @param {object} params Parameters to pass to the template function. - * @param {object} locals Locals to pass to `invoke` if the template is loaded - * via a `templateProvider`. Defaults to `{ params: params }`. - * - * @return {string|object} The template html as a string, or a promise for - * that string,or `null` if no template is configured. - */ - this.fromConfig = function (config, params, locals) { - return ( - isDefined(config.template) ? this.fromString(config.template, params) : - isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) : - isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) : - null - ); - }; - - /** - * @ngdoc function - * @name ui.router.util.$templateFactory#fromString - * @methodOf ui.router.util.$templateFactory - * - * @description - * Creates a template from a string or a function returning a string. - * - * @param {string|object} template html template as a string or function that - * returns an html template as a string. - * @param {object} params Parameters to pass to the template function. - * - * @return {string|object} The template html as a string, or a promise for that - * string. - */ - this.fromString = function (template, params) { - return isFunction(template) ? template(params) : template; - }; - - /** - * @ngdoc function - * @name ui.router.util.$templateFactory#fromUrl - * @methodOf ui.router.util.$templateFactory - * - * @description - * Loads a template from the a URL via `$http` and `$templateCache`. - * - * @param {string|Function} url url of the template to load, or a function - * that returns a url. - * @param {Object} params Parameters to pass to the url function. - * @return {string|Promise.} The template html as a string, or a promise - * for that string. - */ - this.fromUrl = function (url, params) { - if (isFunction(url)) url = url(params); - if (url == null) return null; - else return $http - .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }}) - .then(function(response) { return response.data; }); - }; - - /** - * @ngdoc function - * @name ui.router.util.$templateFactory#fromProvider - * @methodOf ui.router.util.$templateFactory - * - * @description - * Creates a template by invoking an injectable provider function. - * - * @param {Function} provider Function to invoke via `$injector.invoke` - * @param {Object} params Parameters for the template. - * @param {Object} locals Locals to pass to `invoke`. Defaults to - * `{ params: params }`. - * @return {string|Promise.} The template html as a string, or a promise - * for that string. - */ - this.fromProvider = function (provider, params, locals) { - return $injector.invoke(provider, null, locals || { params: params }); - }; -} + /** + * @ngdoc function + * @name ui.router.util.$resolve#resolve + * @methodOf ui.router.util.$resolve + * + * @description + * Resolves a set of invocables. An invocable is a function to be invoked via + * `$injector.invoke()`, and can have an arbitrary number of dependencies. + * An invocable can either return a value directly, + * or a `$q` promise. If a promise is returned it will be resolved and the + * resulting value will be used instead. Dependencies of invocables are resolved + * (in this order of precedence) + * + * - from the specified `locals` + * - from another invocable that is part of this `$resolve` call + * - from an invocable that is inherited from a `parent` call to `$resolve` + * (or recursively + * - from any ancestor `$resolve` of that parent). + * + * The return value of `$resolve` is a promise for an object that contains + * (in this order of precedence) + * + * - any `locals` (if specified) + * - the resolved return values of all injectables + * - any values inherited from a `parent` call to `$resolve` (if specified) + * + * The promise will resolve after the `parent` promise (if any) and all promises + * returned by injectables have been resolved. If any invocable + * (or `$injector.invoke`) throws an exception, or if a promise returned by an + * invocable is rejected, the `$resolve` promise is immediately rejected with the + * same error. A rejection of a `parent` promise (if specified) will likewise be + * propagated immediately. Once the `$resolve` promise has been rejected, no + * further invocables will be called. + * + * Cyclic dependencies between invocables are not permitted and will caues `$resolve` + * to throw an error. As a special case, an injectable can depend on a parameter + * with the same name as the injectable, which will be fulfilled from the `parent` + * injectable of the same name. This allows inherited values to be decorated. + * Note that in this case any other injectable in the same `$resolve` with the same + * dependency would see the decorated value, not the inherited value. + * + * Note that missing dependencies -- unlike cyclic dependencies -- will cause an + * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) + * exception. + * + * Invocables are invoked eagerly as soon as all dependencies are available. + * This is true even for dependencies inherited from a `parent` call to `$resolve`. + * + * As a special case, an invocable can be a string, in which case it is taken to + * be a service name to be passed to `$injector.get()`. This is supported primarily + * for backwards-compatibility with the `resolve` property of `$routeProvider` + * routes. + * + * @param {object} invocables functions to invoke or + * `$injector` services to fetch. + * @param {object} locals values to make available to the injectables + * @param {object} parent a promise returned by another call to `$resolve`. + * @param {object} self the `this` for the invoked methods + * @return {object} Promise for an object that contains the resolved return value + * of all invocables, as well as any inherited and local values. + */ + this.resolve = function (invocables, locals, parent, self) { + return this.study(invocables)(locals, parent, self); + }; + } -angular.module('ui.router.util').service('$templateFactory', $TemplateFactory); + angular.module('ui.router.util').service('$resolve', $Resolve); -var $$UMFP; // reference to $UrlMatcherFactoryProvider -/** - * @ngdoc object - * @name ui.router.util.type:UrlMatcher - * - * @description - * Matches URLs against patterns and extracts named parameters from the path or the search - * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list - * of search parameters. Multiple search parameter names are separated by '&'. Search parameters - * do not influence whether or not a URL is matched, but their values are passed through into - * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. - * - * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace - * syntax, which optionally allows a regular expression for the parameter to be specified: - * - * * `':'` name - colon placeholder - * * `'*'` name - catch-all placeholder - * * `'{' name '}'` - curly placeholder - * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the - * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. - * - * Parameter names may contain only word characters (latin letters, digits, and underscore) and - * must be unique within the pattern (across both path and search parameters). For colon - * placeholders or curly placeholders without an explicit regexp, a path parameter matches any - * number of characters other than '/'. For catch-all placeholders the path parameter matches - * any number of characters. - * - * Examples: - * - * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for - * trailing slashes, and patterns have to match the entire path, not just a prefix. - * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or - * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. - * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. - * * `'/user/{id:[^/]*}'` - Same as the previous example. - * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id - * parameter consists of 1 to 8 hex digits. - * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the - * path into the parameter 'path'. - * * `'/files/*path'` - ditto. - * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined - * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start - * - * @param {string} pattern The pattern to compile into a matcher. - * @param {Object} config A configuration object hash: - * @param {Object=} parentMatcher Used to concatenate the pattern/config onto - * an existing UrlMatcher - * - * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`. - * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`. - * - * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any - * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns - * non-null) will start with this prefix. - * - * @property {string} source The pattern that was passed into the constructor - * - * @property {string} sourcePath The path portion of the source property - * - * @property {string} sourceSearch The search portion of the source property - * - * @property {string} regex The constructed regex that will be used to match against the url when - * it is time to determine which url will match. - * - * @returns {Object} New `UrlMatcher` object - */ -function UrlMatcher(pattern, config, parentMatcher) { - config = extend({ params: {} }, isObject(config) ? config : {}); - - // Find all placeholders and create a compiled pattern, using either classic or curly syntax: - // '*' name - // ':' name - // '{' name '}' - // '{' name ':' regexp '}' - // The regular expression is somewhat complicated due to the need to allow curly braces - // inside the regular expression. The placeholder regexp breaks down as follows: - // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) - // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case - // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either - // [^{}\\]+ - anything other than curly braces or backslash - // \\. - a backslash escape - // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms - var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, - searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, - compiled = '^', last = 0, m, - segments = this.segments = [], - parentParams = parentMatcher ? parentMatcher.params : {}, - params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(), - paramNames = []; - - function addParameter(id, type, config, location) { - paramNames.push(id); - if (parentParams[id]) return parentParams[id]; - if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); - if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); - params[id] = new $$UMFP.Param(id, type, config, location); - return params[id]; - } - - function quoteRegExp(string, pattern, squash) { - var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); - if (!pattern) return result; - switch(squash) { - case false: surroundPattern = ['(', ')']; break; - case true: surroundPattern = ['?(', ')?']; break; - default: surroundPattern = ['(' + squash + "|", ')?']; break; - } - return result + surroundPattern[0] + pattern + surroundPattern[1]; - } - - this.source = pattern; - - // Split into static segments separated by path parameter placeholders. - // The number of segments is always 1 more than the number of parameters. - function matchDetails(m, isSearch) { - var id, regexp, segment, type, cfg, arrayMode; - id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null - cfg = config.params[id]; - segment = pattern.substring(last, m.index); - regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null); - type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp) }); - return { - id: id, regexp: regexp, segment: segment, type: type, cfg: cfg - }; - } - - var p, param, segment; - while ((m = placeholder.exec(pattern))) { - p = matchDetails(m, false); - if (p.segment.indexOf('?') >= 0) break; // we're into the search part - - param = addParameter(p.id, p.type, p.cfg, "path"); - compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash); - segments.push(p.segment); - last = placeholder.lastIndex; - } - segment = pattern.substring(last); - - // Find any search parameter names and remove them from the last segment - var i = segment.indexOf('?'); - - if (i >= 0) { - var search = this.sourceSearch = segment.substring(i); - segment = segment.substring(0, i); - this.sourcePath = pattern.substring(0, last + i); - - if (search.length > 0) { - last = 0; - while ((m = searchPlaceholder.exec(search))) { - p = matchDetails(m, true); - param = addParameter(p.id, p.type, p.cfg, "search"); - last = placeholder.lastIndex; - // check if ?& - } - } - } else { - this.sourcePath = pattern; - this.sourceSearch = ''; - } + /** + * @ngdoc object + * @name ui.router.util.$templateFactory + * + * @requires $http + * @requires $templateCache + * @requires $injector + * + * @description + * Service. Manages loading of templates. + */ + $TemplateFactory.$inject = ['$http', '$templateCache', '$injector']; + function $TemplateFactory($http, $templateCache, $injector) { - compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$'; - segments.push(segment); + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromConfig + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template from a configuration object. + * + * @param {object} config Configuration object for which to load a template. + * The following properties are search in the specified order, and the first one + * that is defined is used to create the template: + * + * @param {string|object} config.template html string template or function to + * load via {@link ui.router.util.$templateFactory#fromString fromString}. + * @param {string|object} config.templateUrl url to load or a function returning + * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}. + * @param {Function} config.templateProvider function to invoke via + * {@link ui.router.util.$templateFactory#fromProvider fromProvider}. + * @param {object} params Parameters to pass to the template function. + * @param {object} locals Locals to pass to `invoke` if the template is loaded + * via a `templateProvider`. Defaults to `{ params: params }`. + * + * @return {string|object} The template html as a string, or a promise for + * that string,or `null` if no template is configured. + */ + this.fromConfig = function (config, params, locals) { + return ( + isDefined(config.template) ? this.fromString(config.template, params) : + isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) : + isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) : + null + ); + }; - this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined); - this.prefix = segments[0]; - this.$$paramNames = paramNames; -} + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromString + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template from a string or a function returning a string. + * + * @param {string|object} template html template as a string or function that + * returns an html template as a string. + * @param {object} params Parameters to pass to the template function. + * + * @return {string|object} The template html as a string, or a promise for that + * string. + */ + this.fromString = function (template, params) { + return isFunction(template) ? template(params) : template; + }; -/** - * @ngdoc function - * @name ui.router.util.type:UrlMatcher#concat - * @methodOf ui.router.util.type:UrlMatcher - * - * @description - * Returns a new matcher for a pattern constructed by appending the path part and adding the - * search parameters of the specified pattern to this pattern. The current pattern is not - * modified. This can be understood as creating a pattern for URLs that are relative to (or - * suffixes of) the current pattern. - * - * @example - * The following two matchers are equivalent: - *
          - * new UrlMatcher('/user/{id}?q').concat('/details?date');
          - * new UrlMatcher('/user/{id}/details?q&date');
          - * 
          - * - * @param {string} pattern The pattern to append. - * @param {Object} config An object hash of the configuration for the matcher. - * @returns {UrlMatcher} A matcher for the concatenated pattern. - */ -UrlMatcher.prototype.concat = function (pattern, config) { - // Because order of search parameters is irrelevant, we can add our own search - // parameters to the end of the new pattern. Parse the new pattern by itself - // and then join the bits together, but it's much easier to do this on a string level. - var defaultConfig = { - caseInsensitive: $$UMFP.caseInsensitive(), - strict: $$UMFP.strictMode(), - squash: $$UMFP.defaultSquashPolicy() - }; - return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this); -}; - -UrlMatcher.prototype.toString = function () { - return this.source; -}; + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromUrl + * @methodOf ui.router.util.$templateFactory + * + * @description + * Loads a template from the a URL via `$http` and `$templateCache`. + * + * @param {string|Function} url url of the template to load, or a function + * that returns a url. + * @param {Object} params Parameters to pass to the url function. + * @return {string|Promise.} The template html as a string, or a promise + * for that string. + */ + this.fromUrl = function (url, params) { + if (isFunction(url)) url = url(params); + if (url == null) return null; + else return $http + .get(url, {cache: $templateCache, headers: {Accept: 'text/html'}}) + .then(function (response) { + return response.data; + }); + }; -/** - * @ngdoc function - * @name ui.router.util.type:UrlMatcher#exec - * @methodOf ui.router.util.type:UrlMatcher - * - * @description - * Tests the specified path against this matcher, and returns an object containing the captured - * parameter values, or null if the path does not match. The returned object contains the values - * of any search parameters that are mentioned in the pattern, but their value may be null if - * they are not present in `searchParams`. This means that search parameters are always treated - * as optional. - * - * @example - *
          - * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
          - *   x: '1', q: 'hello'
          - * });
          - * // returns { id: 'bob', q: 'hello', r: null }
          - * 
          - * - * @param {string} path The URL path to match, e.g. `$location.path()`. - * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. - * @returns {Object} The captured parameter values. - */ -UrlMatcher.prototype.exec = function (path, searchParams) { - var m = this.regexp.exec(path); - if (!m) return null; - searchParams = searchParams || {}; - - var paramNames = this.parameters(), nTotal = paramNames.length, - nPath = this.segments.length - 1, - values = {}, i, j, cfg, paramName; - - if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); - - function decodePathArray(string) { - function reverseString(str) { return str.split("").reverse().join(""); } - function unquoteDashes(str) { return str.replace(/\\-/, "-"); } - - var split = reverseString(string).split(/-(?!\\)/); - var allReversed = map(split, reverseString); - return map(allReversed, unquoteDashes).reverse(); - } - - for (i = 0; i < nPath; i++) { - paramName = paramNames[i]; - var param = this.params[paramName]; - var paramVal = m[i+1]; - // if the param value matches a pre-replace pair, replace the value before decoding. - for (j = 0; j < param.replace; j++) { - if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; + /** + * @ngdoc function + * @name ui.router.util.$templateFactory#fromProvider + * @methodOf ui.router.util.$templateFactory + * + * @description + * Creates a template by invoking an injectable provider function. + * + * @param {Function} provider Function to invoke via `$injector.invoke` + * @param {Object} params Parameters for the template. + * @param {Object} locals Locals to pass to `invoke`. Defaults to + * `{ params: params }`. + * @return {string|Promise.} The template html as a string, or a promise + * for that string. + */ + this.fromProvider = function (provider, params, locals) { + return $injector.invoke(provider, null, locals || {params: params}); + }; } - if (paramVal && param.array === true) paramVal = decodePathArray(paramVal); - values[paramName] = param.value(paramVal); - } - for (/**/; i < nTotal; i++) { - paramName = paramNames[i]; - values[paramName] = this.params[paramName].value(searchParams[paramName]); - } - return values; -}; + angular.module('ui.router.util').service('$templateFactory', $TemplateFactory); -/** - * @ngdoc function - * @name ui.router.util.type:UrlMatcher#parameters - * @methodOf ui.router.util.type:UrlMatcher - * - * @description - * Returns the names of all path and search parameters of this pattern in an unspecified order. - * - * @returns {Array.} An array of parameter names. Must be treated as read-only. If the - * pattern has no parameters, an empty array is returned. - */ -UrlMatcher.prototype.parameters = function (param) { - if (!isDefined(param)) return this.$$paramNames; - return this.params[param] || null; -}; + var $$UMFP; // reference to $UrlMatcherFactoryProvider -/** - * @ngdoc function - * @name ui.router.util.type:UrlMatcher#validate - * @methodOf ui.router.util.type:UrlMatcher - * - * @description - * Checks an object hash of parameters to validate their correctness according to the parameter - * types of this `UrlMatcher`. - * - * @param {Object} params The object hash of parameters to validate. - * @returns {boolean} Returns `true` if `params` validates, otherwise `false`. - */ -UrlMatcher.prototype.validates = function (params) { - return this.params.$$validates(params); -}; + /** + * @ngdoc object + * @name ui.router.util.type:UrlMatcher + * + * @description + * Matches URLs against patterns and extracts named parameters from the path or the search + * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list + * of search parameters. Multiple search parameter names are separated by '&'. Search parameters + * do not influence whether or not a URL is matched, but their values are passed through into + * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. + * + * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace + * syntax, which optionally allows a regular expression for the parameter to be specified: + * + * * `':'` name - colon placeholder + * * `'*'` name - catch-all placeholder + * * `'{' name '}'` - curly placeholder + * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the + * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. + * + * Parameter names may contain only word characters (latin letters, digits, and underscore) and + * must be unique within the pattern (across both path and search parameters). For colon + * placeholders or curly placeholders without an explicit regexp, a path parameter matches any + * number of characters other than '/'. For catch-all placeholders the path parameter matches + * any number of characters. + * + * Examples: + * + * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for + * trailing slashes, and patterns have to match the entire path, not just a prefix. + * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or + * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. + * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. + * * `'/user/{id:[^/]*}'` - Same as the previous example. + * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id + * parameter consists of 1 to 8 hex digits. + * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the + * path into the parameter 'path'. + * * `'/files/*path'` - ditto. + * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined + * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start + * + * @param {string} pattern The pattern to compile into a matcher. + * @param {Object} config A configuration object hash: + * @param {Object=} parentMatcher Used to concatenate the pattern/config onto + * an existing UrlMatcher + * + * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`. + * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`. + * + * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any + * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns + * non-null) will start with this prefix. + * + * @property {string} source The pattern that was passed into the constructor + * + * @property {string} sourcePath The path portion of the source property + * + * @property {string} sourceSearch The search portion of the source property + * + * @property {string} regex The constructed regex that will be used to match against the url when + * it is time to determine which url will match. + * + * @returns {Object} New `UrlMatcher` object + */ + function UrlMatcher(pattern, config, parentMatcher) { + config = extend({params: {}}, isObject(config) ? config : {}); + + // Find all placeholders and create a compiled pattern, using either classic or curly syntax: + // '*' name + // ':' name + // '{' name '}' + // '{' name ':' regexp '}' + // The regular expression is somewhat complicated due to the need to allow curly braces + // inside the regular expression. The placeholder regexp breaks down as follows: + // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) + // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case + // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either + // [^{}\\]+ - anything other than curly braces or backslash + // \\. - a backslash escape + // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms + var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + compiled = '^', last = 0, m, + segments = this.segments = [], + parentParams = parentMatcher ? parentMatcher.params : {}, + params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(), + paramNames = []; + + function addParameter(id, type, config, location) { + paramNames.push(id); + if (parentParams[id]) return parentParams[id]; + if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); + if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); + params[id] = new $$UMFP.Param(id, type, config, location); + return params[id]; + } -/** - * @ngdoc function - * @name ui.router.util.type:UrlMatcher#format - * @methodOf ui.router.util.type:UrlMatcher - * - * @description - * Creates a URL that matches this pattern by substituting the specified values - * for the path and search parameters. Null values for path parameters are - * treated as empty strings. - * - * @example - *
          - * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
          - * // returns '/user/bob?q=yes'
          - * 
          - * - * @param {Object} values the values to substitute for the parameters in this pattern. - * @returns {string} the formatted URL (path and optionally search part). - */ -UrlMatcher.prototype.format = function (values) { - values = values || {}; - var segments = this.segments, params = this.parameters(), paramset = this.params; - if (!this.validates(values)) return null; - - var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0]; - - function encodeDashes(str) { // Replace dashes with encoded "\-" - return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); }); - } - - for (i = 0; i < nTotal; i++) { - var isPathParam = i < nPath; - var name = params[i], param = paramset[name], value = param.value(values[name]); - var isDefaultValue = param.isOptional && param.type.equals(param.value(), value); - var squash = isDefaultValue ? param.squash : false; - var encoded = param.type.encode(value); - - if (isPathParam) { - var nextSegment = segments[i + 1]; - if (squash === false) { - if (encoded != null) { - if (isArray(encoded)) { - result += map(encoded, encodeDashes).join("-"); - } else { - result += encodeURIComponent(encoded); - } + function quoteRegExp(string, pattern, squash) { + var surroundPattern = ['', ''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); + if (!pattern) return result; + switch (squash) { + case false: + surroundPattern = ['(', ')']; + break; + case true: + surroundPattern = ['?(', ')?']; + break; + default: + surroundPattern = ['(' + squash + "|", ')?']; + break; + } + return result + surroundPattern[0] + pattern + surroundPattern[1]; } - result += nextSegment; - } else if (squash === true) { - var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/; - result += nextSegment.match(capture)[1]; - } else if (isString(squash)) { - result += squash + nextSegment; - } - } else { - if (encoded == null || (isDefaultValue && squash !== false)) continue; - if (!isArray(encoded)) encoded = [ encoded ]; - encoded = map(encoded, encodeURIComponent).join('&' + name + '='); - result += (search ? '&' : '?') + (name + '=' + encoded); - search = true; - } - } - return result; -}; + this.source = pattern; + + // Split into static segments separated by path parameter placeholders. + // The number of segments is always 1 more than the number of parameters. + function matchDetails(m, isSearch) { + var id, regexp, segment, type, cfg, arrayMode; + id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null + cfg = config.params[id]; + segment = pattern.substring(last, m.index); + regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null); + type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), {pattern: new RegExp(regexp)}); + return { + id: id, regexp: regexp, segment: segment, type: type, cfg: cfg + }; + } -/** - * @ngdoc object - * @name ui.router.util.type:Type - * - * @description - * Implements an interface to define custom parameter types that can be decoded from and encoded to - * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`} - * objects when matching or formatting URLs, or comparing or validating parameter values. - * - * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more - * information on registering custom types. - * - * @param {Object} config A configuration object which contains the custom type definition. The object's - * properties will override the default methods and/or pattern in `Type`'s public interface. - * @example - *
          - * {
          +        var p, param, segment;
          +        while ((m = placeholder.exec(pattern))) {
          +            p = matchDetails(m, false);
          +            if (p.segment.indexOf('?') >= 0) break; // we're into the search part
          +
          +            param = addParameter(p.id, p.type, p.cfg, "path");
          +            compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);
          +            segments.push(p.segment);
          +            last = placeholder.lastIndex;
          +        }
          +        segment = pattern.substring(last);
          +
          +        // Find any search parameter names and remove them from the last segment
          +        var i = segment.indexOf('?');
          +
          +        if (i >= 0) {
          +            var search = this.sourceSearch = segment.substring(i);
          +            segment = segment.substring(0, i);
          +            this.sourcePath = pattern.substring(0, last + i);
          +
          +            if (search.length > 0) {
          +                last = 0;
          +                while ((m = searchPlaceholder.exec(search))) {
          +                    p = matchDetails(m, true);
          +                    param = addParameter(p.id, p.type, p.cfg, "search");
          +                    last = placeholder.lastIndex;
          +                    // check if ?&
          +                }
          +            }
          +        } else {
          +            this.sourcePath = pattern;
          +            this.sourceSearch = '';
          +        }
          +
          +        compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
          +        segments.push(segment);
          +
          +        this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
          +        this.prefix = segments[0];
          +        this.$$paramNames = paramNames;
          +    }
          +
          +    /**
          +     * @ngdoc function
          +     * @name ui.router.util.type:UrlMatcher#concat
          +     * @methodOf ui.router.util.type:UrlMatcher
          +     *
          +     * @description
          +     * Returns a new matcher for a pattern constructed by appending the path part and adding the
          +     * search parameters of the specified pattern to this pattern. The current pattern is not
          +     * modified. This can be understood as creating a pattern for URLs that are relative to (or
          +     * suffixes of) the current pattern.
          +     *
          +     * @example
          +     * The following two matchers are equivalent:
          +     * 
          +     * new UrlMatcher('/user/{id}?q').concat('/details?date');
          +     * new UrlMatcher('/user/{id}/details?q&date');
          +     * 
          + * + * @param {string} pattern The pattern to append. + * @param {Object} config An object hash of the configuration for the matcher. + * @returns {UrlMatcher} A matcher for the concatenated pattern. + */ + UrlMatcher.prototype.concat = function (pattern, config) { + // Because order of search parameters is irrelevant, we can add our own search + // parameters to the end of the new pattern. Parse the new pattern by itself + // and then join the bits together, but it's much easier to do this on a string level. + var defaultConfig = { + caseInsensitive: $$UMFP.caseInsensitive(), + strict: $$UMFP.strictMode(), + squash: $$UMFP.defaultSquashPolicy() + }; + return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this); + }; + + UrlMatcher.prototype.toString = function () { + return this.source; + }; + + /** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#exec + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Tests the specified path against this matcher, and returns an object containing the captured + * parameter values, or null if the path does not match. The returned object contains the values + * of any search parameters that are mentioned in the pattern, but their value may be null if + * they are not present in `searchParams`. This means that search parameters are always treated + * as optional. + * + * @example + *
          +     * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
          + *   x: '1', q: 'hello'
          + * });
          +     * // returns { id: 'bob', q: 'hello', r: null }
          +     * 
          + * + * @param {string} path The URL path to match, e.g. `$location.path()`. + * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. + * @returns {Object} The captured parameter values. + */ + UrlMatcher.prototype.exec = function (path, searchParams) { + var m = this.regexp.exec(path); + if (!m) return null; + searchParams = searchParams || {}; + + var paramNames = this.parameters(), nTotal = paramNames.length, + nPath = this.segments.length - 1, + values = {}, i, j, cfg, paramName; + + if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); + + function decodePathArray(string) { + function reverseString(str) { + return str.split("").reverse().join(""); + } + + function unquoteDashes(str) { + return str.replace(/\\-/, "-"); + } + + var split = reverseString(string).split(/-(?!\\)/); + var allReversed = map(split, reverseString); + return map(allReversed, unquoteDashes).reverse(); + } + + for (i = 0; i < nPath; i++) { + paramName = paramNames[i]; + var param = this.params[paramName]; + var paramVal = m[i + 1]; + // if the param value matches a pre-replace pair, replace the value before decoding. + for (j = 0; j < param.replace; j++) { + if (param.replace[j].from === paramVal) paramVal = param.replace[j].to; + } + if (paramVal && param.array === true) paramVal = decodePathArray(paramVal); + values[paramName] = param.value(paramVal); + } + for (/**/; i < nTotal; i++) { + paramName = paramNames[i]; + values[paramName] = this.params[paramName].value(searchParams[paramName]); + } + + return values; + }; + + /** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#parameters + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Returns the names of all path and search parameters of this pattern in an unspecified order. + * + * @returns {Array.} An array of parameter names. Must be treated as read-only. If the + * pattern has no parameters, an empty array is returned. + */ + UrlMatcher.prototype.parameters = function (param) { + if (!isDefined(param)) return this.$$paramNames; + return this.params[param] || null; + }; + + /** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#validate + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Checks an object hash of parameters to validate their correctness according to the parameter + * types of this `UrlMatcher`. + * + * @param {Object} params The object hash of parameters to validate. + * @returns {boolean} Returns `true` if `params` validates, otherwise `false`. + */ + UrlMatcher.prototype.validates = function (params) { + return this.params.$$validates(params); + }; + + /** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#format + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Creates a URL that matches this pattern by substituting the specified values + * for the path and search parameters. Null values for path parameters are + * treated as empty strings. + * + * @example + *
          +     * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
          +     * // returns '/user/bob?q=yes'
          +     * 
          + * + * @param {Object} values the values to substitute for the parameters in this pattern. + * @returns {string} the formatted URL (path and optionally search part). + */ + UrlMatcher.prototype.format = function (values) { + values = values || {}; + var segments = this.segments, params = this.parameters(), paramset = this.params; + if (!this.validates(values)) return null; + + var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0]; + + function encodeDashes(str) { // Replace dashes with encoded "\-" + return encodeURIComponent(str).replace(/-/g, function (c) { + return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); + }); + } + + for (i = 0; i < nTotal; i++) { + var isPathParam = i < nPath; + var name = params[i], param = paramset[name], value = param.value(values[name]); + var isDefaultValue = param.isOptional && param.type.equals(param.value(), value); + var squash = isDefaultValue ? param.squash : false; + var encoded = param.type.encode(value); + + if (isPathParam) { + var nextSegment = segments[i + 1]; + if (squash === false) { + if (encoded != null) { + if (isArray(encoded)) { + result += map(encoded, encodeDashes).join("-"); + } else { + result += encodeURIComponent(encoded); + } + } + result += nextSegment; + } else if (squash === true) { + var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/; + result += nextSegment.match(capture)[1]; + } else if (isString(squash)) { + result += squash + nextSegment; + } + } else { + if (encoded == null || (isDefaultValue && squash !== false)) continue; + if (!isArray(encoded)) encoded = [encoded]; + encoded = map(encoded, encodeURIComponent).join('&' + name + '='); + result += (search ? '&' : '?') + (name + '=' + encoded); + search = true; + } + } + + return result; + }; + + /** + * @ngdoc object + * @name ui.router.util.type:Type + * + * @description + * Implements an interface to define custom parameter types that can be decoded from and encoded to + * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`} + * objects when matching or formatting URLs, or comparing or validating parameter values. + * + * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more + * information on registering custom types. + * + * @param {Object} config A configuration object which contains the custom type definition. The object's + * properties will override the default methods and/or pattern in `Type`'s public interface. + * @example + *
          +     * {
            *   decode: function(val) { return parseInt(val, 10); },
            *   encode: function(val) { return val && val.toString(); },
            *   equals: function(a, b) { return this.is(a) && a === b; },
            *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
            *   pattern: /\d+/
            * }
          - * 
          - * - * @property {RegExp} pattern The regular expression pattern used to match values of this type when - * coming from a substring of a URL. - * - * @returns {Object} Returns a new `Type` object. - */ -function Type(config) { - extend(this, config); -} + *
          + * + * @property {RegExp} pattern The regular expression pattern used to match values of this type when + * coming from a substring of a URL. + * + * @returns {Object} Returns a new `Type` object. + */ + function Type(config) { + extend(this, config); + } -/** - * @ngdoc function - * @name ui.router.util.type:Type#is - * @methodOf ui.router.util.type:Type - * - * @description - * Detects whether a value is of a particular type. Accepts a native (decoded) value - * and determines whether it matches the current `Type` object. - * - * @param {*} val The value to check. - * @param {string} key Optional. If the type check is happening in the context of a specific - * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the - * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects. - * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`. - */ -Type.prototype.is = function(val, key) { - return true; -}; + /** + * @ngdoc function + * @name ui.router.util.type:Type#is + * @methodOf ui.router.util.type:Type + * + * @description + * Detects whether a value is of a particular type. Accepts a native (decoded) value + * and determines whether it matches the current `Type` object. + * + * @param {*} val The value to check. + * @param {string} key Optional. If the type check is happening in the context of a specific + * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the + * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects. + * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`. + */ + Type.prototype.is = function (val, key) { + return true; + }; -/** - * @ngdoc function - * @name ui.router.util.type:Type#encode - * @methodOf ui.router.util.type:Type - * - * @description - * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the - * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it - * only needs to be a representation of `val` that has been coerced to a string. - * - * @param {*} val The value to encode. - * @param {string} key The name of the parameter in which `val` is stored. Can be used for - * meta-programming of `Type` objects. - * @returns {string} Returns a string representation of `val` that can be encoded in a URL. - */ -Type.prototype.encode = function(val, key) { - return val; -}; + /** + * @ngdoc function + * @name ui.router.util.type:Type#encode + * @methodOf ui.router.util.type:Type + * + * @description + * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the + * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it + * only needs to be a representation of `val` that has been coerced to a string. + * + * @param {*} val The value to encode. + * @param {string} key The name of the parameter in which `val` is stored. Can be used for + * meta-programming of `Type` objects. + * @returns {string} Returns a string representation of `val` that can be encoded in a URL. + */ + Type.prototype.encode = function (val, key) { + return val; + }; -/** - * @ngdoc function - * @name ui.router.util.type:Type#decode - * @methodOf ui.router.util.type:Type - * - * @description - * Converts a parameter value (from URL string or transition param) to a custom/native value. - * - * @param {string} val The URL parameter value to decode. - * @param {string} key The name of the parameter in which `val` is stored. Can be used for - * meta-programming of `Type` objects. - * @returns {*} Returns a custom representation of the URL parameter value. - */ -Type.prototype.decode = function(val, key) { - return val; -}; + /** + * @ngdoc function + * @name ui.router.util.type:Type#decode + * @methodOf ui.router.util.type:Type + * + * @description + * Converts a parameter value (from URL string or transition param) to a custom/native value. + * + * @param {string} val The URL parameter value to decode. + * @param {string} key The name of the parameter in which `val` is stored. Can be used for + * meta-programming of `Type` objects. + * @returns {*} Returns a custom representation of the URL parameter value. + */ + Type.prototype.decode = function (val, key) { + return val; + }; -/** - * @ngdoc function - * @name ui.router.util.type:Type#equals - * @methodOf ui.router.util.type:Type - * - * @description - * Determines whether two decoded values are equivalent. - * - * @param {*} a A value to compare against. - * @param {*} b A value to compare against. - * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`. - */ -Type.prototype.equals = function(a, b) { - return a == b; -}; - -Type.prototype.$subPattern = function() { - var sub = this.pattern.toString(); - return sub.substr(1, sub.length - 2); -}; - -Type.prototype.pattern = /.*/; - -Type.prototype.toString = function() { return "{Type:" + this.name + "}"; }; - -/* - * Wraps an existing custom Type as an array of Type, depending on 'mode'. - * e.g.: - * - urlmatcher pattern "/path?{queryParam[]:int}" - * - url: "/path?queryParam=1&queryParam=2 - * - $stateParams.queryParam will be [1, 2] - * if `mode` is "auto", then - * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 - * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2] - */ -Type.prototype.$asArray = function(mode, isSearch) { - if (!mode) return this; - if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only"); - return new ArrayType(this, mode); - - function ArrayType(type, mode) { - function bindTo(type, callbackName) { - return function() { - return type[callbackName].apply(type, arguments); - }; - } + /** + * @ngdoc function + * @name ui.router.util.type:Type#equals + * @methodOf ui.router.util.type:Type + * + * @description + * Determines whether two decoded values are equivalent. + * + * @param {*} a A value to compare against. + * @param {*} b A value to compare against. + * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`. + */ + Type.prototype.equals = function (a, b) { + return a == b; + }; - // Wrap non-array value as array - function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); } - // Unwrap array value for "auto" mode. Return undefined for empty array. - function arrayUnwrap(val) { - switch(val.length) { - case 0: return undefined; - case 1: return mode === "auto" ? val[0] : val; - default: return val; - } - } - function falsey(val) { return !val; } - - // Wraps type (.is/.encode/.decode) functions to operate on each value of an array - function arrayHandler(callback, allTruthyMode) { - return function handleArray(val) { - val = arrayWrap(val); - var result = map(val, callback); - if (allTruthyMode === true) - return filter(result, falsey).length === 0; - return arrayUnwrap(result); - }; - } + Type.prototype.$subPattern = function () { + var sub = this.pattern.toString(); + return sub.substr(1, sub.length - 2); + }; + + Type.prototype.pattern = /.*/; + + Type.prototype.toString = function () { + return "{Type:" + this.name + "}"; + }; - // Wraps type (.equals) functions to operate on each value of an array - function arrayEqualsHandler(callback) { - return function handleArray(val1, val2) { - var left = arrayWrap(val1), right = arrayWrap(val2); - if (left.length !== right.length) return false; - for (var i = 0; i < left.length; i++) { - if (!callback(left[i], right[i])) return false; + /* + * Wraps an existing custom Type as an array of Type, depending on 'mode'. + * e.g.: + * - urlmatcher pattern "/path?{queryParam[]:int}" + * - url: "/path?queryParam=1&queryParam=2 + * - $stateParams.queryParam will be [1, 2] + * if `mode` is "auto", then + * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 + * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2] + */ + Type.prototype.$asArray = function (mode, isSearch) { + if (!mode) return this; + if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only"); + return new ArrayType(this, mode); + + function ArrayType(type, mode) { + function bindTo(type, callbackName) { + return function () { + return type[callbackName].apply(type, arguments); + }; + } + + // Wrap non-array value as array + function arrayWrap(val) { + return isArray(val) ? val : (isDefined(val) ? [val] : []); + } + + // Unwrap array value for "auto" mode. Return undefined for empty array. + function arrayUnwrap(val) { + switch (val.length) { + case 0: + return undefined; + case 1: + return mode === "auto" ? val[0] : val; + default: + return val; + } + } + + function falsey(val) { + return !val; + } + + // Wraps type (.is/.encode/.decode) functions to operate on each value of an array + function arrayHandler(callback, allTruthyMode) { + return function handleArray(val) { + val = arrayWrap(val); + var result = map(val, callback); + if (allTruthyMode === true) + return filter(result, falsey).length === 0; + return arrayUnwrap(result); + }; + } + + // Wraps type (.equals) functions to operate on each value of an array + function arrayEqualsHandler(callback) { + return function handleArray(val1, val2) { + var left = arrayWrap(val1), right = arrayWrap(val2); + if (left.length !== right.length) return false; + for (var i = 0; i < left.length; i++) { + if (!callback(left[i], right[i])) return false; + } + return true; + }; + } + + this.encode = arrayHandler(bindTo(type, 'encode')); + this.decode = arrayHandler(bindTo(type, 'decode')); + this.is = arrayHandler(bindTo(type, 'is'), true); + this.equals = arrayEqualsHandler(bindTo(type, 'equals')); + this.pattern = type.pattern; + this.$arrayMode = mode; } - return true; - }; - } + }; - this.encode = arrayHandler(bindTo(type, 'encode')); - this.decode = arrayHandler(bindTo(type, 'decode')); - this.is = arrayHandler(bindTo(type, 'is'), true); - this.equals = arrayEqualsHandler(bindTo(type, 'equals')); - this.pattern = type.pattern; - this.$arrayMode = mode; - } -}; + /** + * @ngdoc object + * @name ui.router.util.$urlMatcherFactory + * + * @description + * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory + * is also available to providers under the name `$urlMatcherFactoryProvider`. + */ + function $UrlMatcherFactory() { + $$UMFP = this; + var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false; -/** - * @ngdoc object - * @name ui.router.util.$urlMatcherFactory - * - * @description - * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory - * is also available to providers under the name `$urlMatcherFactoryProvider`. - */ -function $UrlMatcherFactory() { - $$UMFP = this; + function valToString(val) { + return val != null ? val.toString().replace(/\//g, "%2F") : val; + } - var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false; + function valFromString(val) { + return val != null ? val.toString().replace(/%2F/g, "/") : val; + } - function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; } - function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; } // TODO: in 1.0, make string .is() return false if value is undefined by default. // function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); } - function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); } - - var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = { - string: { - encode: valToString, - decode: valFromString, - is: regexpMatches, - pattern: /[^/]*/ - }, - int: { - encode: valToString, - decode: function(val) { return parseInt(val, 10); }, - is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; }, - pattern: /\d+/ - }, - bool: { - encode: function(val) { return val ? 1 : 0; }, - decode: function(val) { return parseInt(val, 10) !== 0; }, - is: function(val) { return val === true || val === false; }, - pattern: /0|1/ - }, - date: { - encode: function (val) { - if (!this.is(val)) - return undefined; - return [ val.getFullYear(), - ('0' + (val.getMonth() + 1)).slice(-2), - ('0' + val.getDate()).slice(-2) - ].join("-"); - }, - decode: function (val) { - if (this.is(val)) return val; - var match = this.capture.exec(val); - return match ? new Date(match[1], match[2] - 1, match[3]) : undefined; - }, - is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); }, - equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); }, - pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, - capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/ - }, - json: { - encode: angular.toJson, - decode: angular.fromJson, - is: angular.isObject, - equals: angular.equals, - pattern: /[^/]*/ - }, - any: { // does not encode/decode - encode: angular.identity, - decode: angular.identity, - is: angular.identity, - equals: angular.equals, - pattern: /.*/ - } - }; + function regexpMatches(val) { /*jshint validthis:true */ + return this.pattern.test(val); + } - function getDefaultConfig() { - return { - strict: isStrictMode, - caseInsensitive: isCaseInsensitive - }; - } - - function isInjectable(value) { - return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1]))); - } - - /** - * [Internal] Get the default value of a parameter, which may be an injectable function. - */ - $UrlMatcherFactory.$$getDefaultValue = function(config) { - if (!isInjectable(config.value)) return config.value; - if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); - return injector.invoke(config.value); - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#caseInsensitive - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Defines whether URL matching should be case sensitive (the default behavior), or not. - * - * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`; - * @returns {boolean} the current value of caseInsensitive - */ - this.caseInsensitive = function(value) { - if (isDefined(value)) - isCaseInsensitive = value; - return isCaseInsensitive; - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#strictMode - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Defines whether URLs should match trailing slashes, or not (the default behavior). - * - * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`. - * @returns {boolean} the current value of strictMode - */ - this.strictMode = function(value) { - if (isDefined(value)) - isStrictMode = value; - return isStrictMode; - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Sets the default behavior when generating or matching URLs with default parameter values. - * - * @param {string} value A string that defines the default parameter URL squashing behavior. - * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL - * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the - * parameter is surrounded by slashes, squash (remove) one slash from the URL - * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) - * the parameter value from the URL and replace it with this string. - */ - this.defaultSquashPolicy = function(value) { - if (!isDefined(value)) return defaultSquashPolicy; - if (value !== true && value !== false && !isString(value)) - throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string"); - defaultSquashPolicy = value; - return value; - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#compile - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern. - * - * @param {string} pattern The URL pattern. - * @param {Object} config The config object hash. - * @returns {UrlMatcher} The UrlMatcher. - */ - this.compile = function (pattern, config) { - return new UrlMatcher(pattern, extend(getDefaultConfig(), config)); - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#isMatcher - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Returns true if the specified object is a `UrlMatcher`, or false otherwise. - * - * @param {Object} object The object to perform the type check against. - * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by - * implementing all the same methods. - */ - this.isMatcher = function (o) { - if (!isObject(o)) return false; - var result = true; - - forEach(UrlMatcher.prototype, function(val, name) { - if (isFunction(val)) { - result = result && (isDefined(o[name]) && isFunction(o[name])); - } - }); - return result; - }; - - /** - * @ngdoc function - * @name ui.router.util.$urlMatcherFactory#type - * @methodOf ui.router.util.$urlMatcherFactory - * - * @description - * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to - * generate URLs with typed parameters. - * - * @param {string} name The type name. - * @param {Object|Function} definition The type definition. See - * {@link ui.router.util.type:Type `Type`} for information on the values accepted. - * @param {Object|Function} definitionFn (optional) A function that is injected before the app - * runtime starts. The result of this function is merged into the existing `definition`. - * See {@link ui.router.util.type:Type `Type`} for information on the values accepted. - * - * @returns {Object} Returns `$urlMatcherFactoryProvider`. - * - * @example - * This is a simple example of a custom type that encodes and decodes items from an - * array, using the array index as the URL-encoded value: - * - *
          -   * var list = ['John', 'Paul', 'George', 'Ringo'];
          -   *
          -   * $urlMatcherFactoryProvider.type('listItem', {
          +        var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
          +            string: {
          +                encode: valToString,
          +                decode: valFromString,
          +                is: regexpMatches,
          +                pattern: /[^/]*/
          +            },
          +            int: {
          +                encode: valToString,
          +                decode: function (val) {
          +                    return parseInt(val, 10);
          +                },
          +                is: function (val) {
          +                    return isDefined(val) && this.decode(val.toString()) === val;
          +                },
          +                pattern: /\d+/
          +            },
          +            bool: {
          +                encode: function (val) {
          +                    return val ? 1 : 0;
          +                },
          +                decode: function (val) {
          +                    return parseInt(val, 10) !== 0;
          +                },
          +                is: function (val) {
          +                    return val === true || val === false;
          +                },
          +                pattern: /0|1/
          +            },
          +            date: {
          +                encode: function (val) {
          +                    if (!this.is(val))
          +                        return undefined;
          +                    return [val.getFullYear(),
          +                        ('0' + (val.getMonth() + 1)).slice(-2),
          +                        ('0' + val.getDate()).slice(-2)
          +                    ].join("-");
          +                },
          +                decode: function (val) {
          +                    if (this.is(val)) return val;
          +                    var match = this.capture.exec(val);
          +                    return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
          +                },
          +                is: function (val) {
          +                    return val instanceof Date && !isNaN(val.valueOf());
          +                },
          +                equals: function (a, b) {
          +                    return this.is(a) && this.is(b) && a.toISOString() === b.toISOString();
          +                },
          +                pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
          +                capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
          +            },
          +            json: {
          +                encode: angular.toJson,
          +                decode: angular.fromJson,
          +                is: angular.isObject,
          +                equals: angular.equals,
          +                pattern: /[^/]*/
          +            },
          +            any: { // does not encode/decode
          +                encode: angular.identity,
          +                decode: angular.identity,
          +                is: angular.identity,
          +                equals: angular.equals,
          +                pattern: /.*/
          +            }
          +        };
          +
          +        function getDefaultConfig() {
          +            return {
          +                strict: isStrictMode,
          +                caseInsensitive: isCaseInsensitive
          +            };
          +        }
          +
          +        function isInjectable(value) {
          +            return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
          +        }
          +
          +        /**
          +         * [Internal] Get the default value of a parameter, which may be an injectable function.
          +         */
          +        $UrlMatcherFactory.$$getDefaultValue = function (config) {
          +            if (!isInjectable(config.value)) return config.value;
          +            if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
          +            return injector.invoke(config.value);
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#caseInsensitive
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Defines whether URL matching should be case sensitive (the default behavior), or not.
          +         *
          +         * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
          +         * @returns {boolean} the current value of caseInsensitive
          +         */
          +        this.caseInsensitive = function (value) {
          +            if (isDefined(value))
          +                isCaseInsensitive = value;
          +            return isCaseInsensitive;
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#strictMode
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Defines whether URLs should match trailing slashes, or not (the default behavior).
          +         *
          +         * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
          +         * @returns {boolean} the current value of strictMode
          +         */
          +        this.strictMode = function (value) {
          +            if (isDefined(value))
          +                isStrictMode = value;
          +            return isStrictMode;
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Sets the default behavior when generating or matching URLs with default parameter values.
          +         *
          +         * @param {string} value A string that defines the default parameter URL squashing behavior.
          +         *    `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
          +         *    `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
          +         *             parameter is surrounded by slashes, squash (remove) one slash from the URL
          +         *    any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
          +         *             the parameter value from the URL and replace it with this string.
          +         */
          +        this.defaultSquashPolicy = function (value) {
          +            if (!isDefined(value)) return defaultSquashPolicy;
          +            if (value !== true && value !== false && !isString(value))
          +                throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
          +            defaultSquashPolicy = value;
          +            return value;
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#compile
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
          +         *
          +         * @param {string} pattern  The URL pattern.
          +         * @param {Object} config  The config object hash.
          +         * @returns {UrlMatcher}  The UrlMatcher.
          +         */
          +        this.compile = function (pattern, config) {
          +            return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#isMatcher
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
          +         *
          +         * @param {Object} object  The object to perform the type check against.
          +         * @returns {Boolean}  Returns `true` if the object matches the `UrlMatcher` interface, by
          +         *          implementing all the same methods.
          +         */
          +        this.isMatcher = function (o) {
          +            if (!isObject(o)) return false;
          +            var result = true;
          +
          +            forEach(UrlMatcher.prototype, function (val, name) {
          +                if (isFunction(val)) {
          +                    result = result && (isDefined(o[name]) && isFunction(o[name]));
          +                }
          +            });
          +            return result;
          +        };
          +
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.util.$urlMatcherFactory#type
          +         * @methodOf ui.router.util.$urlMatcherFactory
          +         *
          +         * @description
          +         * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
          +         * generate URLs with typed parameters.
          +         *
          +         * @param {string} name  The type name.
          +         * @param {Object|Function} definition   The type definition. See
          +         *        {@link ui.router.util.type:Type `Type`} for information on the values accepted.
          +         * @param {Object|Function} definitionFn (optional) A function that is injected before the app
          +         *        runtime starts.  The result of this function is merged into the existing `definition`.
          +         *        See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
          +         *
          +         * @returns {Object}  Returns `$urlMatcherFactoryProvider`.
          +         *
          +         * @example
          +         * This is a simple example of a custom type that encodes and decodes items from an
          +         * array, using the array index as the URL-encoded value:
          +         *
          +         * 
          +         * var list = ['John', 'Paul', 'George', 'Ringo'];
          +         *
          +         * $urlMatcherFactoryProvider.type('listItem', {
              *   encode: function(item) {
              *     // Represent the list item in the URL using its corresponding index
              *     return list.indexOf(item);
          @@ -1448,29 +1505,29 @@ function $UrlMatcherFactory() {
              *     return list.indexOf(item) > -1;
              *   }
              * });
          -   *
          -   * $stateProvider.state('list', {
          +         *
          +         * $stateProvider.state('list', {
              *   url: "/list/{item:listItem}",
              *   controller: function($scope, $stateParams) {
              *     console.log($stateParams.item);
              *   }
              * });
          -   *
          -   * // ...
          -   *
          -   * // Changes URL to '/list/3', logs "Ringo" to the console
          -   * $state.go('list', { item: "Ringo" });
          -   * 
          - * - * This is a more complex example of a type that relies on dependency injection to - * interact with services, and uses the parameter name from the URL to infer how to - * handle encoding and decoding parameter values: - * - *
          -   * // Defines a custom type that gets a value from a service,
          -   * // where each service gets different types of values from
          -   * // a backend API:
          -   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
          +         *
          +         * // ...
          +         *
          +         * // Changes URL to '/list/3', logs "Ringo" to the console
          +         * $state.go('list', { item: "Ringo" });
          +         * 
          + * + * This is a more complex example of a type that relies on dependency injection to + * interact with services, and uses the parameter name from the URL to infer how to + * handle encoding and decoding parameter values: + * + *
          +         * // Defines a custom type that gets a value from a service,
          +         * // where each service gets different types of values from
          +         * // a backend API:
          +         * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
              *
              *   // Matches up services to URL parameter names
              *   var services = {
          @@ -1499,10 +1556,10 @@ function $UrlMatcherFactory() {
              *     }
              *   };
              * });
          -   *
          -   * // In a config() block, you can then attach URLs with
          -   * // type-annotated parameters:
          -   * $stateProvider.state('users', {
          +         *
          +         * // In a config() block, you can then attach URLs with
          +         * // type-annotated parameters:
          +         * $stateProvider.state('users', {
              *   url: "/users",
              *   // ...
              * }).state('users.item', {
          @@ -1513,245 +1570,267 @@ function $UrlMatcherFactory() {
              *   },
              *   // ...
              * });
          -   * 
          - */ - this.type = function (name, definition, definitionFn) { - if (!isDefined(definition)) return $types[name]; - if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined."); - - $types[name] = new Type(extend({ name: name }, definition)); - if (definitionFn) { - typeQueue.push({ name: name, def: definitionFn }); - if (!enqueue) flushTypeQueue(); - } - return this; - }; - - // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s - function flushTypeQueue() { - while(typeQueue.length) { - var type = typeQueue.shift(); - if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime."); - angular.extend($types[type.name], injector.invoke(type.def)); - } - } - - // Register default types. Store them in the prototype of $types. - forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); }); - $types = inherit($types, {}); - - /* No need to document $get, since it returns this */ - this.$get = ['$injector', function ($injector) { - injector = $injector; - enqueue = false; - flushTypeQueue(); - - forEach(defaultTypes, function(type, name) { - if (!$types[name]) $types[name] = new Type(type); - }); - return this; - }]; - - this.Param = function Param(id, type, config, location) { - var self = this; - config = unwrapShorthand(config); - type = getType(config, type, location); - var arrayMode = getArrayMode(); - type = arrayMode ? type.$asArray(arrayMode, location === "search") : type; - if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined) - config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to "" - var isOptional = config.value !== undefined; - var squash = getSquashPolicy(config, isOptional); - var replace = getReplace(config, arrayMode, isOptional, squash); - - function unwrapShorthand(config) { - var keys = isObject(config) ? objectKeys(config) : []; - var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 && - indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1; - if (isShorthand) config = { value: config }; - config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; }; - return config; - } + *
          + */ + this.type = function (name, definition, definitionFn) { + if (!isDefined(definition)) return $types[name]; + if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined."); + + $types[name] = new Type(extend({name: name}, definition)); + if (definitionFn) { + typeQueue.push({name: name, def: definitionFn}); + if (!enqueue) flushTypeQueue(); + } + return this; + }; - function getType(config, urlType, location) { - if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations."); - if (urlType) return urlType; - if (!config.type) return (location === "config" ? $types.any : $types.string); - return config.type instanceof Type ? config.type : new Type(config.type); - } + // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s + function flushTypeQueue() { + while (typeQueue.length) { + var type = typeQueue.shift(); + if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime."); + angular.extend($types[type.name], injector.invoke(type.def)); + } + } - // array config: param name (param[]) overrides default settings. explicit config overrides param name. - function getArrayMode() { - var arrayDefaults = { array: (location === "search" ? "auto" : false) }; - var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; - return extend(arrayDefaults, arrayParamNomenclature, config).array; - } + // Register default types. Store them in the prototype of $types. + forEach(defaultTypes, function (type, name) { + $types[name] = new Type(extend({name: name}, type)); + }); + $types = inherit($types, {}); - /** - * returns false, true, or the squash value to indicate the "default parameter url squash policy". - */ - function getSquashPolicy(config, isOptional) { - var squash = config.squash; - if (!isOptional || squash === false) return false; - if (!isDefined(squash) || squash == null) return defaultSquashPolicy; - if (squash === true || isString(squash)) return squash; - throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); - } + /* No need to document $get, since it returns this */ + this.$get = ['$injector', function ($injector) { + injector = $injector; + enqueue = false; + flushTypeQueue(); - function getReplace(config, arrayMode, isOptional, squash) { - var replace, configuredKeys, defaultPolicy = [ - { from: "", to: (isOptional || arrayMode ? undefined : "") }, - { from: null, to: (isOptional || arrayMode ? undefined : "") } - ]; - replace = isArray(config.replace) ? config.replace : []; - if (isString(squash)) - replace.push({ from: squash, to: undefined }); - configuredKeys = map(replace, function(item) { return item.from; } ); - return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace); - } + forEach(defaultTypes, function (type, name) { + if (!$types[name]) $types[name] = new Type(type); + }); + return this; + }]; - /** - * [Internal] Get the default value of a parameter, which may be an injectable function. - */ - function $$getDefaultValue() { - if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); - return injector.invoke(config.$$fn); + this.Param = function Param(id, type, config, location) { + var self = this; + config = unwrapShorthand(config); + type = getType(config, type, location); + var arrayMode = getArrayMode(); + type = arrayMode ? type.$asArray(arrayMode, location === "search") : type; + if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined) + config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to "" + var isOptional = config.value !== undefined; + var squash = getSquashPolicy(config, isOptional); + var replace = getReplace(config, arrayMode, isOptional, squash); + + function unwrapShorthand(config) { + var keys = isObject(config) ? objectKeys(config) : []; + var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 && + indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1; + if (isShorthand) config = {value: config}; + config.$$fn = isInjectable(config.value) ? config.value : function () { + return config.value; + }; + return config; + } + + function getType(config, urlType, location) { + if (config.type && urlType) throw new Error("Param '" + id + "' has two type configurations."); + if (urlType) return urlType; + if (!config.type) return (location === "config" ? $types.any : $types.string); + return config.type instanceof Type ? config.type : new Type(config.type); + } + + // array config: param name (param[]) overrides default settings. explicit config overrides param name. + function getArrayMode() { + var arrayDefaults = {array: (location === "search" ? "auto" : false)}; + var arrayParamNomenclature = id.match(/\[\]$/) ? {array: true} : {}; + return extend(arrayDefaults, arrayParamNomenclature, config).array; + } + + /** + * returns false, true, or the squash value to indicate the "default parameter url squash policy". + */ + function getSquashPolicy(config, isOptional) { + var squash = config.squash; + if (!isOptional || squash === false) return false; + if (!isDefined(squash) || squash == null) return defaultSquashPolicy; + if (squash === true || isString(squash)) return squash; + throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); + } + + function getReplace(config, arrayMode, isOptional, squash) { + var replace, configuredKeys, defaultPolicy = [ + {from: "", to: (isOptional || arrayMode ? undefined : "")}, + {from: null, to: (isOptional || arrayMode ? undefined : "")} + ]; + replace = isArray(config.replace) ? config.replace : []; + if (isString(squash)) + replace.push({from: squash, to: undefined}); + configuredKeys = map(replace, function (item) { + return item.from; + }); + return filter(defaultPolicy, function (item) { + return indexOf(configuredKeys, item.from) === -1; + }).concat(replace); + } + + /** + * [Internal] Get the default value of a parameter, which may be an injectable function. + */ + function $$getDefaultValue() { + if (!injector) throw new Error("Injectable functions cannot be called at configuration time"); + return injector.invoke(config.$$fn); + } + + /** + * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the + * default value, which may be the result of an injectable function. + */ + function $value(value) { + function hasReplaceVal(val) { + return function (obj) { + return obj.from === val; + }; + } + + function $replace(value) { + var replacement = map(filter(self.replace, hasReplaceVal(value)), function (obj) { + return obj.to; + }); + return replacement.length ? replacement[0] : value; + } + + value = $replace(value); + return isDefined(value) ? self.type.decode(value) : $$getDefaultValue(); + } + + function toString() { + return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; + } + + extend(this, { + id: id, + type: type, + location: location, + array: arrayMode, + squash: squash, + replace: replace, + isOptional: isOptional, + value: $value, + dynamic: undefined, + config: config, + toString: toString + }); + }; + + function ParamSet(params) { + extend(this, params || {}); + } + + ParamSet.prototype = { + $$new: function () { + return inherit(this, extend(new ParamSet(), {$$parent: this})); + }, + $$keys: function () { + var keys = [], chain = [], parent = this, + ignore = objectKeys(ParamSet.prototype); + while (parent) { + chain.push(parent); + parent = parent.$$parent; + } + chain.reverse(); + forEach(chain, function (paramset) { + forEach(objectKeys(paramset), function (key) { + if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key); + }); + }); + return keys; + }, + $$values: function (paramValues) { + var values = {}, self = this; + forEach(self.$$keys(), function (key) { + values[key] = self[key].value(paramValues && paramValues[key]); + }); + return values; + }, + $$equals: function (paramValues1, paramValues2) { + var equal = true, self = this; + forEach(self.$$keys(), function (key) { + var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key]; + if (!self[key].type.equals(left, right)) equal = false; + }); + return equal; + }, + $$validates: function $$validate(paramValues) { + var result = true, isOptional, val, param, self = this; + + forEach(this.$$keys(), function (key) { + param = self[key]; + val = paramValues[key]; + isOptional = !val && param.isOptional; + result = result && (isOptional || !!param.type.is(val)); + }); + return result; + }, + $$parent: undefined + }; + + this.ParamSet = ParamSet; } +// Register as a provider so it's available to other providers + angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory); + angular.module('ui.router.util').run(['$urlMatcherFactory', function ($urlMatcherFactory) { + }]); + /** - * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the - * default value, which may be the result of an injectable function. + * @ngdoc object + * @name ui.router.router.$urlRouterProvider + * + * @requires ui.router.util.$urlMatcherFactoryProvider + * @requires $locationProvider + * + * @description + * `$urlRouterProvider` has the responsibility of watching `$location`. + * When `$location` changes it runs through a list of rules one by one until a + * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify + * a url in a state configuration. All urls are compiled into a UrlMatcher object. + * + * There are several methods on `$urlRouterProvider` that make it useful to use directly + * in your module config. */ - function $value(value) { - function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; } - function $replace(value) { - var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; }); - return replacement.length ? replacement[0] : value; - } - value = $replace(value); - return isDefined(value) ? self.type.decode(value) : $$getDefaultValue(); - } - - function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; } - - extend(this, { - id: id, - type: type, - location: location, - array: arrayMode, - squash: squash, - replace: replace, - isOptional: isOptional, - value: $value, - dynamic: undefined, - config: config, - toString: toString - }); - }; - - function ParamSet(params) { - extend(this, params || {}); - } - - ParamSet.prototype = { - $$new: function() { - return inherit(this, extend(new ParamSet(), { $$parent: this})); - }, - $$keys: function () { - var keys = [], chain = [], parent = this, - ignore = objectKeys(ParamSet.prototype); - while (parent) { chain.push(parent); parent = parent.$$parent; } - chain.reverse(); - forEach(chain, function(paramset) { - forEach(objectKeys(paramset), function(key) { - if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key); - }); - }); - return keys; - }, - $$values: function(paramValues) { - var values = {}, self = this; - forEach(self.$$keys(), function(key) { - values[key] = self[key].value(paramValues && paramValues[key]); - }); - return values; - }, - $$equals: function(paramValues1, paramValues2) { - var equal = true, self = this; - forEach(self.$$keys(), function(key) { - var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key]; - if (!self[key].type.equals(left, right)) equal = false; - }); - return equal; - }, - $$validates: function $$validate(paramValues) { - var result = true, isOptional, val, param, self = this; - - forEach(this.$$keys(), function(key) { - param = self[key]; - val = paramValues[key]; - isOptional = !val && param.isOptional; - result = result && (isOptional || !!param.type.is(val)); - }); - return result; - }, - $$parent: undefined - }; - - this.ParamSet = ParamSet; -} + $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider']; + function $UrlRouterProvider($locationProvider, $urlMatcherFactory) { + var rules = [], otherwise = null, interceptDeferred = false, listener; + + // Returns a string that is a prefix of all strings matching the RegExp + function regExpPrefix(re) { + var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); + return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; + } -// Register as a provider so it's available to other providers -angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory); -angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]); + // Interpolates matched values into a String.replace()-style pattern + function interpolate(pattern, match) { + return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { + return match[what === '$' ? 0 : Number(what)]; + }); + } -/** - * @ngdoc object - * @name ui.router.router.$urlRouterProvider - * - * @requires ui.router.util.$urlMatcherFactoryProvider - * @requires $locationProvider - * - * @description - * `$urlRouterProvider` has the responsibility of watching `$location`. - * When `$location` changes it runs through a list of rules one by one until a - * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify - * a url in a state configuration. All urls are compiled into a UrlMatcher object. - * - * There are several methods on `$urlRouterProvider` that make it useful to use directly - * in your module config. - */ -$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider']; -function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) { - var rules = [], otherwise = null, interceptDeferred = false, listener; - - // Returns a string that is a prefix of all strings matching the RegExp - function regExpPrefix(re) { - var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); - return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; - } - - // Interpolates matched values into a String.replace()-style pattern - function interpolate(pattern, match) { - return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { - return match[what === '$' ? 0 : Number(what)]; - }); - } - - /** - * @ngdoc function - * @name ui.router.router.$urlRouterProvider#rule - * @methodOf ui.router.router.$urlRouterProvider - * - * @description - * Defines rules that are used by `$urlRouterProvider` to find matches for - * specific URLs. - * - * @example - *
          -   * var app = angular.module('app', ['ui.router.router']);
          -   *
          -   * app.config(function ($urlRouterProvider) {
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.router.$urlRouterProvider#rule
          +         * @methodOf ui.router.router.$urlRouterProvider
          +         *
          +         * @description
          +         * Defines rules that are used by `$urlRouterProvider` to find matches for
          +         * specific URLs.
          +         *
          +         * @example
          +         * 
          +         * var app = angular.module('app', ['ui.router.router']);
          +         *
          +         * app.config(function ($urlRouterProvider) {
              *   // Here's an example of how you might allow case insensitive urls
              *   $urlRouterProvider.rule(function ($injector, $location) {
              *     var path = $location.path(),
          @@ -1762,32 +1841,32 @@ function $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {
              *     }
              *   });
              * });
          -   * 
          - * - * @param {object} rule Handler function that takes `$injector` and `$location` - * services as arguments. You can use them to return a valid path as a string. - * - * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance - */ - this.rule = function (rule) { - if (!isFunction(rule)) throw new Error("'rule' must be a function"); - rules.push(rule); - return this; - }; - - /** - * @ngdoc object - * @name ui.router.router.$urlRouterProvider#otherwise - * @methodOf ui.router.router.$urlRouterProvider - * - * @description - * Defines a path that is used when an invalid route is requested. - * - * @example - *
          -   * var app = angular.module('app', ['ui.router.router']);
          -   *
          -   * app.config(function ($urlRouterProvider) {
          +         * 
          + * + * @param {object} rule Handler function that takes `$injector` and `$location` + * services as arguments. You can use them to return a valid path as a string. + * + * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance + */ + this.rule = function (rule) { + if (!isFunction(rule)) throw new Error("'rule' must be a function"); + rules.push(rule); + return this; + }; + + /** + * @ngdoc object + * @name ui.router.router.$urlRouterProvider#otherwise + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Defines a path that is used when an invalid route is requested. + * + * @example + *
          +         * var app = angular.module('app', ['ui.router.router']);
          +         *
          +         * app.config(function ($urlRouterProvider) {
              *   // if the path doesn't match any of the urls you configured
              *   // otherwise will take care of routing the user to the
              *   // specified url
          @@ -1798,56 +1877,58 @@ function $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {
              *     return '/a/valid/url';
              *   });
              * });
          -   * 
          - * - * @param {string|object} rule The url path you want to redirect to or a function - * rule that returns the url path. The function version is passed two params: - * `$injector` and `$location` services, and must return a url string. - * - * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance - */ - this.otherwise = function (rule) { - if (isString(rule)) { - var redirect = rule; - rule = function () { return redirect; }; - } - else if (!isFunction(rule)) throw new Error("'rule' must be a function"); - otherwise = rule; - return this; - }; - - - function handleIfMatch($injector, handler, match) { - if (!match) return false; - var result = $injector.invoke(handler, handler, { $match: match }); - return isDefined(result) ? result : true; - } - - /** - * @ngdoc function - * @name ui.router.router.$urlRouterProvider#when - * @methodOf ui.router.router.$urlRouterProvider - * - * @description - * Registers a handler for a given url matching. if handle is a string, it is - * treated as a redirect, and is interpolated according to the syntax of match - * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). - * - * If the handler is a function, it is injectable. It gets invoked if `$location` - * matches. You have the option of inject the match object as `$match`. - * - * The handler can return - * - * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` - * will continue trying to find another one that matches. - * - **string** which is treated as a redirect and passed to `$location.url()` - * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. - * - * @example - *
          -   * var app = angular.module('app', ['ui.router.router']);
          -   *
          -   * app.config(function ($urlRouterProvider) {
          +         * 
          + * + * @param {string|object} rule The url path you want to redirect to or a function + * rule that returns the url path. The function version is passed two params: + * `$injector` and `$location` services, and must return a url string. + * + * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance + */ + this.otherwise = function (rule) { + if (isString(rule)) { + var redirect = rule; + rule = function () { + return redirect; + }; + } + else if (!isFunction(rule)) throw new Error("'rule' must be a function"); + otherwise = rule; + return this; + }; + + + function handleIfMatch($injector, handler, match) { + if (!match) return false; + var result = $injector.invoke(handler, handler, {$match: match}); + return isDefined(result) ? result : true; + } + + /** + * @ngdoc function + * @name ui.router.router.$urlRouterProvider#when + * @methodOf ui.router.router.$urlRouterProvider + * + * @description + * Registers a handler for a given url matching. if handle is a string, it is + * treated as a redirect, and is interpolated according to the syntax of match + * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise). + * + * If the handler is a function, it is injectable. It gets invoked if `$location` + * matches. You have the option of inject the match object as `$match`. + * + * The handler can return + * + * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` + * will continue trying to find another one that matches. + * - **string** which is treated as a redirect and passed to `$location.url()` + * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. + * + * @example + *
          +         * var app = angular.module('app', ['ui.router.router']);
          +         *
          +         * app.config(function ($urlRouterProvider) {
              *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {
              *     if ($state.$current.navigable !== state ||
              *         !equalForKeys($match, $stateParams) {
          @@ -1855,72 +1936,76 @@ function $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {
              *     }
              *   });
              * });
          -   * 
          - * - * @param {string|object} what The incoming path that you want to redirect. - * @param {string|object} handler The path you want to redirect your user to. - */ - this.when = function (what, handler) { - var redirect, handlerIsString = isString(handler); - if (isString(what)) what = $urlMatcherFactory.compile(what); - - if (!handlerIsString && !isFunction(handler) && !isArray(handler)) - throw new Error("invalid 'handler' in when()"); - - var strategies = { - matcher: function (what, handler) { - if (handlerIsString) { - redirect = $urlMatcherFactory.compile(handler); - handler = ['$match', function ($match) { return redirect.format($match); }]; - } - return extend(function ($injector, $location) { - return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); - }, { - prefix: isString(what.prefix) ? what.prefix : '' - }); - }, - regex: function (what, handler) { - if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); - - if (handlerIsString) { - redirect = handler; - handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; - } - return extend(function ($injector, $location) { - return handleIfMatch($injector, handler, what.exec($location.path())); - }, { - prefix: regExpPrefix(what) - }); - } - }; - - var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; - - for (var n in check) { - if (check[n]) return this.rule(strategies[n](what, handler)); - } - - throw new Error("invalid 'what' in when()"); - }; + *
          + * + * @param {string|object} what The incoming path that you want to redirect. + * @param {string|object} handler The path you want to redirect your user to. + */ + this.when = function (what, handler) { + var redirect, handlerIsString = isString(handler); + if (isString(what)) what = $urlMatcherFactory.compile(what); + + if (!handlerIsString && !isFunction(handler) && !isArray(handler)) + throw new Error("invalid 'handler' in when()"); + + var strategies = { + matcher: function (what, handler) { + if (handlerIsString) { + redirect = $urlMatcherFactory.compile(handler); + handler = ['$match', function ($match) { + return redirect.format($match); + }]; + } + return extend(function ($injector, $location) { + return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); + }, { + prefix: isString(what.prefix) ? what.prefix : '' + }); + }, + regex: function (what, handler) { + if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); + + if (handlerIsString) { + redirect = handler; + handler = ['$match', function ($match) { + return interpolate(redirect, $match); + }]; + } + return extend(function ($injector, $location) { + return handleIfMatch($injector, handler, what.exec($location.path())); + }, { + prefix: regExpPrefix(what) + }); + } + }; + + var check = {matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp}; + + for (var n in check) { + if (check[n]) return this.rule(strategies[n](what, handler)); + } + + throw new Error("invalid 'what' in when()"); + }; - /** - * @ngdoc function - * @name ui.router.router.$urlRouterProvider#deferIntercept - * @methodOf ui.router.router.$urlRouterProvider - * - * @description - * Disables (or enables) deferring location change interception. - * - * If you wish to customize the behavior of syncing the URL (for example, if you wish to - * defer a transition but maintain the current URL), call this method at configuration time. - * Then, at run time, call `$urlRouter.listen()` after you have configured your own - * `$locationChangeSuccess` event handler. - * - * @example - *
          -   * var app = angular.module('app', ['ui.router.router']);
          -   *
          -   * app.config(function ($urlRouterProvider) {
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.router.$urlRouterProvider#deferIntercept
          +         * @methodOf ui.router.router.$urlRouterProvider
          +         *
          +         * @description
          +         * Disables (or enables) deferring location change interception.
          +         *
          +         * If you wish to customize the behavior of syncing the URL (for example, if you wish to
          +         * defer a transition but maintain the current URL), call this method at configuration time.
          +         * Then, at run time, call `$urlRouter.listen()` after you have configured your own
          +         * `$locationChangeSuccess` event handler.
          +         *
          +         * @example
          +         * 
          +         * var app = angular.module('app', ['ui.router.router']);
          +         *
          +         * app.config(function ($urlRouterProvider) {
              *
              *   // Prevent $urlRouter from automatically intercepting URL changes;
              *   // this allows you to configure custom behavior in between
          @@ -1946,87 +2031,88 @@ function $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {
              *   // Configures $urlRouter's listener *after* your custom listener
              *   $urlRouter.listen();
              * });
          -   * 
          - * - * @param {boolean} defer Indicates whether to defer location change interception. Passing - no parameter is equivalent to `true`. - */ - this.deferIntercept = function (defer) { - if (defer === undefined) defer = true; - interceptDeferred = defer; - }; - - /** - * @ngdoc object - * @name ui.router.router.$urlRouter - * - * @requires $location - * @requires $rootScope - * @requires $injector - * @requires $browser - * - * @description - * - */ - this.$get = $get; - $get.$inject = ['$location', '$rootScope', '$injector', '$browser']; - function $get( $location, $rootScope, $injector, $browser) { - - var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl; - - function appendBasePath(url, isHtml5, absolute) { - if (baseHref === '/') return url; - if (isHtml5) return baseHref.slice(0, -1) + url; - if (absolute) return baseHref.slice(1) + url; - return url; - } - - // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree - function update(evt) { - if (evt && evt.defaultPrevented) return; - var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl; - lastPushedUrl = undefined; - if (ignoreUpdate) return true; - - function check(rule) { - var handled = rule($injector, $location); - - if (!handled) return false; - if (isString(handled)) $location.replace().url(handled); - return true; - } - var n = rules.length, i; - - for (i = 0; i < n; i++) { - if (check(rules[i])) return; - } - // always check otherwise last to allow dynamic updates to the set of rules - if (otherwise) check(otherwise); - } - - function listen() { - listener = listener || $rootScope.$on('$locationChangeSuccess', update); - return listener; - } + *
          + * + * @param {boolean} defer Indicates whether to defer location change interception. Passing + no parameter is equivalent to `true`. + */ + this.deferIntercept = function (defer) { + if (defer === undefined) defer = true; + interceptDeferred = defer; + }; - if (!interceptDeferred) listen(); - - return { - /** - * @ngdoc function - * @name ui.router.router.$urlRouter#sync - * @methodOf ui.router.router.$urlRouter - * - * @description - * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. - * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, - * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed - * with the transition by calling `$urlRouter.sync()`. - * - * @example - *
          -       * angular.module('app', ['ui.router'])
          -       *   .run(function($rootScope, $urlRouter) {
          +        /**
          +         * @ngdoc object
          +         * @name ui.router.router.$urlRouter
          +         *
          +         * @requires $location
          +         * @requires $rootScope
          +         * @requires $injector
          +         * @requires $browser
          +         *
          +         * @description
          +         *
          +         */
          +        this.$get = $get;
          +        $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
          +        function $get($location, $rootScope, $injector, $browser) {
          +
          +            var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
          +
          +            function appendBasePath(url, isHtml5, absolute) {
          +                if (baseHref === '/') return url;
          +                if (isHtml5) return baseHref.slice(0, -1) + url;
          +                if (absolute) return baseHref.slice(1) + url;
          +                return url;
          +            }
          +
          +            // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
          +            function update(evt) {
          +                if (evt && evt.defaultPrevented) return;
          +                var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
          +                lastPushedUrl = undefined;
          +                if (ignoreUpdate) return true;
          +
          +                function check(rule) {
          +                    var handled = rule($injector, $location);
          +
          +                    if (!handled) return false;
          +                    if (isString(handled)) $location.replace().url(handled);
          +                    return true;
          +                }
          +
          +                var n = rules.length, i;
          +
          +                for (i = 0; i < n; i++) {
          +                    if (check(rules[i])) return;
          +                }
          +                // always check otherwise last to allow dynamic updates to the set of rules
          +                if (otherwise) check(otherwise);
          +            }
          +
          +            function listen() {
          +                listener = listener || $rootScope.$on('$locationChangeSuccess', update);
          +                return listener;
          +            }
          +
          +            if (!interceptDeferred) listen();
          +
          +            return {
          +                /**
          +                 * @ngdoc function
          +                 * @name ui.router.router.$urlRouter#sync
          +                 * @methodOf ui.router.router.$urlRouter
          +                 *
          +                 * @description
          +                 * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
          +                 * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
          +                 * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
          +                 * with the transition by calling `$urlRouter.sync()`.
          +                 *
          +                 * @example
          +                 * 
          +                 * angular.module('app', ['ui.router'])
          +                 *   .run(function($rootScope, $urlRouter) {
                  *     $rootScope.$on('$locationChangeSuccess', function(evt) {
                  *       // Halt state change from even starting
                  *       evt.preventDefault();
          @@ -2036,399 +2122,401 @@ function $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {
                  *       if (meetsRequirement) $urlRouter.sync();
                  *     });
                  * });
          -       * 
          - */ - sync: function() { - update(); - }, - - listen: function() { - return listen(); - }, - - update: function(read) { - if (read) { - location = $location.url(); - return; - } - if ($location.url() === location) return; - - $location.url(location); - $location.replace(); - }, - - push: function(urlMatcher, params, options) { - $location.url(urlMatcher.format(params || {})); - lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined; - if (options && options.replace) $location.replace(); - }, - - /** - * @ngdoc function - * @name ui.router.router.$urlRouter#href - * @methodOf ui.router.router.$urlRouter - * - * @description - * A URL generation method that returns the compiled URL for a given - * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. - * - * @example - *
          -       * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
          +                 * 
          + */ + sync: function () { + update(); + }, + + listen: function () { + return listen(); + }, + + update: function (read) { + if (read) { + location = $location.url(); + return; + } + if ($location.url() === location) return; + + $location.url(location); + $location.replace(); + }, + + push: function (urlMatcher, params, options) { + $location.url(urlMatcher.format(params || {})); + lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined; + if (options && options.replace) $location.replace(); + }, + + /** + * @ngdoc function + * @name ui.router.router.$urlRouter#href + * @methodOf ui.router.router.$urlRouter + * + * @description + * A URL generation method that returns the compiled URL for a given + * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters. + * + * @example + *
          +                 * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
                  *   person: "bob"
                  * });
          -       * // $bob == "/about/bob";
          -       * 
          - * - * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. - * @param {object=} params An object of parameter values to fill the matcher's required parameters. - * @param {object=} options Options object. The options are: - * - * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". - * - * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` - */ - href: function(urlMatcher, params, options) { - if (!urlMatcher.validates(params)) return null; - - var isHtml5 = $locationProvider.html5Mode(); - if (angular.isObject(isHtml5)) { - isHtml5 = isHtml5.enabled; - } - - var url = urlMatcher.format(params); - options = options || {}; - - if (!isHtml5 && url !== null) { - url = "#" + $locationProvider.hashPrefix() + url; - } - url = appendBasePath(url, isHtml5, options.absolute); - - if (!options.absolute || !url) { - return url; - } - - var slash = (!isHtml5 && url ? '/' : ''), port = $location.port(); - port = (port === 80 || port === 443 ? '' : ':' + port); - - return [$location.protocol(), '://', $location.host(), port, slash, url].join(''); - } - }; - } -} - -angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); - -/** - * @ngdoc object - * @name ui.router.state.$stateProvider - * - * @requires ui.router.router.$urlRouterProvider - * @requires ui.router.util.$urlMatcherFactoryProvider - * - * @description - * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely - * on state. - * - * A state corresponds to a "place" in the application in terms of the overall UI and - * navigation. A state describes (via the controller / template / view properties) what - * the UI looks like and does at that place. - * - * States often have things in common, and the primary way of factoring out these - * commonalities in this model is via the state hierarchy, i.e. parent/child states aka - * nested states. - * - * The `$stateProvider` provides interfaces to declare these states for your app. - */ -$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider']; -function $StateProvider( $urlRouterProvider, $urlMatcherFactory) { - - var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; - - // Builds state properties from definition passed to registerState() - var stateBuilder = { - - // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. - // state.children = []; - // if (parent) parent.children.push(state); - parent: function(state) { - if (isDefined(state.parent) && state.parent) return findState(state.parent); - // regex matches any valid composite state name - // would match "contact.list" but not "contacts" - var compositeName = /^(.+)\.[^.]+$/.exec(state.name); - return compositeName ? findState(compositeName[1]) : root; - }, - - // inherit 'data' from parent and override by own values (if any) - data: function(state) { - if (state.parent && state.parent.data) { - state.data = state.self.data = extend({}, state.parent.data, state.data); - } - return state.data; - }, - - // Build a URLMatcher if necessary, either via a relative or absolute URL - url: function(state) { - var url = state.url, config = { params: state.params || {} }; - - if (isString(url)) { - if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); - return (state.parent.navigable || root).url.concat(url, config); - } - - if (!url || $urlMatcherFactory.isMatcher(url)) return url; - throw new Error("Invalid url '" + url + "' in state '" + state + "'"); - }, - - // Keep track of the closest ancestor state that has a URL (i.e. is navigable) - navigable: function(state) { - return state.url ? state : (state.parent ? state.parent.navigable : null); - }, - - // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params - ownParams: function(state) { - var params = state.url && state.url.params || new $$UMFP.ParamSet(); - forEach(state.params || {}, function(config, id) { - if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); - }); - return params; - }, - - // Derive parameters for this state and ensure they're a super-set of parent's parameters - params: function(state) { - return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet(); - }, - - // If there is no explicit multi-view configuration, make one up so we don't have - // to handle both cases in the view directive later. Note that having an explicit - // 'views' property will mean the default unnamed view properties are ignored. This - // is also a good time to resolve view names to absolute names, so everything is a - // straight lookup at link time. - views: function(state) { - var views = {}; - - forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { - if (name.indexOf('@') < 0) name += '@' + state.parent.name; - views[name] = view; - }); - return views; - }, - - // Keep a full path from the root down to this state as this is needed for state activation. - path: function(state) { - return state.parent ? state.parent.path.concat(state) : []; // exclude root from path - }, - - // Speed up $state.contains() as it's used a lot - includes: function(state) { - var includes = state.parent ? extend({}, state.parent.includes) : {}; - includes[state.name] = true; - return includes; - }, - - $delegates: {} - }; - - function isRelative(stateName) { - return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; - } - - function findState(stateOrName, base) { - if (!stateOrName) return undefined; - - var isStr = isString(stateOrName), - name = isStr ? stateOrName : stateOrName.name, - path = isRelative(name); - - if (path) { - if (!base) throw new Error("No reference point given for path '" + name + "'"); - base = findState(base); - - var rel = name.split("."), i = 0, pathLength = rel.length, current = base; - - for (; i < pathLength; i++) { - if (rel[i] === "" && i === 0) { - current = base; - continue; - } - if (rel[i] === "^") { - if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); - current = current.parent; - continue; + * // $bob == "/about/bob"; + *
          + * + * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate. + * @param {object=} params An object of parameter values to fill the matcher's required parameters. + * @param {object=} options Options object. The options are: + * + * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". + * + * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` + */ + href: function (urlMatcher, params, options) { + if (!urlMatcher.validates(params)) return null; + + var isHtml5 = $locationProvider.html5Mode(); + if (angular.isObject(isHtml5)) { + isHtml5 = isHtml5.enabled; + } + + var url = urlMatcher.format(params); + options = options || {}; + + if (!isHtml5 && url !== null) { + url = "#" + $locationProvider.hashPrefix() + url; + } + url = appendBasePath(url, isHtml5, options.absolute); + + if (!options.absolute || !url) { + return url; + } + + var slash = (!isHtml5 && url ? '/' : ''), port = $location.port(); + port = (port === 80 || port === 443 ? '' : ':' + port); + + return [$location.protocol(), '://', $location.host(), port, slash, url].join(''); + } + }; } - break; - } - rel = rel.slice(i).join("."); - name = current.name + (current.name && rel ? "." : "") + rel; - } - var state = states[name]; - - if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { - return state; } - return undefined; - } - function queueState(parentName, state) { - if (!queue[parentName]) { - queue[parentName] = []; - } - queue[parentName].push(state); - } - - function flushQueuedChildren(parentName) { - var queued = queue[parentName] || []; - while(queued.length) { - registerState(queued.shift()); - } - } - - function registerState(state) { - // Wrap a new object around the state so we can store our private details easily. - state = inherit(state, { - self: state, - resolve: state.resolve || {}, - toString: function() { return this.name; } - }); - - var name = state.name; - if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); - if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined"); - - // Get parent name - var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) - : (isString(state.parent)) ? state.parent - : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name - : ''; - - // If parent is not registered yet, add state to queue and register later - if (parentName && !states[parentName]) { - return queueState(parentName, state.self); - } + angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); - for (var key in stateBuilder) { - if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); - } - states[name] = state; + /** + * @ngdoc object + * @name ui.router.state.$stateProvider + * + * @requires ui.router.router.$urlRouterProvider + * @requires ui.router.util.$urlMatcherFactoryProvider + * + * @description + * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely + * on state. + * + * A state corresponds to a "place" in the application in terms of the overall UI and + * navigation. A state describes (via the controller / template / view properties) what + * the UI looks like and does at that place. + * + * States often have things in common, and the primary way of factoring out these + * commonalities in this model is via the state hierarchy, i.e. parent/child states aka + * nested states. + * + * The `$stateProvider` provides interfaces to declare these states for your app. + */ + $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider']; + function $StateProvider($urlRouterProvider, $urlMatcherFactory) { + + var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; + + // Builds state properties from definition passed to registerState() + var stateBuilder = { + + // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. + // state.children = []; + // if (parent) parent.children.push(state); + parent: function (state) { + if (isDefined(state.parent) && state.parent) return findState(state.parent); + // regex matches any valid composite state name + // would match "contact.list" but not "contacts" + var compositeName = /^(.+)\.[^.]+$/.exec(state.name); + return compositeName ? findState(compositeName[1]) : root; + }, + + // inherit 'data' from parent and override by own values (if any) + data: function (state) { + if (state.parent && state.parent.data) { + state.data = state.self.data = extend({}, state.parent.data, state.data); + } + return state.data; + }, + + // Build a URLMatcher if necessary, either via a relative or absolute URL + url: function (state) { + var url = state.url, config = {params: state.params || {}}; + + if (isString(url)) { + if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); + return (state.parent.navigable || root).url.concat(url, config); + } + + if (!url || $urlMatcherFactory.isMatcher(url)) return url; + throw new Error("Invalid url '" + url + "' in state '" + state + "'"); + }, + + // Keep track of the closest ancestor state that has a URL (i.e. is navigable) + navigable: function (state) { + return state.url ? state : (state.parent ? state.parent.navigable : null); + }, + + // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params + ownParams: function (state) { + var params = state.url && state.url.params || new $$UMFP.ParamSet(); + forEach(state.params || {}, function (config, id) { + if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); + }); + return params; + }, + + // Derive parameters for this state and ensure they're a super-set of parent's parameters + params: function (state) { + return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet(); + }, + + // If there is no explicit multi-view configuration, make one up so we don't have + // to handle both cases in the view directive later. Note that having an explicit + // 'views' property will mean the default unnamed view properties are ignored. This + // is also a good time to resolve view names to absolute names, so everything is a + // straight lookup at link time. + views: function (state) { + var views = {}; + + forEach(isDefined(state.views) ? state.views : {'': state}, function (view, name) { + if (name.indexOf('@') < 0) name += '@' + state.parent.name; + views[name] = view; + }); + return views; + }, + + // Keep a full path from the root down to this state as this is needed for state activation. + path: function (state) { + return state.parent ? state.parent.path.concat(state) : []; // exclude root from path + }, + + // Speed up $state.contains() as it's used a lot + includes: function (state) { + var includes = state.parent ? extend({}, state.parent.includes) : {}; + includes[state.name] = true; + return includes; + }, + + $delegates: {} + }; - // Register the state in the global state list and with $urlRouter if necessary. - if (!state[abstractKey] && state.url) { - $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { - if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { - $state.transitionTo(state, $match, { inherit: true, location: false }); + function isRelative(stateName) { + return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; } - }]); - } - - // Register any queued children - flushQueuedChildren(name); - return state; - } + function findState(stateOrName, base) { + if (!stateOrName) return undefined; + + var isStr = isString(stateOrName), + name = isStr ? stateOrName : stateOrName.name, + path = isRelative(name); + + if (path) { + if (!base) throw new Error("No reference point given for path '" + name + "'"); + base = findState(base); + + var rel = name.split("."), i = 0, pathLength = rel.length, current = base; + + for (; i < pathLength; i++) { + if (rel[i] === "" && i === 0) { + current = base; + continue; + } + if (rel[i] === "^") { + if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); + current = current.parent; + continue; + } + break; + } + rel = rel.slice(i).join("."); + name = current.name + (current.name && rel ? "." : "") + rel; + } + var state = states[name]; + + if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { + return state; + } + return undefined; + } - // Checks text to see if it looks like a glob. - function isGlob (text) { - return text.indexOf('*') > -1; - } + function queueState(parentName, state) { + if (!queue[parentName]) { + queue[parentName] = []; + } + queue[parentName].push(state); + } - // Returns true if glob matches current $state name. - function doesStateMatchGlob (glob) { - var globSegments = glob.split('.'), - segments = $state.$current.name.split('.'); + function flushQueuedChildren(parentName) { + var queued = queue[parentName] || []; + while (queued.length) { + registerState(queued.shift()); + } + } - //match greedy starts - if (globSegments[0] === '**') { - segments = segments.slice(indexOf(segments, globSegments[1])); - segments.unshift('**'); - } - //match greedy ends - if (globSegments[globSegments.length - 1] === '**') { - segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); - segments.push('**'); - } + function registerState(state) { + // Wrap a new object around the state so we can store our private details easily. + state = inherit(state, { + self: state, + resolve: state.resolve || {}, + toString: function () { + return this.name; + } + }); - if (globSegments.length != segments.length) { - return false; - } + var name = state.name; + if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); + if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined"); + + // Get parent name + var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) + : (isString(state.parent)) ? state.parent + : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name + : ''; + + // If parent is not registered yet, add state to queue and register later + if (parentName && !states[parentName]) { + return queueState(parentName, state.self); + } + + for (var key in stateBuilder) { + if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); + } + states[name] = state; + + // Register the state in the global state list and with $urlRouter if necessary. + if (!state[abstractKey] && state.url) { + $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { + if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { + $state.transitionTo(state, $match, {inherit: true, location: false}); + } + }]); + } + + // Register any queued children + flushQueuedChildren(name); + + return state; + } - //match single stars - for (var i = 0, l = globSegments.length; i < l; i++) { - if (globSegments[i] === '*') { - segments[i] = '*'; - } - } + // Checks text to see if it looks like a glob. + function isGlob(text) { + return text.indexOf('*') > -1; + } - return segments.join('') === globSegments.join(''); - } + // Returns true if glob matches current $state name. + function doesStateMatchGlob(glob) { + var globSegments = glob.split('.'), + segments = $state.$current.name.split('.'); + + //match greedy starts + if (globSegments[0] === '**') { + segments = segments.slice(indexOf(segments, globSegments[1])); + segments.unshift('**'); + } + //match greedy ends + if (globSegments[globSegments.length - 1] === '**') { + segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); + segments.push('**'); + } + + if (globSegments.length != segments.length) { + return false; + } + + //match single stars + for (var i = 0, l = globSegments.length; i < l; i++) { + if (globSegments[i] === '*') { + segments[i] = '*'; + } + } + + return segments.join('') === globSegments.join(''); + } - // Implicit root state that is always active - root = registerState({ - name: '', - url: '^', - views: null, - 'abstract': true - }); - root.navigable = null; + // Implicit root state that is always active + root = registerState({ + name: '', + url: '^', + views: null, + 'abstract': true + }); + root.navigable = null; - /** - * @ngdoc function - * @name ui.router.state.$stateProvider#decorator - * @methodOf ui.router.state.$stateProvider - * - * @description - * Allows you to extend (carefully) or override (at your own peril) the - * `stateBuilder` object used internally by `$stateProvider`. This can be used - * to add custom functionality to ui-router, for example inferring templateUrl - * based on the state name. - * - * When passing only a name, it returns the current (original or decorated) builder - * function that matches `name`. - * - * The builder functions that can be decorated are listed below. Though not all - * necessarily have a good use case for decoration, that is up to you to decide. - * - * In addition, users can attach custom decorators, which will generate new - * properties within the state's internal definition. There is currently no clear - * use-case for this beyond accessing internal states (i.e. $state.$current), - * however, expect this to become increasingly relevant as we introduce additional - * meta-programming features. - * - * **Warning**: Decorators should not be interdependent because the order of - * execution of the builder functions in non-deterministic. Builder functions - * should only be dependent on the state definition object and super function. - * - * - * Existing builder functions and current return values: - * - * - **parent** `{object}` - returns the parent state object. - * - **data** `{object}` - returns state data, including any inherited data that is not - * overridden by own values (if any). - * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher} - * or `null`. - * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is - * navigable). - * - **params** `{object}` - returns an array of state params that are ensured to - * be a super-set of parent's params. - * - **views** `{object}` - returns a views object where each key is an absolute view - * name (i.e. "viewName@stateName") and each value is the config object - * (template, controller) for the view. Even when you don't use the views object - * explicitly on a state config, one is still created for you internally. - * So by decorating this builder function you have access to decorating template - * and controller properties. - * - **ownParams** `{object}` - returns an array of params that belong to the state, - * not including any params defined by ancestor states. - * - **path** `{string}` - returns the full path from the root down to this state. - * Needed for state activation. - * - **includes** `{object}` - returns an object that includes every state that - * would pass a `$state.includes()` test. - * - * @example - *
          -   * // Override the internal 'views' builder with a function that takes the state
          -   * // definition, and a reference to the internal function being overridden:
          -   * $stateProvider.decorator('views', function (state, parent) {
          +        /**
          +         * @ngdoc function
          +         * @name ui.router.state.$stateProvider#decorator
          +         * @methodOf ui.router.state.$stateProvider
          +         *
          +         * @description
          +         * Allows you to extend (carefully) or override (at your own peril) the
          +         * `stateBuilder` object used internally by `$stateProvider`. This can be used
          +         * to add custom functionality to ui-router, for example inferring templateUrl
          +         * based on the state name.
          +         *
          +         * When passing only a name, it returns the current (original or decorated) builder
          +         * function that matches `name`.
          +         *
          +         * The builder functions that can be decorated are listed below. Though not all
          +         * necessarily have a good use case for decoration, that is up to you to decide.
          +         *
          +         * In addition, users can attach custom decorators, which will generate new
          +         * properties within the state's internal definition. There is currently no clear
          +         * use-case for this beyond accessing internal states (i.e. $state.$current),
          +         * however, expect this to become increasingly relevant as we introduce additional
          +         * meta-programming features.
          +         *
          +         * **Warning**: Decorators should not be interdependent because the order of
          +         * execution of the builder functions in non-deterministic. Builder functions
          +         * should only be dependent on the state definition object and super function.
          +         *
          +         *
          +         * Existing builder functions and current return values:
          +         *
          +         * - **parent** `{object}` - returns the parent state object.
          +         * - **data** `{object}` - returns state data, including any inherited data that is not
          +         *   overridden by own values (if any).
          +         * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
          +         *   or `null`.
          +         * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
          +         *   navigable).
          +         * - **params** `{object}` - returns an array of state params that are ensured to
          +         *   be a super-set of parent's params.
          +         * - **views** `{object}` - returns a views object where each key is an absolute view
          +         *   name (i.e. "viewName@stateName") and each value is the config object
          +         *   (template, controller) for the view. Even when you don't use the views object
          +         *   explicitly on a state config, one is still created for you internally.
          +         *   So by decorating this builder function you have access to decorating template
          +         *   and controller properties.
          +         * - **ownParams** `{object}` - returns an array of params that belong to the state,
          +         *   not including any params defined by ancestor states.
          +         * - **path** `{string}` - returns the full path from the root down to this state.
          +         *   Needed for state activation.
          +         * - **includes** `{object}` - returns an object that includes every state that
          +         *   would pass a `$state.includes()` test.
          +         *
          +         * @example
          +         * 
          +         * // Override the internal 'views' builder with a function that takes the state
          +         * // definition, and a reference to the internal function being overridden:
          +         * $stateProvider.decorator('views', function (state, parent) {
              *   var result = {},
              *       views = parent(state);
              *
          @@ -2439,117 +2527,117 @@ function $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {
              *   });
              *   return result;
              * });
          -   *
          -   * $stateProvider.state('home', {
          +         *
          +         * $stateProvider.state('home', {
              *   views: {
              *     'contact.list': { controller: 'ListController' },
              *     'contact.item': { controller: 'ItemController' }
              *   }
              * });
          -   *
          -   * // ...
          -   *
          -   * $state.go('home');
          -   * // Auto-populates list and item views with /partials/home/contact/list.html,
          -   * // and /partials/home/contact/item.html, respectively.
          -   * 
          - * - * @param {string} name The name of the builder function to decorate. - * @param {object} func A function that is responsible for decorating the original - * builder function. The function receives two parameters: - * - * - `{object}` - state - The state config object. - * - `{object}` - super - The original builder function. - * - * @return {object} $stateProvider - $stateProvider instance - */ - this.decorator = decorator; - function decorator(name, func) { - /*jshint validthis: true */ - if (isString(name) && !isDefined(func)) { - return stateBuilder[name]; - } - if (!isFunction(func) || !isString(name)) { - return this; - } - if (stateBuilder[name] && !stateBuilder.$delegates[name]) { - stateBuilder.$delegates[name] = stateBuilder[name]; - } - stateBuilder[name] = func; - return this; - } - - /** - * @ngdoc function - * @name ui.router.state.$stateProvider#state - * @methodOf ui.router.state.$stateProvider - * - * @description - * Registers a state configuration under a given state name. The stateConfig object - * has the following acceptable properties. - * - * @param {string} name A unique state name, e.g. "home", "about", "contacts". - * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". - * @param {object} stateConfig State configuration object. - * @param {string|function=} stateConfig.template - * - * html template as a string or a function that returns - * an html template as a string which should be used by the uiView directives. This property - * takes precedence over templateUrl. - * - * If `template` is a function, it will be called with the following parameters: - * - * - {array.<object>} - state parameters extracted from the current $location.path() by - * applying the current state - * - *
          template:
          -   *   "

          inline template definition

          " + - * "
          "
          - *
          template: function(params) {
          +         *
          +         * // ...
          +         *
          +         * $state.go('home');
          +         * // Auto-populates list and item views with /partials/home/contact/list.html,
          +         * // and /partials/home/contact/item.html, respectively.
          +         * 
          + * + * @param {string} name The name of the builder function to decorate. + * @param {object} func A function that is responsible for decorating the original + * builder function. The function receives two parameters: + * + * - `{object}` - state - The state config object. + * - `{object}` - super - The original builder function. + * + * @return {object} $stateProvider - $stateProvider instance + */ + this.decorator = decorator; + function decorator(name, func) { + /*jshint validthis: true */ + if (isString(name) && !isDefined(func)) { + return stateBuilder[name]; + } + if (!isFunction(func) || !isString(name)) { + return this; + } + if (stateBuilder[name] && !stateBuilder.$delegates[name]) { + stateBuilder.$delegates[name] = stateBuilder[name]; + } + stateBuilder[name] = func; + return this; + } + + /** + * @ngdoc function + * @name ui.router.state.$stateProvider#state + * @methodOf ui.router.state.$stateProvider + * + * @description + * Registers a state configuration under a given state name. The stateConfig object + * has the following acceptable properties. + * + * @param {string} name A unique state name, e.g. "home", "about", "contacts". + * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". + * @param {object} stateConfig State configuration object. + * @param {string|function=} stateConfig.template + * + * html template as a string or a function that returns + * an html template as a string which should be used by the uiView directives. This property + * takes precedence over templateUrl. + * + * If `template` is a function, it will be called with the following parameters: + * + * - {array.<object>} - state parameters extracted from the current $location.path() by + * applying the current state + * + *
          template:
          +         *   "

          inline template definition

          " + + * "
          "
          + *
          template: function(params) {
              *       return "

          generated template

          "; }
          - * - * - * @param {string|function=} stateConfig.templateUrl - * - * - * path or function that returns a path to an html - * template that should be used by uiView. - * - * If `templateUrl` is a function, it will be called with the following parameters: - * - * - {array.<object>} - state parameters extracted from the current $location.path() by - * applying the current state - * - *
          templateUrl: "home.html"
          - *
          templateUrl: function(params) {
          +         * 
          +         *
          +         * @param {string|function=} stateConfig.templateUrl
          +         * 
          +         *
          +         *   path or function that returns a path to an html
          +         *   template that should be used by uiView.
          +         *
          +         *   If `templateUrl` is a function, it will be called with the following parameters:
          +         *
          +         *   - {array.<object>} - state parameters extracted from the current $location.path() by
          +         *     applying the current state
          +         *
          +         * 
          templateUrl: "home.html"
          + *
          templateUrl: function(params) {
              *     return myTemplates[params.pageId]; }
          - * - * @param {function=} stateConfig.templateProvider - * - * Provider function that returns HTML content string. - *
           templateProvider:
          -   *       function(MyTemplateService, params) {
          +         *
          +         * @param {function=} stateConfig.templateProvider
          +         * 
          +         *    Provider function that returns HTML content string.
          +         * 
           templateProvider:
          +         *       function(MyTemplateService, params) {
              *         return MyTemplateService.getTemplate(params.pageId);
              *       }
          - * - * @param {string|function=} stateConfig.controller - * - * - * Controller fn that should be associated with newly - * related scope or the name of a registered controller if passed as a string. - * Optionally, the ControllerAs may be declared here. - *
          controller: "MyRegisteredController"
          - *
          controller:
          -   *     "MyRegisteredController as fooCtrl"}
          - *
          controller: function($scope, MyService) {
          +         *
          +         * @param {string|function=} stateConfig.controller
          +         * 
          +         *
          +         *  Controller fn that should be associated with newly
          +         *   related scope or the name of a registered controller if passed as a string.
          +         *   Optionally, the ControllerAs may be declared here.
          +         * 
          controller: "MyRegisteredController"
          + *
          controller:
          +         *     "MyRegisteredController as fooCtrl"}
          + *
          controller: function($scope, MyService) {
              *     $scope.data = MyService.getData(); }
          - * - * @param {function=} stateConfig.controllerProvider - * - * - * Injectable provider function that returns the actual controller or string. - *
          controllerProvider:
          -   *   function(MyResolveData) {
          +         *
          +         * @param {function=} stateConfig.controllerProvider
          +         * 
          +         *
          +         * Injectable provider function that returns the actual controller or string.
          +         * 
          controllerProvider:
          +         *   function(MyResolveData) {
              *     if (MyResolveData.foo)
              *       return "FooCtrl"
              *     else if (MyResolveData.bar)
          @@ -2558,64 +2646,64 @@ function $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {
              *       $scope.baz = "Qux";
              *     }
              *   }
          - * - * @param {string=} stateConfig.controllerAs - * - * - * A controller alias name. If present the controller will be - * published to scope under the controllerAs name. - *
          controllerAs: "myCtrl"
          - * - * @param {object=} stateConfig.resolve - * - * - * An optional map<string, function> of dependencies which - * should be injected into the controller. If any of these dependencies are promises, - * the router will wait for them all to be resolved before the controller is instantiated. - * If all the promises are resolved successfully, the $stateChangeSuccess event is fired - * and the values of the resolved promises are injected into any controllers that reference them. - * If any of the promises are rejected the $stateChangeError event is fired. - * - * The map object is: - * - * - key - {string}: name of dependency to be injected into controller - * - factory - {string|function}: If string then it is alias for service. Otherwise if function, - * it is injected and return value it treated as dependency. If result is a promise, it is - * resolved before its value is injected into controller. - * - *
          resolve: {
          +         *
          +         * @param {string=} stateConfig.controllerAs
          +         * 
          +         *
          +         * A controller alias name. If present the controller will be
          +         *   published to scope under the controllerAs name.
          +         * 
          controllerAs: "myCtrl"
          + * + * @param {object=} stateConfig.resolve + * + * + * An optional map<string, function> of dependencies which + * should be injected into the controller. If any of these dependencies are promises, + * the router will wait for them all to be resolved before the controller is instantiated. + * If all the promises are resolved successfully, the $stateChangeSuccess event is fired + * and the values of the resolved promises are injected into any controllers that reference them. + * If any of the promises are rejected the $stateChangeError event is fired. + * + * The map object is: + * + * - key - {string}: name of dependency to be injected into controller + * - factory - {string|function}: If string then it is alias for service. Otherwise if function, + * it is injected and return value it treated as dependency. If result is a promise, it is + * resolved before its value is injected into controller. + * + *
          resolve: {
              *     myResolve1:
              *       function($http, $stateParams) {
              *         return $http.get("/api/foos/"+stateParams.fooID);
              *       }
              *     }
          - * - * @param {string=} stateConfig.url - * - * - * A url fragment with optional parameters. When a state is navigated or - * transitioned to, the `$stateParams` service will be populated with any - * parameters that were passed. - * - * examples: - *
          url: "/home"
          -   * url: "/users/:userid"
          -   * url: "/books/{bookid:[a-zA-Z_-]}"
          -   * url: "/books/{categoryid:int}"
          -   * url: "/books/{publishername:string}/{categoryid:int}"
          -   * url: "/messages?before&after"
          -   * url: "/messages?{before:date}&{after:date}"
          - * url: "/messages/:mailboxid?{before:date}&{after:date}" - * - * @param {object=} stateConfig.views - * - * an optional map<string, object> which defined multiple views, or targets views - * manually/explicitly. - * - * Examples: - * - * Targets three named `ui-view`s in the parent state's template - *
          views: {
          +         *
          +         * @param {string=} stateConfig.url
          +         * 
          +         *
          +         *   A url fragment with optional parameters. When a state is navigated or
          +         *   transitioned to, the `$stateParams` service will be populated with any
          +         *   parameters that were passed.
          +         *
          +         * examples:
          +         * 
          url: "/home"
          +         * url: "/users/:userid"
          +         * url: "/books/{bookid:[a-zA-Z_-]}"
          +         * url: "/books/{categoryid:int}"
          +         * url: "/books/{publishername:string}/{categoryid:int}"
          +         * url: "/messages?before&after"
          +         * url: "/messages?{before:date}&{after:date}"
          + * url: "/messages/:mailboxid?{before:date}&{after:date}" + * + * @param {object=} stateConfig.views + * + * an optional map<string, object> which defined multiple views, or targets views + * manually/explicitly. + * + * Examples: + * + * Targets three named `ui-view`s in the parent state's template + *
          views: {
              *     header: {
              *       controller: "headerCtrl",
              *       templateUrl: "header.html"
          @@ -2627,9 +2715,9 @@ function $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {
              *       templateUrl: "footer.html"
              *     }
              *   }
          - * - * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template. - *
          views: {
          +         *
          +         * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
          +         * 
          views: {
              *     'header@top': {
              *       controller: "msgHeaderCtrl",
              *       templateUrl: "msgHeader.html"
          @@ -2638,1071 +2726,1081 @@ function $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {
              *       templateUrl: "messages.html"
              *     }
              *   }
          - * - * @param {boolean=} [stateConfig.abstract=false] - * - * An abstract state will never be directly activated, - * but can provide inherited properties to its common children states. - *
          abstract: true
          - * - * @param {function=} stateConfig.onEnter - * - * - * Callback function for when a state is entered. Good way - * to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explictly annotate this function, - * because it won't be automatically annotated by your build tools. - * - *
          onEnter: function(MyService, $stateParams) {
          +         *
          +         * @param {boolean=} [stateConfig.abstract=false]
          +         * 
          +         * An abstract state will never be directly activated,
          +         *   but can provide inherited properties to its common children states.
          +         * 
          abstract: true
          + * + * @param {function=} stateConfig.onEnter + * + * + * Callback function for when a state is entered. Good way + * to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explictly annotate this function, + * because it won't be automatically annotated by your build tools. + * + *
          onEnter: function(MyService, $stateParams) {
              *     MyService.foo($stateParams.myParam);
              * }
          - * - * @param {function=} stateConfig.onExit - * - * - * Callback function for when a state is exited. Good way to - * trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explictly annotate this function, - * because it won't be automatically annotated by your build tools. - * - *
          onExit: function(MyService, $stateParams) {
          +         *
          +         * @param {function=} stateConfig.onExit
          +         * 
          +         *
          +         * Callback function for when a state is exited. Good way to
          +         *   trigger an action or dispatch an event, such as opening a dialog.
          +         * If minifying your scripts, make sure to explictly annotate this function,
          +         * because it won't be automatically annotated by your build tools.
          +         *
          +         * 
          onExit: function(MyService, $stateParams) {
              *     MyService.cleanup($stateParams.myParam);
              * }
          - * - * @param {boolean=} [stateConfig.reloadOnSearch=true] - * - * - * If `false`, will not retrigger the same state - * just because a search/query parameter has changed (via $location.search() or $location.hash()). - * Useful for when you'd like to modify $location.search() without triggering a reload. - *
          reloadOnSearch: false
          - * - * @param {object=} stateConfig.data - * - * - * Arbitrary data object, useful for custom configuration. The parent state's `data` is - * prototypally inherited. In other words, adding a data property to a state adds it to - * the entire subtree via prototypal inheritance. - * - *
          data: {
          +         *
          +         * @param {boolean=} [stateConfig.reloadOnSearch=true]
          +         * 
          +         *
          +         * If `false`, will not retrigger the same state
          +         *   just because a search/query parameter has changed (via $location.search() or $location.hash()).
          +         *   Useful for when you'd like to modify $location.search() without triggering a reload.
          +         * 
          reloadOnSearch: false
          + * + * @param {object=} stateConfig.data + * + * + * Arbitrary data object, useful for custom configuration. The parent state's `data` is + * prototypally inherited. In other words, adding a data property to a state adds it to + * the entire subtree via prototypal inheritance. + * + *
          data: {
              *     requiredRole: 'foo'
              * } 
          - * - * @param {object=} stateConfig.params - * - * - * A map which optionally configures parameters declared in the `url`, or - * defines additional non-url parameters. For each parameter being - * configured, add a configuration object keyed to the name of the parameter. - * - * Each parameter configuration object may contain the following properties: - * - * - ** value ** - {object|function=}: specifies the default value for this - * parameter. This implicitly sets this parameter as optional. - * - * When UI-Router routes to a state and no value is - * specified for this parameter in the URL or transition, the - * default value will be used instead. If `value` is a function, - * it will be injected and invoked, and the return value used. - * - * *Note*: `undefined` is treated as "no default value" while `null` - * is treated as "the default value is `null`". - * - * *Shorthand*: If you only need to configure the default value of the - * parameter, you may use a shorthand syntax. In the **`params`** - * map, instead mapping the param name to a full parameter configuration - * object, simply set map it to the default parameter value, e.g.: - * - *
          // define a parameter's default value
          -   * params: {
          +         *
          +         * @param {object=} stateConfig.params
          +         * 
          +         *
          +         * A map which optionally configures parameters declared in the `url`, or
          +         *   defines additional non-url parameters.  For each parameter being
          +         *   configured, add a configuration object keyed to the name of the parameter.
          +         *
          +         *   Each parameter configuration object may contain the following properties:
          +         *
          +         *   - ** value ** - {object|function=}: specifies the default value for this
          +         *     parameter.  This implicitly sets this parameter as optional.
          +         *
          +         *     When UI-Router routes to a state and no value is
          +         *     specified for this parameter in the URL or transition, the
          +         *     default value will be used instead.  If `value` is a function,
          +         *     it will be injected and invoked, and the return value used.
          +         *
          +         *     *Note*: `undefined` is treated as "no default value" while `null`
          +         *     is treated as "the default value is `null`".
          +         *
          +         *     *Shorthand*: If you only need to configure the default value of the
          +         *     parameter, you may use a shorthand syntax.   In the **`params`**
          +         *     map, instead mapping the param name to a full parameter configuration
          +         *     object, simply set map it to the default parameter value, e.g.:
          +         *
          +         * 
          // define a parameter's default value
          +         * params: {
              *     param1: { value: "defaultValue" }
              * }
          -   * // shorthand default values
          -   * params: {
          +         * // shorthand default values
          +         * params: {
              *     param1: "defaultValue",
              *     param2: "param2Default"
              * }
          - * - * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be - * treated as an array of values. If you specified a Type, the value will be - * treated as an array of the specified Type. Note: query parameter values - * default to a special `"auto"` mode. - * - * For query parameters in `"auto"` mode, if multiple values for a single parameter - * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values - * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if - * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single - * value (e.g.: `{ foo: '1' }`). - * - *
          params: {
          +         *
          +         *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
          +         *     treated as an array of values.  If you specified a Type, the value will be
          +         *     treated as an array of the specified Type.  Note: query parameter values
          +         *     default to a special `"auto"` mode.
          +         *
          +         *     For query parameters in `"auto"` mode, if multiple  values for a single parameter
          +         *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
          +         *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if
          +         *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
          +         *     value (e.g.: `{ foo: '1' }`).
          +         *
          +         * 
          params: {
              *     param1: { array: true }
              * }
          - * - * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when - * the current parameter value is the same as the default value. If `squash` is not set, it uses the - * configured default squash policy. - * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`}) - * - * There are three squash settings: - * - * - false: The parameter's default value is not squashed. It is encoded and included in the URL - * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed - * by slashes in the state's `url` declaration, then one of those slashes are omitted. - * This can allow for cleaner looking URLs. - * - `""`: The parameter's default value is replaced with an arbitrary placeholder of your choice. - * - *
          params: {
          +         *
          +         *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
          +         *     the current parameter value is the same as the default value. If `squash` is not set, it uses the
          +         *     configured default squash policy.
          +         *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
          +         *
          +         *   There are three squash settings:
          +         *
          +         *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL
          +         *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed
          +         *       by slashes in the state's `url` declaration, then one of those slashes are omitted.
          +         *       This can allow for cleaner looking URLs.
          +         *     - `""`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.
          +         *
          +         * 
          params: {
              *     param1: {
              *       value: "defaultId",
              *       squash: true
              * } }
          -   * // squash "defaultValue" to "~"
          -   * params: {
          +         * // squash "defaultValue" to "~"
          +         * params: {
              *     param1: {
              *       value: "defaultValue",
              *       squash: "~"
              * } }
          -   * 
          - * - * - * @example - *
          -   * // Some state name examples
          -   *
          -   * // stateName can be a single top-level name (must be unique).
          -   * $stateProvider.state("home", {});
          -   *
          -   * // Or it can be a nested state name. This state is a child of the
          -   * // above "home" state.
          -   * $stateProvider.state("home.newest", {});
          -   *
          -   * // Nest states as deeply as needed.
          -   * $stateProvider.state("home.newest.abc.xyz.inception", {});
          -   *
          -   * // state() returns $stateProvider, so you can chain state declarations.
          -   * $stateProvider
          -   *   .state("home", {})
          -   *   .state("about", {})
          -   *   .state("contacts", {});
          -   * 
          - * - */ - this.state = state; - function state(name, definition) { - /*jshint validthis: true */ - if (isObject(name)) definition = name; - else definition.name = name; - registerState(definition); - return this; - } - - /** - * @ngdoc object - * @name ui.router.state.$state - * - * @requires $rootScope - * @requires $q - * @requires ui.router.state.$view - * @requires $injector - * @requires ui.router.util.$resolve - * @requires ui.router.state.$stateParams - * @requires ui.router.router.$urlRouter - * - * @property {object} params A param object, e.g. {sectionId: section.id)}, that - * you'd like to test against the current active state. - * @property {object} current A reference to the state's config object. However - * you passed it in. Useful for accessing custom data. - * @property {object} transition Currently pending transition. A promise that'll - * resolve or reject. - * - * @description - * `$state` service is responsible for representing states as well as transitioning - * between them. It also provides interfaces to ask for current state or even states - * you're coming from. - */ - this.$get = $get; - $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory']; - function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) { - - var TransitionSuperseded = $q.reject(new Error('transition superseded')); - var TransitionPrevented = $q.reject(new Error('transition prevented')); - var TransitionAborted = $q.reject(new Error('transition aborted')); - var TransitionFailed = $q.reject(new Error('transition failed')); - - // Handles the case where a state which is the target of a transition is not found, and the user - // can optionally retry or defer the transition - function handleRedirect(redirect, state, params, options) { - /** - * @ngdoc event - * @name ui.router.state.$state#$stateNotFound - * @eventOf ui.router.state.$state - * @eventType broadcast on root scope - * @description - * Fired when a requested state **cannot be found** using the provided state name during transition. - * The event is broadcast allowing any handlers a single chance to deal with the error (usually by - * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, - * you can see its three properties in the example. You can use `event.preventDefault()` to abort the - * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. - * - * @param {Object} event Event object. - * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. - * @param {State} fromState Current state object. - * @param {Object} fromParams Current state params. - * - * @example - * - *
          -       * // somewhere, assume lazy.state has not been defined
          -       * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
          -       *
          -       * // somewhere else
          -       * $scope.$on('$stateNotFound',
          -       * function(event, unfoundState, fromState, fromParams){
          -       *     console.log(unfoundState.to); // "lazy.state"
          -       *     console.log(unfoundState.toParams); // {a:1, b:2}
          -       *     console.log(unfoundState.options); // {inherit:false} + default options
          -       * })
          -       * 
          - */ - var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); - - if (evt.defaultPrevented) { - $urlRouter.update(); - return TransitionAborted; - } - - if (!evt.retry) { - return null; - } - - // Allow the handler to return a promise to defer state lookup retry - if (options.$retry) { - $urlRouter.update(); - return TransitionFailed; - } - var retryTransition = $state.transition = $q.when(evt.retry); - - retryTransition.then(function() { - if (retryTransition !== $state.transition) return TransitionSuperseded; - redirect.options.$retry = true; - return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); - }, function() { - return TransitionAborted; - }); - $urlRouter.update(); - - return retryTransition; - } - - root.locals = { resolve: null, globals: { $stateParams: {} } }; - - $state = { - params: {}, - current: root.self, - $current: root, - transition: null - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#reload - * @methodOf ui.router.state.$state - * - * @description - * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, - * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon). - * - * @example - *
          -     * var app angular.module('app', ['ui.router']);
          -     *
          -     * app.controller('ctrl', function ($scope, $state) {
          -     *   $scope.reload = function(){
          -     *     $state.reload();
          -     *   }
          -     * });
          -     * 
          - * - * `reload()` is just an alias for: - *
          -     * $state.transitionTo($state.current, $stateParams, { 
          -     *   reload: true, inherit: false, notify: true
          -     * });
          -     * 
          - * - * @returns {promise} A promise representing the state of the new transition. See - * {@link ui.router.state.$state#methods_go $state.go}. - */ - $state.reload = function reload() { - return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true }); - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#go - * @methodOf ui.router.state.$state - * - * @description - * Convenience method for transitioning to a new state. `$state.go` calls - * `$state.transitionTo` internally but automatically sets options to - * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. - * This allows you to easily use an absolute or relative to path and specify - * only the parameters you'd like to update (while letting unspecified parameters - * inherit from the currently active ancestor states). - * - * @example - *
          -     * var app = angular.module('app', ['ui.router']);
          -     *
          -     * app.controller('ctrl', function ($scope, $state) {
          -     *   $scope.changeState = function () {
          -     *     $state.go('contact.detail');
          -     *   };
          -     * });
          -     * 
          - * - * - * @param {string} to Absolute state name or relative state path. Some examples: - * - * - `$state.go('contact.detail')` - will go to the `contact.detail` state - * - `$state.go('^')` - will go to a parent state - * - `$state.go('^.sibling')` - will go to a sibling state - * - `$state.go('.child.grandchild')` - will go to grandchild state - * - * @param {object=} params A map of the parameters that will be sent to the state, - * will populate $stateParams. Any parameters that are not specified will be inherited from currently - * defined parameters. This allows, for example, going to a sibling state that shares parameters - * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. - * transitioning to a sibling will get you the parameters for all parents, transitioning to a child - * will get you all current parameters, etc. - * @param {object=} options Options object. The options are: - * - * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` - * will not. If string, must be `"replace"`, which will update url and also replace last history record. - * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. - * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), - * defines which state to be relative from. - * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. - * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params - * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd - * use this when you want to force a reload when *everything* is the same, including search params. - * - * @returns {promise} A promise representing the state of the new transition. - * - * Possible success values: - * - * - $state.current - * - *
          Possible rejection values: - * - * - 'transition superseded' - when a newer transition has been started after this one - * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener - * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or - * when a `$stateNotFound` `event.retry` promise errors. - * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. - * - *resolve error* - when an error has occurred with a `resolve` - * - */ - $state.go = function go(to, params, options) { - return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#transitionTo - * @methodOf ui.router.state.$state - * - * @description - * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} - * uses `transitionTo` internally. `$state.go` is recommended in most situations. - * - * @example - *
          -     * var app = angular.module('app', ['ui.router']);
          -     *
          -     * app.controller('ctrl', function ($scope, $state) {
          -     *   $scope.changeState = function () {
          -     *     $state.transitionTo('contact.detail');
          -     *   };
          -     * });
          -     * 
          - * - * @param {string} to State name. - * @param {object=} toParams A map of the parameters that will be sent to the state, - * will populate $stateParams. - * @param {object=} options Options object. The options are: - * - * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` - * will not. If string, must be `"replace"`, which will update url and also replace last history record. - * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. - * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), - * defines which state to be relative from. - * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. - * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params - * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd - * use this when you want to force a reload when *everything* is the same, including search params. - * - * @returns {promise} A promise representing the state of the new transition. See - * {@link ui.router.state.$state#methods_go $state.go}. - */ - $state.transitionTo = function transitionTo(to, toParams, options) { - toParams = toParams || {}; - options = extend({ - location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false - }, options || {}); - - var from = $state.$current, fromParams = $state.params, fromPath = from.path; - var evt, toState = findState(to, options.relative); - - if (!isDefined(toState)) { - var redirect = { to: to, toParams: toParams, options: options }; - var redirectResult = handleRedirect(redirect, from.self, fromParams, options); - - if (redirectResult) { - return redirectResult; - } - - // Always retry once if the $stateNotFound was not prevented - // (handles either redirect changed or state lazy-definition) - to = redirect.to; - toParams = redirect.toParams; - options = redirect.options; - toState = findState(to, options.relative); - - if (!isDefined(toState)) { - if (!options.relative) throw new Error("No such state '" + to + "'"); - throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); - } - } - if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); - if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); - if (!toState.params.$$validates(toParams)) return TransitionFailed; - - toParams = toState.params.$$values(toParams); - to = toState; - - var toPath = to.path; - - // Starting from the root of the path, keep all levels that haven't changed - var keep = 0, state = toPath[keep], locals = root.locals, toLocals = []; - - if (!options.reload) { - while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) { - locals = toLocals[keep] = state.locals; - keep++; - state = toPath[keep]; - } - } - - // If we're going to the same state and all locals are kept, we've got nothing to do. - // But clear 'transition', as we still want to cancel any other pending transitions. - // TODO: We may not want to bump 'transition' if we're called from a location change - // that we've initiated ourselves, because we might accidentally abort a legitimate - // transition initiated from code? - if (shouldTriggerReload(to, from, locals, options)) { - if (to.self.reloadOnSearch !== false) $urlRouter.update(); - $state.transition = null; - return $q.when($state.current); - } - - // Filter parameters before we pass them to event handlers etc. - toParams = filterByKeys(to.params.$$keys(), toParams || {}); - - // Broadcast start event and cancel the transition if requested - if (options.notify) { - /** - * @ngdoc event - * @name ui.router.state.$state#$stateChangeStart - * @eventOf ui.router.state.$state - * @eventType broadcast on root scope - * @description - * Fired when the state transition **begins**. You can use `event.preventDefault()` - * to prevent the transition from happening and then the transition promise will be - * rejected with a `'transition prevented'` value. - * - * @param {Object} event Event object. - * @param {State} toState The state being transitioned to. - * @param {Object} toParams The params supplied to the `toState`. - * @param {State} fromState The current state, pre-transition. - * @param {Object} fromParams The params supplied to the `fromState`. - * - * @example - * - *
          -         * $rootScope.$on('$stateChangeStart',
          -         * function(event, toState, toParams, fromState, fromParams){
          -         *     event.preventDefault();
          -         *     // transitionTo() promise will be rejected with
          -         *     // a 'transition prevented' error
          -         * })
          -         * 
          - */ - if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) { - $urlRouter.update(); - return TransitionPrevented; - } - } - - // Resolve locals for the remaining states, but don't update any global state just - // yet -- if anything fails to resolve the current state needs to remain untouched. - // We also set up an inheritance chain for the locals here. This allows the view directive - // to quickly look up the correct definition for each view in the current state. Even - // though we create the locals object itself outside resolveState(), it is initially - // empty and gets filled asynchronously. We need to keep track of the promise for the - // (fully resolved) current locals, and pass this down the chain. - var resolved = $q.when(locals); - - for (var l = keep; l < toPath.length; l++, state = toPath[l]) { - locals = toLocals[l] = inherit(locals); - resolved = resolveState(state, toParams, state === to, resolved, locals, options); - } - - // Once everything is resolved, we are ready to perform the actual transition - // and return a promise for the new state. We also keep track of what the - // current promise is, so that we can detect overlapping transitions and - // keep only the outcome of the last transition. - var transition = $state.transition = resolved.then(function () { - var l, entering, exiting; - - if ($state.transition !== transition) return TransitionSuperseded; - - // Exit 'from' states not kept - for (l = fromPath.length - 1; l >= keep; l--) { - exiting = fromPath[l]; - if (exiting.self.onExit) { - $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); - } - exiting.locals = null; - } - - // Enter 'to' states not kept - for (l = keep; l < toPath.length; l++) { - entering = toPath[l]; - entering.locals = toLocals[l]; - if (entering.self.onEnter) { - $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals); - } - } - - // Run it again, to catch any transitions in callbacks - if ($state.transition !== transition) return TransitionSuperseded; - - // Update globals in $state - $state.$current = to; - $state.current = to.self; - $state.params = toParams; - copy($state.params, $stateParams); - $state.transition = null; - - if (options.location && to.navigable) { - $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, { - $$avoidResync: true, replace: options.location === 'replace' - }); - } - - if (options.notify) { - /** - * @ngdoc event - * @name ui.router.state.$state#$stateChangeSuccess - * @eventOf ui.router.state.$state - * @eventType broadcast on root scope - * @description - * Fired once the state transition is **complete**. - * - * @param {Object} event Event object. - * @param {State} toState The state being transitioned to. - * @param {Object} toParams The params supplied to the `toState`. - * @param {State} fromState The current state, pre-transition. - * @param {Object} fromParams The params supplied to the `fromState`. - */ - $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams); - } - $urlRouter.update(true); - - return $state.current; - }, function (error) { - if ($state.transition !== transition) return TransitionSuperseded; - - $state.transition = null; - /** - * @ngdoc event - * @name ui.router.state.$state#$stateChangeError - * @eventOf ui.router.state.$state - * @eventType broadcast on root scope - * @description - * Fired when an **error occurs** during transition. It's important to note that if you - * have any errors in your resolve functions (javascript errors, non-existent services, etc) - * they will not throw traditionally. You must listen for this $stateChangeError event to - * catch **ALL** errors. - * - * @param {Object} event Event object. - * @param {State} toState The state being transitioned to. - * @param {Object} toParams The params supplied to the `toState`. - * @param {State} fromState The current state, pre-transition. - * @param {Object} fromParams The params supplied to the `fromState`. - * @param {Error} error The resolve error object. - */ - evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error); - - if (!evt.defaultPrevented) { - $urlRouter.update(); - } - - return $q.reject(error); - }); - - return transition; - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#is - * @methodOf ui.router.state.$state - * - * @description - * Similar to {@link ui.router.state.$state#methods_includes $state.includes}, - * but only checks for the full state name. If params is supplied then it will be - * tested for strict equality against the current active params object, so all params - * must match with none missing and no extras. - * - * @example - *
          -     * $state.$current.name = 'contacts.details.item';
          -     *
          -     * // absolute name
          -     * $state.is('contact.details.item'); // returns true
          -     * $state.is(contactDetailItemStateObject); // returns true
          -     *
          -     * // relative name (. and ^), typically from a template
          -     * // E.g. from the 'contacts.details' template
          -     * 
          Item
          - *
          - * - * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check. - * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like - * to test against the current active state. - * @param {object=} options An options object. The options are: - * - * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will - * test relative to `options.relative` state (or name). - * - * @returns {boolean} Returns true if it is the state. - */ - $state.is = function is(stateOrName, params, options) { - options = extend({ relative: $state.$current }, options || {}); - var state = findState(stateOrName, options.relative); - - if (!isDefined(state)) { return undefined; } - if ($state.$current !== state) { return false; } - return params ? equalForKeys(state.params.$$values(params), $stateParams) : true; - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#includes - * @methodOf ui.router.state.$state - * - * @description - * A method to determine if the current active state is equal to or is the child of the - * state stateName. If any params are passed then they will be tested for a match as well. - * Not all the parameters need to be passed, just the ones you'd like to test for equality. - * - * @example - * Partial and relative names - *
          -     * $state.$current.name = 'contacts.details.item';
          -     *
          -     * // Using partial names
          -     * $state.includes("contacts"); // returns true
          -     * $state.includes("contacts.details"); // returns true
          -     * $state.includes("contacts.details.item"); // returns true
          -     * $state.includes("contacts.list"); // returns false
          -     * $state.includes("about"); // returns false
          -     *
          -     * // Using relative names (. and ^), typically from a template
          -     * // E.g. from the 'contacts.details' template
          -     * 
          Item
          - *
          - * - * Basic globbing patterns - *
          -     * $state.$current.name = 'contacts.details.item.url';
          -     *
          -     * $state.includes("*.details.*.*"); // returns true
          -     * $state.includes("*.details.**"); // returns true
          -     * $state.includes("**.item.**"); // returns true
          -     * $state.includes("*.details.item.url"); // returns true
          -     * $state.includes("*.details.*.url"); // returns true
          -     * $state.includes("*.details.*"); // returns false
          -     * $state.includes("item.**"); // returns false
          -     * 
          - * - * @param {string} stateOrName A partial name, relative name, or glob pattern - * to be searched for within the current state name. - * @param {object=} params A param object, e.g. `{sectionId: section.id}`, - * that you'd like to test against the current active state. - * @param {object=} options An options object. The options are: - * - * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set, - * .includes will test relative to `options.relative` state (or name). - * - * @returns {boolean} Returns true if it does include the state - */ - $state.includes = function includes(stateOrName, params, options) { - options = extend({ relative: $state.$current }, options || {}); - if (isString(stateOrName) && isGlob(stateOrName)) { - if (!doesStateMatchGlob(stateOrName)) { - return false; - } - stateOrName = $state.$current.name; - } - - var state = findState(stateOrName, options.relative); - if (!isDefined(state)) { return undefined; } - if (!isDefined($state.$current.includes[state.name])) { return false; } - return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true; - }; - - - /** - * @ngdoc function - * @name ui.router.state.$state#href - * @methodOf ui.router.state.$state - * - * @description - * A url generation method that returns the compiled url for the given state populated with the given params. - * - * @example - *
          -     * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
          -     * 
          - * - * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. - * @param {object=} params An object of parameter values to fill the state's required parameters. - * @param {object=} options Options object. The options are: - * - * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the - * first parameter, then the constructed href url will be built from the first navigable ancestor (aka - * ancestor with a valid url). - * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. - * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), - * defines which state to be relative from. - * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". - * - * @returns {string} compiled state url - */ - $state.href = function href(stateOrName, params, options) { - options = extend({ - lossy: true, - inherit: true, - absolute: false, - relative: $state.$current - }, options || {}); - - var state = findState(stateOrName, options.relative); - - if (!isDefined(state)) return null; - if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state); - - var nav = (state && options.lossy) ? state.navigable : state; - - if (!nav || nav.url === undefined || nav.url === null) { - return null; - } - return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), { - absolute: options.absolute - }); - }; - - /** - * @ngdoc function - * @name ui.router.state.$state#get - * @methodOf ui.router.state.$state - * - * @description - * Returns the state configuration object for any specific state or all states. - * - * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for - * the requested state. If not provided, returns an array of ALL state configs. - * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context. - * @returns {Object|Array} State configuration object or array of all objects. - */ - $state.get = function (stateOrName, context) { - if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; }); - var state = findState(stateOrName, context || $state.$current); - return (state && state.self) ? state.self : null; - }; - - function resolveState(state, params, paramsAreFiltered, inherited, dst, options) { - // Make a restricted $stateParams with only the parameters that apply to this state if - // necessary. In addition to being available to the controller and onEnter/onExit callbacks, - // we also need $stateParams to be available for any $injector calls we make during the - // dependency resolution process. - var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params); - var locals = { $stateParams: $stateParams }; - - // Resolve 'global' dependencies for the state, i.e. those not specific to a view. - // We're also including $stateParams in this; that way the parameters are restricted - // to the set that should be visible to the state, and are independent of when we update - // the global $state and $stateParams values. - dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); - var promises = [dst.resolve.then(function (globals) { - dst.globals = globals; - })]; - if (inherited) promises.push(inherited); - - // Resolve template and dependencies for all views. - forEach(state.views, function (view, name) { - var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); - injectables.$template = [ function () { - return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || ''; - }]; - - promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) { - // References to the controller (only instantiated at link time) - if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { - var injectLocals = angular.extend({}, injectables, locals); - result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); - } else { - result.$$controller = view.controller; - } - // Provide access to the state itself for internal use - result.$$state = state; - result.$$controllerAs = view.controllerAs; - dst[name] = result; - })); - }); - - // Wait for all the promises and then return the activation object - return $q.all(promises).then(function (values) { - return dst; - }); - } + *
          + * + * + * @example + *
          +         * // Some state name examples
          +         *
          +         * // stateName can be a single top-level name (must be unique).
          +         * $stateProvider.state("home", {});
          +         *
          +         * // Or it can be a nested state name. This state is a child of the
          +         * // above "home" state.
          +         * $stateProvider.state("home.newest", {});
          +         *
          +         * // Nest states as deeply as needed.
          +         * $stateProvider.state("home.newest.abc.xyz.inception", {});
          +         *
          +         * // state() returns $stateProvider, so you can chain state declarations.
          +         * $stateProvider
          +         *   .state("home", {})
          +         *   .state("about", {})
          +         *   .state("contacts", {});
          +         * 
          + * + */ + this.state = state; + function state(name, definition) { + /*jshint validthis: true */ + if (isObject(name)) definition = name; + else definition.name = name; + registerState(definition); + return this; + } - return $state; - } + /** + * @ngdoc object + * @name ui.router.state.$state + * + * @requires $rootScope + * @requires $q + * @requires ui.router.state.$view + * @requires $injector + * @requires ui.router.util.$resolve + * @requires ui.router.state.$stateParams + * @requires ui.router.router.$urlRouter + * + * @property {object} params A param object, e.g. {sectionId: section.id)}, that + * you'd like to test against the current active state. + * @property {object} current A reference to the state's config object. However + * you passed it in. Useful for accessing custom data. + * @property {object} transition Currently pending transition. A promise that'll + * resolve or reject. + * + * @description + * `$state` service is responsible for representing states as well as transitioning + * between them. It also provides interfaces to ask for current state or even states + * you're coming from. + */ + this.$get = $get; + $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory']; + function $get($rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) { + + var TransitionSuperseded = $q.reject(new Error('transition superseded')); + var TransitionPrevented = $q.reject(new Error('transition prevented')); + var TransitionAborted = $q.reject(new Error('transition aborted')); + var TransitionFailed = $q.reject(new Error('transition failed')); + + // Handles the case where a state which is the target of a transition is not found, and the user + // can optionally retry or defer the transition + function handleRedirect(redirect, state, params, options) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateNotFound + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when a requested state **cannot be found** using the provided state name during transition. + * The event is broadcast allowing any handlers a single chance to deal with the error (usually by + * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, + * you can see its three properties in the example. You can use `event.preventDefault()` to abort the + * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. + * + * @param {Object} event Event object. + * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. + * @param {State} fromState Current state object. + * @param {Object} fromParams Current state params. + * + * @example + * + *
          +                 * // somewhere, assume lazy.state has not been defined
          +                 * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
          +                 *
          +                 * // somewhere else
          +                 * $scope.$on('$stateNotFound',
          +                 * function(event, unfoundState, fromState, fromParams){
          +       *     console.log(unfoundState.to); // "lazy.state"
          +       *     console.log(unfoundState.toParams); // {a:1, b:2}
          +       *     console.log(unfoundState.options); // {inherit:false} + default options
          +       * })
          +                 * 
          + */ + var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); + + if (evt.defaultPrevented) { + $urlRouter.update(); + return TransitionAborted; + } + + if (!evt.retry) { + return null; + } + + // Allow the handler to return a promise to defer state lookup retry + if (options.$retry) { + $urlRouter.update(); + return TransitionFailed; + } + var retryTransition = $state.transition = $q.when(evt.retry); + + retryTransition.then(function () { + if (retryTransition !== $state.transition) return TransitionSuperseded; + redirect.options.$retry = true; + return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); + }, function () { + return TransitionAborted; + }); + $urlRouter.update(); + + return retryTransition; + } + + root.locals = {resolve: null, globals: {$stateParams: {}}}; + + $state = { + params: {}, + current: root.self, + $current: root, + transition: null + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#reload + * @methodOf ui.router.state.$state + * + * @description + * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, + * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon). + * + * @example + *
          +             * var app angular.module('app', ['ui.router']);
          +             *
          +             * app.controller('ctrl', function ($scope, $state) {
          +     *   $scope.reload = function(){
          +     *     $state.reload();
          +     *   }
          +     * });
          +             * 
          + * + * `reload()` is just an alias for: + *
          +             * $state.transitionTo($state.current, $stateParams, {
          +     *   reload: true, inherit: false, notify: true
          +     * });
          +             * 
          + * + * @returns {promise} A promise representing the state of the new transition. See + * {@link ui.router.state.$state#methods_go $state.go}. + */ + $state.reload = function reload() { + return $state.transitionTo($state.current, $stateParams, {reload: true, inherit: false, notify: true}); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#go + * @methodOf ui.router.state.$state + * + * @description + * Convenience method for transitioning to a new state. `$state.go` calls + * `$state.transitionTo` internally but automatically sets options to + * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. + * This allows you to easily use an absolute or relative to path and specify + * only the parameters you'd like to update (while letting unspecified parameters + * inherit from the currently active ancestor states). + * + * @example + *
          +             * var app = angular.module('app', ['ui.router']);
          +             *
          +             * app.controller('ctrl', function ($scope, $state) {
          +     *   $scope.changeState = function () {
          +     *     $state.go('contact.detail');
          +     *   };
          +     * });
          +             * 
          + * + * + * @param {string} to Absolute state name or relative state path. Some examples: + * + * - `$state.go('contact.detail')` - will go to the `contact.detail` state + * - `$state.go('^')` - will go to a parent state + * - `$state.go('^.sibling')` - will go to a sibling state + * - `$state.go('.child.grandchild')` - will go to grandchild state + * + * @param {object=} params A map of the parameters that will be sent to the state, + * will populate $stateParams. Any parameters that are not specified will be inherited from currently + * defined parameters. This allows, for example, going to a sibling state that shares parameters + * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. + * transitioning to a sibling will get you the parameters for all parents, transitioning to a child + * will get you all current parameters, etc. + * @param {object=} options Options object. The options are: + * + * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` + * will not. If string, must be `"replace"`, which will update url and also replace last history record. + * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. + * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params + * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd + * use this when you want to force a reload when *everything* is the same, including search params. + * + * @returns {promise} A promise representing the state of the new transition. + * + * Possible success values: + * + * - $state.current + * + *
          Possible rejection values: + * + * - 'transition superseded' - when a newer transition has been started after this one + * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener + * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or + * when a `$stateNotFound` `event.retry` promise errors. + * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. + * - *resolve error* - when an error has occurred with a `resolve` + * + */ + $state.go = function go(to, params, options) { + return $state.transitionTo(to, params, extend({inherit: true, relative: $state.$current}, options)); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#transitionTo + * @methodOf ui.router.state.$state + * + * @description + * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} + * uses `transitionTo` internally. `$state.go` is recommended in most situations. + * + * @example + *
          +             * var app = angular.module('app', ['ui.router']);
          +             *
          +             * app.controller('ctrl', function ($scope, $state) {
          +     *   $scope.changeState = function () {
          +     *     $state.transitionTo('contact.detail');
          +     *   };
          +     * });
          +             * 
          + * + * @param {string} to State name. + * @param {object=} toParams A map of the parameters that will be sent to the state, + * will populate $stateParams. + * @param {object=} options Options object. The options are: + * + * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` + * will not. If string, must be `"replace"`, which will update url and also replace last history record. + * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. + * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params + * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd + * use this when you want to force a reload when *everything* is the same, including search params. + * + * @returns {promise} A promise representing the state of the new transition. See + * {@link ui.router.state.$state#methods_go $state.go}. + */ + $state.transitionTo = function transitionTo(to, toParams, options) { + toParams = toParams || {}; + options = extend({ + location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false + }, options || {}); + + var from = $state.$current, fromParams = $state.params, fromPath = from.path; + var evt, toState = findState(to, options.relative); + + if (!isDefined(toState)) { + var redirect = {to: to, toParams: toParams, options: options}; + var redirectResult = handleRedirect(redirect, from.self, fromParams, options); + + if (redirectResult) { + return redirectResult; + } + + // Always retry once if the $stateNotFound was not prevented + // (handles either redirect changed or state lazy-definition) + to = redirect.to; + toParams = redirect.toParams; + options = redirect.options; + toState = findState(to, options.relative); + + if (!isDefined(toState)) { + if (!options.relative) throw new Error("No such state '" + to + "'"); + throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); + } + } + if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); + if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); + if (!toState.params.$$validates(toParams)) return TransitionFailed; + + toParams = toState.params.$$values(toParams); + to = toState; + + var toPath = to.path; + + // Starting from the root of the path, keep all levels that haven't changed + var keep = 0, state = toPath[keep], locals = root.locals, toLocals = []; + + if (!options.reload) { + while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) { + locals = toLocals[keep] = state.locals; + keep++; + state = toPath[keep]; + } + } + + // If we're going to the same state and all locals are kept, we've got nothing to do. + // But clear 'transition', as we still want to cancel any other pending transitions. + // TODO: We may not want to bump 'transition' if we're called from a location change + // that we've initiated ourselves, because we might accidentally abort a legitimate + // transition initiated from code? + if (shouldTriggerReload(to, from, locals, options)) { + if (to.self.reloadOnSearch !== false) $urlRouter.update(); + $state.transition = null; + return $q.when($state.current); + } + + // Filter parameters before we pass them to event handlers etc. + toParams = filterByKeys(to.params.$$keys(), toParams || {}); + + // Broadcast start event and cancel the transition if requested + if (options.notify) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeStart + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when the state transition **begins**. You can use `event.preventDefault()` + * to prevent the transition from happening and then the transition promise will be + * rejected with a `'transition prevented'` value. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + * + * @example + * + *
          +                     * $rootScope.$on('$stateChangeStart',
          +                     * function(event, toState, toParams, fromState, fromParams){
          +         *     event.preventDefault();
          +         *     // transitionTo() promise will be rejected with
          +         *     // a 'transition prevented' error
          +         * })
          +                     * 
          + */ + if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) { + $urlRouter.update(); + return TransitionPrevented; + } + } + + // Resolve locals for the remaining states, but don't update any global state just + // yet -- if anything fails to resolve the current state needs to remain untouched. + // We also set up an inheritance chain for the locals here. This allows the view directive + // to quickly look up the correct definition for each view in the current state. Even + // though we create the locals object itself outside resolveState(), it is initially + // empty and gets filled asynchronously. We need to keep track of the promise for the + // (fully resolved) current locals, and pass this down the chain. + var resolved = $q.when(locals); + + for (var l = keep; l < toPath.length; l++, state = toPath[l]) { + locals = toLocals[l] = inherit(locals); + resolved = resolveState(state, toParams, state === to, resolved, locals, options); + } + + // Once everything is resolved, we are ready to perform the actual transition + // and return a promise for the new state. We also keep track of what the + // current promise is, so that we can detect overlapping transitions and + // keep only the outcome of the last transition. + var transition = $state.transition = resolved.then(function () { + var l, entering, exiting; + + if ($state.transition !== transition) return TransitionSuperseded; + + // Exit 'from' states not kept + for (l = fromPath.length - 1; l >= keep; l--) { + exiting = fromPath[l]; + if (exiting.self.onExit) { + $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); + } + exiting.locals = null; + } + + // Enter 'to' states not kept + for (l = keep; l < toPath.length; l++) { + entering = toPath[l]; + entering.locals = toLocals[l]; + if (entering.self.onEnter) { + $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals); + } + } + + // Run it again, to catch any transitions in callbacks + if ($state.transition !== transition) return TransitionSuperseded; + + // Update globals in $state + $state.$current = to; + $state.current = to.self; + $state.params = toParams; + copy($state.params, $stateParams); + $state.transition = null; + + if (options.location && to.navigable) { + $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, { + $$avoidResync: true, replace: options.location === 'replace' + }); + } + + if (options.notify) { + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeSuccess + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired once the state transition is **complete**. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + */ + $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams); + } + $urlRouter.update(true); + + return $state.current; + }, function (error) { + if ($state.transition !== transition) return TransitionSuperseded; + + $state.transition = null; + /** + * @ngdoc event + * @name ui.router.state.$state#$stateChangeError + * @eventOf ui.router.state.$state + * @eventType broadcast on root scope + * @description + * Fired when an **error occurs** during transition. It's important to note that if you + * have any errors in your resolve functions (javascript errors, non-existent services, etc) + * they will not throw traditionally. You must listen for this $stateChangeError event to + * catch **ALL** errors. + * + * @param {Object} event Event object. + * @param {State} toState The state being transitioned to. + * @param {Object} toParams The params supplied to the `toState`. + * @param {State} fromState The current state, pre-transition. + * @param {Object} fromParams The params supplied to the `fromState`. + * @param {Error} error The resolve error object. + */ + evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error); + + if (!evt.defaultPrevented) { + $urlRouter.update(); + } + + return $q.reject(error); + }); + + return transition; + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#is + * @methodOf ui.router.state.$state + * + * @description + * Similar to {@link ui.router.state.$state#methods_includes $state.includes}, + * but only checks for the full state name. If params is supplied then it will be + * tested for strict equality against the current active params object, so all params + * must match with none missing and no extras. + * + * @example + *
          +             * $state.$current.name = 'contacts.details.item';
          +             *
          +             * // absolute name
          +             * $state.is('contact.details.item'); // returns true
          +             * $state.is(contactDetailItemStateObject); // returns true
          +             *
          +             * // relative name (. and ^), typically from a template
          +             * // E.g. from the 'contacts.details' template
          +             * 
          Item
          + *
          + * + * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check. + * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like + * to test against the current active state. + * @param {object=} options An options object. The options are: + * + * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will + * test relative to `options.relative` state (or name). + * + * @returns {boolean} Returns true if it is the state. + */ + $state.is = function is(stateOrName, params, options) { + options = extend({relative: $state.$current}, options || {}); + var state = findState(stateOrName, options.relative); + + if (!isDefined(state)) { + return undefined; + } + if ($state.$current !== state) { + return false; + } + return params ? equalForKeys(state.params.$$values(params), $stateParams) : true; + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#includes + * @methodOf ui.router.state.$state + * + * @description + * A method to determine if the current active state is equal to or is the child of the + * state stateName. If any params are passed then they will be tested for a match as well. + * Not all the parameters need to be passed, just the ones you'd like to test for equality. + * + * @example + * Partial and relative names + *
          +             * $state.$current.name = 'contacts.details.item';
          +             *
          +             * // Using partial names
          +             * $state.includes("contacts"); // returns true
          +             * $state.includes("contacts.details"); // returns true
          +             * $state.includes("contacts.details.item"); // returns true
          +             * $state.includes("contacts.list"); // returns false
          +             * $state.includes("about"); // returns false
          +             *
          +             * // Using relative names (. and ^), typically from a template
          +             * // E.g. from the 'contacts.details' template
          +             * 
          Item
          + *
          + * + * Basic globbing patterns + *
          +             * $state.$current.name = 'contacts.details.item.url';
          +             *
          +             * $state.includes("*.details.*.*"); // returns true
          +             * $state.includes("*.details.**"); // returns true
          +             * $state.includes("**.item.**"); // returns true
          +             * $state.includes("*.details.item.url"); // returns true
          +             * $state.includes("*.details.*.url"); // returns true
          +             * $state.includes("*.details.*"); // returns false
          +             * $state.includes("item.**"); // returns false
          +             * 
          + * + * @param {string} stateOrName A partial name, relative name, or glob pattern + * to be searched for within the current state name. + * @param {object=} params A param object, e.g. `{sectionId: section.id}`, + * that you'd like to test against the current active state. + * @param {object=} options An options object. The options are: + * + * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set, + * .includes will test relative to `options.relative` state (or name). + * + * @returns {boolean} Returns true if it does include the state + */ + $state.includes = function includes(stateOrName, params, options) { + options = extend({relative: $state.$current}, options || {}); + if (isString(stateOrName) && isGlob(stateOrName)) { + if (!doesStateMatchGlob(stateOrName)) { + return false; + } + stateOrName = $state.$current.name; + } + + var state = findState(stateOrName, options.relative); + if (!isDefined(state)) { + return undefined; + } + if (!isDefined($state.$current.includes[state.name])) { + return false; + } + return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true; + }; + + + /** + * @ngdoc function + * @name ui.router.state.$state#href + * @methodOf ui.router.state.$state + * + * @description + * A url generation method that returns the compiled url for the given state populated with the given params. + * + * @example + *
          +             * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
          +             * 
          + * + * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. + * @param {object=} params An object of parameter values to fill the state's required parameters. + * @param {object=} options Options object. The options are: + * + * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the + * first parameter, then the constructed href url will be built from the first navigable ancestor (aka + * ancestor with a valid url). + * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. + * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), + * defines which state to be relative from. + * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". + * + * @returns {string} compiled state url + */ + $state.href = function href(stateOrName, params, options) { + options = extend({ + lossy: true, + inherit: true, + absolute: false, + relative: $state.$current + }, options || {}); + + var state = findState(stateOrName, options.relative); + + if (!isDefined(state)) return null; + if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state); + + var nav = (state && options.lossy) ? state.navigable : state; + + if (!nav || nav.url === undefined || nav.url === null) { + return null; + } + return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), { + absolute: options.absolute + }); + }; + + /** + * @ngdoc function + * @name ui.router.state.$state#get + * @methodOf ui.router.state.$state + * + * @description + * Returns the state configuration object for any specific state or all states. + * + * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for + * the requested state. If not provided, returns an array of ALL state configs. + * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context. + * @returns {Object|Array} State configuration object or array of all objects. + */ + $state.get = function (stateOrName, context) { + if (arguments.length === 0) return map(objectKeys(states), function (name) { + return states[name].self; + }); + var state = findState(stateOrName, context || $state.$current); + return (state && state.self) ? state.self : null; + }; + + function resolveState(state, params, paramsAreFiltered, inherited, dst, options) { + // Make a restricted $stateParams with only the parameters that apply to this state if + // necessary. In addition to being available to the controller and onEnter/onExit callbacks, + // we also need $stateParams to be available for any $injector calls we make during the + // dependency resolution process. + var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params); + var locals = {$stateParams: $stateParams}; + + // Resolve 'global' dependencies for the state, i.e. those not specific to a view. + // We're also including $stateParams in this; that way the parameters are restricted + // to the set that should be visible to the state, and are independent of when we update + // the global $state and $stateParams values. + dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); + var promises = [dst.resolve.then(function (globals) { + dst.globals = globals; + })]; + if (inherited) promises.push(inherited); + + // Resolve template and dependencies for all views. + forEach(state.views, function (view, name) { + var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); + injectables.$template = [function () { + return $view.load(name, {view: view, locals: locals, params: $stateParams, notify: options.notify}) || ''; + }]; + + promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) { + // References to the controller (only instantiated at link time) + if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { + var injectLocals = angular.extend({}, injectables, locals); + result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); + } else { + result.$$controller = view.controller; + } + // Provide access to the state itself for internal use + result.$$state = state; + result.$$controllerAs = view.controllerAs; + dst[name] = result; + })); + }); + + // Wait for all the promises and then return the activation object + return $q.all(promises).then(function (values) { + return dst; + }); + } + + return $state; + } - function shouldTriggerReload(to, from, locals, options) { - if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) { - return true; + function shouldTriggerReload(to, from, locals, options) { + if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) { + return true; + } + } } - } -} -angular.module('ui.router.state') - .value('$stateParams', {}) - .provider('$state', $StateProvider); + angular.module('ui.router.state') + .value('$stateParams', {}) + .provider('$state', $StateProvider); -$ViewProvider.$inject = []; -function $ViewProvider() { - - this.$get = $get; - /** - * @ngdoc object - * @name ui.router.state.$view - * - * @requires ui.router.util.$templateFactory - * @requires $rootScope - * - * @description - * - */ - $get.$inject = ['$rootScope', '$templateFactory']; - function $get( $rootScope, $templateFactory) { - return { - // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... }) - /** - * @ngdoc function - * @name ui.router.state.$view#load - * @methodOf ui.router.state.$view - * - * @description - * - * @param {string} name name - * @param {object} options option object. - */ - load: function load(name, options) { - var result, defaults = { - template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {} - }; - options = extend(defaults, options); + $ViewProvider.$inject = []; + function $ViewProvider() { - if (options.view) { - result = $templateFactory.fromConfig(options.view, options.params, options.locals); - } - if (result && options.notify) { + this.$get = $get; /** - * @ngdoc event - * @name ui.router.state.$state#$viewContentLoading - * @eventOf ui.router.state.$view - * @eventType broadcast on root scope - * @description - * - * Fired once the view **begins loading**, *before* the DOM is rendered. + * @ngdoc object + * @name ui.router.state.$view * - * @param {Object} event Event object. - * @param {Object} viewConfig The view config properties (template, controller, etc). + * @requires ui.router.util.$templateFactory + * @requires $rootScope * - * @example + * @description * - *
          -         * $scope.$on('$viewContentLoading',
          -         * function(event, viewConfig){
          +         */
          +        $get.$inject = ['$rootScope', '$templateFactory'];
          +        function $get($rootScope, $templateFactory) {
          +            return {
          +                // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
          +                /**
          +                 * @ngdoc function
          +                 * @name ui.router.state.$view#load
          +                 * @methodOf ui.router.state.$view
          +                 *
          +                 * @description
          +                 *
          +                 * @param {string} name name
          +                 * @param {object} options option object.
          +                 */
          +                load: function load(name, options) {
          +                    var result, defaults = {
          +                        template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
          +                    };
          +                    options = extend(defaults, options);
          +
          +                    if (options.view) {
          +                        result = $templateFactory.fromConfig(options.view, options.params, options.locals);
          +                    }
          +                    if (result && options.notify) {
          +                        /**
          +                         * @ngdoc event
          +                         * @name ui.router.state.$state#$viewContentLoading
          +                         * @eventOf ui.router.state.$view
          +                         * @eventType broadcast on root scope
          +                         * @description
          +                         *
          +                         * Fired once the view **begins loading**, *before* the DOM is rendered.
          +                         *
          +                         * @param {Object} event Event object.
          +                         * @param {Object} viewConfig The view config properties (template, controller, etc).
          +                         *
          +                         * @example
          +                         *
          +                         * 
          +                         * $scope.$on('$viewContentLoading',
          +                         * function(event, viewConfig){
                    *     // Access to all the view config properties.
                    *     // and one special property 'targetView'
                    *     // viewConfig.targetView
                    * });
          -         * 
          - */ - $rootScope.$broadcast('$viewContentLoading', options); + *
          + */ + $rootScope.$broadcast('$viewContentLoading', options); + } + return result; + } + }; } - return result; - } - }; - } -} + } -angular.module('ui.router.state').provider('$view', $ViewProvider); + angular.module('ui.router.state').provider('$view', $ViewProvider); -/** - * @ngdoc object - * @name ui.router.state.$uiViewScrollProvider - * - * @description - * Provider that returns the {@link ui.router.state.$uiViewScroll} service function. - */ -function $ViewScrollProvider() { + /** + * @ngdoc object + * @name ui.router.state.$uiViewScrollProvider + * + * @description + * Provider that returns the {@link ui.router.state.$uiViewScroll} service function. + */ + function $ViewScrollProvider() { - var useAnchorScroll = false; + var useAnchorScroll = false; - /** - * @ngdoc function - * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll - * @methodOf ui.router.state.$uiViewScrollProvider - * - * @description - * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for - * scrolling based on the url anchor. - */ - this.useAnchorScroll = function () { - useAnchorScroll = true; - }; - - /** - * @ngdoc object - * @name ui.router.state.$uiViewScroll - * - * @requires $anchorScroll - * @requires $timeout - * - * @description - * When called with a jqLite element, it scrolls the element into view (after a - * `$timeout` so the DOM has time to refresh). - * - * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor, - * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}. - */ - this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { - if (useAnchorScroll) { - return $anchorScroll; - } + /** + * @ngdoc function + * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll + * @methodOf ui.router.state.$uiViewScrollProvider + * + * @description + * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for + * scrolling based on the url anchor. + */ + this.useAnchorScroll = function () { + useAnchorScroll = true; + }; - return function ($element) { - $timeout(function () { - $element[0].scrollIntoView(); - }, 0, false); - }; - }]; -} + /** + * @ngdoc object + * @name ui.router.state.$uiViewScroll + * + * @requires $anchorScroll + * @requires $timeout + * + * @description + * When called with a jqLite element, it scrolls the element into view (after a + * `$timeout` so the DOM has time to refresh). + * + * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor, + * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}. + */ + this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { + if (useAnchorScroll) { + return $anchorScroll; + } + + return function ($element) { + $timeout(function () { + $element[0].scrollIntoView(); + }, 0, false); + }; + }]; + } -angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); + angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); -/** - * @ngdoc directive - * @name ui.router.state.directive:ui-view - * - * @requires ui.router.state.$state - * @requires $compile - * @requires $controller - * @requires $injector - * @requires ui.router.state.$uiViewScroll - * @requires $document - * - * @restrict ECA - * - * @description - * The ui-view directive tells $state where to place your templates. - * - * @param {string=} name A view name. The name should be unique amongst the other views in the - * same state. You can have views of the same name that live in different states. - * - * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window - * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll - * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you - * scroll ui-view elements into view when they are populated during a state activation. - * - * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) - * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.* - * - * @param {string=} onload Expression to evaluate whenever the view updates. - * - * @example - * A view can be unnamed or named. - *
          - * 
          - * 
          - * - * - *
          - *
          - * - * You can only have one unnamed view within any template (or root html). If you are only using a - * single view and it is unnamed then you can populate it like so: - *
          - * 
          - * $stateProvider.state("home", { + /** + * @ngdoc directive + * @name ui.router.state.directive:ui-view + * + * @requires ui.router.state.$state + * @requires $compile + * @requires $controller + * @requires $injector + * @requires ui.router.state.$uiViewScroll + * @requires $document + * + * @restrict ECA + * + * @description + * The ui-view directive tells $state where to place your templates. + * + * @param {string=} name A view name. The name should be unique amongst the other views in the + * same state. You can have views of the same name that live in different states. + * + * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window + * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll + * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you + * scroll ui-view elements into view when they are populated during a state activation. + * + * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) + * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.* + * + * @param {string=} onload Expression to evaluate whenever the view updates. + * + * @example + * A view can be unnamed or named. + *
          +     * 
          +     * 
          + * + * + *
          + *
          + * + * You can only have one unnamed view within any template (or root html). If you are only using a + * single view and it is unnamed then you can populate it like so: + *
          +     * 
          + * $stateProvider.state("home", { * template: "

          HELLO!

          " * }) - *
          - * - * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`} - * config property, by name, in this case an empty name: - *
          - * $stateProvider.state("home", {
          +     * 
          + * + * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`} + * config property, by name, in this case an empty name: + *
          +     * $stateProvider.state("home", {
            *   views: {
            *     "": {
            *       template: "

          HELLO!

          " * } - * } + * } * }) - *
          - * - * But typically you'll only use the views property if you name your view or have more than one view - * in the same template. There's not really a compelling reason to name a view if its the only one, - * but you could if you wanted, like so: - *
          - * 
          - *
          - *
          - * $stateProvider.state("home", {
          +     * 
          + * + * But typically you'll only use the views property if you name your view or have more than one view + * in the same template. There's not really a compelling reason to name a view if its the only one, + * but you could if you wanted, like so: + *
          +     * 
          + *
          + *
          +     * $stateProvider.state("home", {
            *   views: {
            *     "main": {
            *       template: "

          HELLO!

          " * } - * } + * } * }) - *
          - * - * Really though, you'll use views to set up multiple views: - *
          - * 
          - *
          - *
          - *
          - * - *
          - * $stateProvider.state("home", {
          +     * 
          + * + * Really though, you'll use views to set up multiple views: + *
          +     * 
          + *
          + *
          + *
          + * + *
          +     * $stateProvider.state("home", {
            *   views: {
            *     "": {
            *       template: "

          HELLO!

          " @@ -3713,520 +3811,532 @@ angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider) * "data": { * template: "" * } - * } + * } * }) - *
          - * - * Examples for `autoscroll`: - * - *
          - * 
          - * 
          - *
          - * 
          - * 
          - * 
          - * 
          - * 
          - */ -$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate']; -function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) { - - function getService() { - return ($injector.has) ? function(service) { - return $injector.has(service) ? $injector.get(service) : null; - } : function(service) { - try { - return $injector.get(service); - } catch (e) { - return null; - } - }; - } - - var service = getService(), - $animator = service('$animator'), - $animate = service('$animate'); - - // Returns a set of DOM manipulation functions based on which Angular version - // it should use - function getRenderer(attrs, scope) { - var statics = function() { - return { - enter: function (element, target, cb) { target.after(element); cb(); }, - leave: function (element, cb) { element.remove(); cb(); } - }; - }; - - if ($animate) { - return { - enter: function(element, target, cb) { - var promise = $animate.enter(element, null, target, cb); - if (promise && promise.then) promise.then(cb); - }, - leave: function(element, cb) { - var promise = $animate.leave(element, cb); - if (promise && promise.then) promise.then(cb); + *
          + * + * Examples for `autoscroll`: + * + *
          +     * 
          +     * 
          +     *
          +     * 
          +     * 
          +     * 
          +     * 
          +     * 
          + */ + $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate']; + function $ViewDirective($state, $injector, $uiViewScroll, $interpolate) { + + function getService() { + return ($injector.has) ? function (service) { + return $injector.has(service) ? $injector.get(service) : null; + } : function (service) { + try { + return $injector.get(service); + } catch (e) { + return null; + } + }; } - }; - } - - if ($animator) { - var animate = $animator && $animator(scope, attrs); - - return { - enter: function(element, target, cb) {animate.enter(element, null, target); cb(); }, - leave: function(element, cb) { animate.leave(element); cb(); } - }; - } - - return statics(); - } - - var directive = { - restrict: 'ECA', - terminal: true, - priority: 400, - transclude: 'element', - compile: function (tElement, tAttrs, $transclude) { - return function (scope, $element, attrs) { - var previousEl, currentEl, currentScope, latestLocals, - onloadExp = attrs.onload || '', - autoScrollExp = attrs.autoscroll, - renderer = getRenderer(attrs, scope); - - scope.$on('$stateChangeSuccess', function() { - updateView(false); - }); - scope.$on('$viewContentLoading', function() { - updateView(false); - }); - - updateView(true); - - function cleanupLastView() { - if (previousEl) { - previousEl.remove(); - previousEl = null; - } - - if (currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if (currentEl) { - renderer.leave(currentEl, function() { - previousEl = null; - }); - - previousEl = currentEl; - currentEl = null; - } + var service = getService(), + $animator = service('$animator'), + $animate = service('$animate'); + + // Returns a set of DOM manipulation functions based on which Angular version + // it should use + function getRenderer(attrs, scope) { + var statics = function () { + return { + enter: function (element, target, cb) { + target.after(element); + cb(); + }, + leave: function (element, cb) { + element.remove(); + cb(); + } + }; + }; + + if ($animate) { + return { + enter: function (element, target, cb) { + var promise = $animate.enter(element, null, target, cb); + if (promise && promise.then) promise.then(cb); + }, + leave: function (element, cb) { + var promise = $animate.leave(element, cb); + if (promise && promise.then) promise.then(cb); + } + }; + } + + if ($animator) { + var animate = $animator && $animator(scope, attrs); + + return { + enter: function (element, target, cb) { + animate.enter(element, null, target); + cb(); + }, + leave: function (element, cb) { + animate.leave(element); + cb(); + } + }; + } + + return statics(); } - function updateView(firstTime) { - var newScope, - name = getUiViewName(scope, attrs, $element, $interpolate), - previousLocals = name && $state.$current && $state.$current.locals[name]; - - if (!firstTime && previousLocals === latestLocals) return; // nothing to do - newScope = scope.$new(); - latestLocals = $state.$current.locals[name]; - - var clone = $transclude(newScope, function(clone) { - renderer.enter(clone, $element, function onUiViewEnter() { - if(currentScope) { - currentScope.$emit('$viewContentAnimationEnded'); - } + var directive = { + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + compile: function (tElement, tAttrs, $transclude) { + return function (scope, $element, attrs) { + var previousEl, currentEl, currentScope, latestLocals, + onloadExp = attrs.onload || '', + autoScrollExp = attrs.autoscroll, + renderer = getRenderer(attrs, scope); + + scope.$on('$stateChangeSuccess', function () { + updateView(false); + }); + scope.$on('$viewContentLoading', function () { + updateView(false); + }); + + updateView(true); + + function cleanupLastView() { + if (previousEl) { + previousEl.remove(); + previousEl = null; + } + + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + + if (currentEl) { + renderer.leave(currentEl, function () { + previousEl = null; + }); + + previousEl = currentEl; + currentEl = null; + } + } + + function updateView(firstTime) { + var newScope, + name = getUiViewName(scope, attrs, $element, $interpolate), + previousLocals = name && $state.$current && $state.$current.locals[name]; + + if (!firstTime && previousLocals === latestLocals) return; // nothing to do + newScope = scope.$new(); + latestLocals = $state.$current.locals[name]; + + var clone = $transclude(newScope, function (clone) { + renderer.enter(clone, $element, function onUiViewEnter() { + if (currentScope) { + currentScope.$emit('$viewContentAnimationEnded'); + } + + if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { + $uiViewScroll(clone); + } + }); + cleanupLastView(); + }); + + currentEl = clone; + currentScope = newScope; + /** + * @ngdoc event + * @name ui.router.state.directive:ui-view#$viewContentLoaded + * @eventOf ui.router.state.directive:ui-view + * @eventType emits on ui-view directive scope + * @description * + * Fired once the view is **loaded**, *after* the DOM is rendered. + * + * @param {Object} event Event object. + */ + currentScope.$emit('$viewContentLoaded'); + currentScope.$eval(onloadExp); + } + }; + } + }; - if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { - $uiViewScroll(clone); - } - }); - cleanupLastView(); - }); - - currentEl = clone; - currentScope = newScope; - /** - * @ngdoc event - * @name ui.router.state.directive:ui-view#$viewContentLoaded - * @eventOf ui.router.state.directive:ui-view - * @eventType emits on ui-view directive scope - * @description * - * Fired once the view is **loaded**, *after* the DOM is rendered. - * - * @param {Object} event Event object. - */ - currentScope.$emit('$viewContentLoaded'); - currentScope.$eval(onloadExp); - } - }; + return directive; } - }; - - return directive; -} - -$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate']; -function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) { - return { - restrict: 'ECA', - priority: -400, - compile: function (tElement) { - var initial = tElement.html(); - return function (scope, $element, attrs) { - var current = $state.$current, - name = getUiViewName(scope, attrs, $element, $interpolate), - locals = current && current.locals[name]; - - if (! locals) { - return; - } - - $element.data('$uiView', { name: name, state: locals.$$state }); - $element.html(locals.$template ? locals.$template : initial); - var link = $compile($element.contents()); - - if (locals.$$controller) { - locals.$scope = scope; - var controller = $controller(locals.$$controller, locals); - if (locals.$$controllerAs) { - scope[locals.$$controllerAs] = controller; - } - $element.data('$ngControllerController', controller); - $element.children().data('$ngControllerController', controller); - } - - link(scope); - }; + $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate']; + function $ViewDirectiveFill($compile, $controller, $state, $interpolate) { + return { + restrict: 'ECA', + priority: -400, + compile: function (tElement) { + var initial = tElement.html(); + return function (scope, $element, attrs) { + var current = $state.$current, + name = getUiViewName(scope, attrs, $element, $interpolate), + locals = current && current.locals[name]; + + if (!locals) { + return; + } + + $element.data('$uiView', {name: name, state: locals.$$state}); + $element.html(locals.$template ? locals.$template : initial); + + var link = $compile($element.contents()); + + if (locals.$$controller) { + locals.$scope = scope; + var controller = $controller(locals.$$controller, locals); + if (locals.$$controllerAs) { + scope[locals.$$controllerAs] = controller; + } + $element.data('$ngControllerController', controller); + $element.children().data('$ngControllerController', controller); + } + + link(scope); + }; + } + }; } - }; -} - -/** - * Shared ui-view code for both directives: - * Given scope, element, and its attributes, return the view's name - */ -function getUiViewName(scope, attrs, element, $interpolate) { - var name = $interpolate(attrs.uiView || attrs.name || '')(scope); - var inherited = element.inheritedData('$uiView'); - return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : '')); -} - -angular.module('ui.router.state').directive('uiView', $ViewDirective); -angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill); - -function parseStateRef(ref, current) { - var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed; - if (preparsed) ref = current + '(' + preparsed[1] + ')'; - parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/); - if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); - return { state: parsed[1], paramExpr: parsed[3] || null }; -} -function stateContext(el) { - var stateData = el.parent().inheritedData('$uiView'); - - if (stateData && stateData.state && stateData.state.name) { - return stateData.state; - } -} + /** + * Shared ui-view code for both directives: + * Given scope, element, and its attributes, return the view's name + */ + function getUiViewName(scope, attrs, element, $interpolate) { + var name = $interpolate(attrs.uiView || attrs.name || '')(scope); + var inherited = element.inheritedData('$uiView'); + return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : '')); + } -/** - * @ngdoc directive - * @name ui.router.state.directive:ui-sref - * - * @requires ui.router.state.$state - * @requires $timeout - * - * @restrict A - * - * @description - * A directive that binds a link (`` tag) to a state. If the state has an associated - * URL, the directive will automatically generate & update the `href` attribute via - * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking - * the link will trigger a state transition with optional parameters. - * - * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be - * handled natively by the browser. - * - * You can also use relative state paths within ui-sref, just like the relative - * paths passed to `$state.go()`. You just need to be aware that the path is relative - * to the state that the link lives in, in other words the state that loaded the - * template containing the link. - * - * You can specify options to pass to {@link ui.router.state.$state#go $state.go()} - * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`, - * and `reload`. - * - * @example - * Here's an example of how you'd use ui-sref and how it would compile. If you have the - * following template: - *
          - * Home | About | Next page
          - * 
          - * 
          - * 
          - * - * Then the compiled html would be (assuming Html5Mode is off and current state is contacts): - *
          - * Home | About | Next page
          - * 
          - * 
            - *
          • - * Joe - *
          • - *
          • - * Alice - *
          • - *
          • - * Bob - *
          • - *
          - * - * Home - *
          - * - * @param {string} ui-sref 'stateName' can be any valid absolute or relative state - * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()} - */ -$StateRefDirective.$inject = ['$state', '$timeout']; -function $StateRefDirective($state, $timeout) { - var allowedOptions = ['location', 'inherit', 'reload']; - - return { - restrict: 'A', - require: ['?^uiSrefActive', '?^uiSrefActiveEq'], - link: function(scope, element, attrs, uiSrefActive) { - var ref = parseStateRef(attrs.uiSref, $state.current.name); - var params = null, url = null, base = stateContext(element) || $state.$current; - var newHref = null, isAnchor = element.prop("tagName") === "A"; - var isForm = element[0].nodeName === "FORM"; - var attr = isForm ? "action" : "href", nav = true; - - var options = { relative: base, inherit: true }; - var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {}; - - angular.forEach(allowedOptions, function(option) { - if (option in optionsOverride) { - options[option] = optionsOverride[option]; - } - }); + angular.module('ui.router.state').directive('uiView', $ViewDirective); + angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill); - var update = function(newVal) { - if (newVal) params = angular.copy(newVal); - if (!nav) return; + function parseStateRef(ref, current) { + var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed; + if (preparsed) ref = current + '(' + preparsed[1] + ')'; + parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/); + if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); + return {state: parsed[1], paramExpr: parsed[3] || null}; + } - newHref = $state.href(ref.state, params, options); + function stateContext(el) { + var stateData = el.parent().inheritedData('$uiView'); - var activeDirective = uiSrefActive[1] || uiSrefActive[0]; - if (activeDirective) { - activeDirective.$$setStateInfo(ref.state, params); - } - if (newHref === null) { - nav = false; - return false; + if (stateData && stateData.state && stateData.state.name) { + return stateData.state; } - attrs.$set(attr, newHref); - }; - - if (ref.paramExpr) { - scope.$watch(ref.paramExpr, function(newVal, oldVal) { - if (newVal !== params) update(newVal); - }, true); - params = angular.copy(scope.$eval(ref.paramExpr)); - } - update(); - - if (isForm) return; - - element.bind("click", function(e) { - var button = e.which || e.button; - if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) { - // HACK: This is to allow ng-clicks to be processed before the transition is initiated: - var transition = $timeout(function() { - $state.go(ref.state, params, options); - }); - e.preventDefault(); - - // if the state has no URL, ignore one preventDefault from the directive. - var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0; - e.preventDefault = function() { - if (ignorePreventDefaultCount-- <= 0) - $timeout.cancel(transition); - }; - } - }); } - }; -} -/** - * @ngdoc directive - * @name ui.router.state.directive:ui-sref-active - * - * @requires ui.router.state.$state - * @requires ui.router.state.$stateParams - * @requires $interpolate - * - * @restrict A - * - * @description - * A directive working alongside ui-sref to add classes to an element when the - * related ui-sref directive's state is active, and removing them when it is inactive. - * The primary use-case is to simplify the special appearance of navigation menus - * relying on `ui-sref`, by having the "active" state's menu button appear different, - * distinguishing it from the inactive menu items. - * - * ui-sref-active can live on the same element as ui-sref or on a parent element. The first - * ui-sref-active found at the same level or above the ui-sref will be used. - * - * Will activate when the ui-sref's target state or any child state is active. If you - * need to activate only when the ui-sref target state is active and *not* any of - * it's children, then you will use - * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq} - * - * @example - * Given the following template: - *
          - * 
          - * 
          - * - * - * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins", - * the resulting HTML will appear as (note the 'active' class): - *
          - * 
          - * 
          - * - * The class name is interpolated **once** during the directives link time (any further changes to the - * interpolated value are ignored). - * - * Multiple classes may be specified in a space-separated format: - *
          - * 
            - *
          • - * link - *
          • - *
          - *
          - */ + /** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref + * + * @requires ui.router.state.$state + * @requires $timeout + * + * @restrict A + * + * @description + * A directive that binds a link (`` tag) to a state. If the state has an associated + * URL, the directive will automatically generate & update the `href` attribute via + * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking + * the link will trigger a state transition with optional parameters. + * + * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be + * handled natively by the browser. + * + * You can also use relative state paths within ui-sref, just like the relative + * paths passed to `$state.go()`. You just need to be aware that the path is relative + * to the state that the link lives in, in other words the state that loaded the + * template containing the link. + * + * You can specify options to pass to {@link ui.router.state.$state#go $state.go()} + * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`, + * and `reload`. + * + * @example + * Here's an example of how you'd use ui-sref and how it would compile. If you have the + * following template: + *
          +     * Home | About | Next page
          +     *
          +     * 
          +     * 
          + * + * Then the compiled html would be (assuming Html5Mode is off and current state is contacts): + *
          +     * Home | About | Next page
          +     *
          +     * 
            + *
          • + * Joe + *
          • + *
          • + * Alice + *
          • + *
          • + * Bob + *
          • + *
          + * + * Home + *
          + * + * @param {string} ui-sref 'stateName' can be any valid absolute or relative state + * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()} + */ + $StateRefDirective.$inject = ['$state', '$timeout']; + function $StateRefDirective($state, $timeout) { + var allowedOptions = ['location', 'inherit', 'reload']; + + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function (scope, element, attrs, uiSrefActive) { + var ref = parseStateRef(attrs.uiSref, $state.current.name); + var params = null, url = null, base = stateContext(element) || $state.$current; + var newHref = null, isAnchor = element.prop("tagName") === "A"; + var isForm = element[0].nodeName === "FORM"; + var attr = isForm ? "action" : "href", nav = true; + + var options = {relative: base, inherit: true}; + var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {}; + + angular.forEach(allowedOptions, function (option) { + if (option in optionsOverride) { + options[option] = optionsOverride[option]; + } + }); + + var update = function (newVal) { + if (newVal) params = angular.copy(newVal); + if (!nav) return; + + newHref = $state.href(ref.state, params, options); + + var activeDirective = uiSrefActive[1] || uiSrefActive[0]; + if (activeDirective) { + activeDirective.$$setStateInfo(ref.state, params); + } + if (newHref === null) { + nav = false; + return false; + } + attrs.$set(attr, newHref); + }; + + if (ref.paramExpr) { + scope.$watch(ref.paramExpr, function (newVal, oldVal) { + if (newVal !== params) update(newVal); + }, true); + params = angular.copy(scope.$eval(ref.paramExpr)); + } + update(); + + if (isForm) return; + + element.bind("click", function (e) { + var button = e.which || e.button; + if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target'))) { + // HACK: This is to allow ng-clicks to be processed before the transition is initiated: + var transition = $timeout(function () { + $state.go(ref.state, params, options); + }); + e.preventDefault(); + + // if the state has no URL, ignore one preventDefault from the directive. + var ignorePreventDefaultCount = isAnchor && !newHref ? 1 : 0; + e.preventDefault = function () { + if (ignorePreventDefaultCount-- <= 0) + $timeout.cancel(transition); + }; + } + }); + } + }; + } -/** - * @ngdoc directive - * @name ui.router.state.directive:ui-sref-active-eq - * - * @requires ui.router.state.$state - * @requires ui.router.state.$stateParams - * @requires $interpolate - * - * @restrict A - * - * @description - * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate - * when the exact target state used in the `ui-sref` is active; no child states. - * - */ -$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate']; -function $StateRefActiveDirective($state, $stateParams, $interpolate) { - return { - restrict: "A", - controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { - var state, params, activeClass; - - // There probably isn't much point in $observing this - // uiSrefActive and uiSrefActiveEq share the same directive object with some - // slight difference in logic routing - activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope); - - // Allow uiSref to communicate with uiSrefActive[Equals] - this.$$setStateInfo = function (newState, newParams) { - state = $state.get(newState, stateContext($element)); - params = newParams; - update(); - }; - - $scope.$on('$stateChangeSuccess', update); - - // Update route state - function update() { - if (isMatch()) { - $element.addClass(activeClass); - } else { - $element.removeClass(activeClass); - } - } + /** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref-active + * + * @requires ui.router.state.$state + * @requires ui.router.state.$stateParams + * @requires $interpolate + * + * @restrict A + * + * @description + * A directive working alongside ui-sref to add classes to an element when the + * related ui-sref directive's state is active, and removing them when it is inactive. + * The primary use-case is to simplify the special appearance of navigation menus + * relying on `ui-sref`, by having the "active" state's menu button appear different, + * distinguishing it from the inactive menu items. + * + * ui-sref-active can live on the same element as ui-sref or on a parent element. The first + * ui-sref-active found at the same level or above the ui-sref will be used. + * + * Will activate when the ui-sref's target state or any child state is active. If you + * need to activate only when the ui-sref target state is active and *not* any of + * it's children, then you will use + * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq} + * + * @example + * Given the following template: + *
          +     * 
          +     * 
          + * + * + * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins", + * the resulting HTML will appear as (note the 'active' class): + *
          +     * 
          +     * 
          + * + * The class name is interpolated **once** during the directives link time (any further changes to the + * interpolated value are ignored). + * + * Multiple classes may be specified in a space-separated format: + *
          +     * 
            + *
          • + * link + *
          • + *
          + *
          + */ - function isMatch() { - if (typeof $attrs.uiSrefActiveEq !== 'undefined') { - return state && $state.is(state.name, params); - } else { - return state && $state.includes(state.name, params); - } - } - }] - }; -} + /** + * @ngdoc directive + * @name ui.router.state.directive:ui-sref-active-eq + * + * @requires ui.router.state.$state + * @requires ui.router.state.$stateParams + * @requires $interpolate + * + * @restrict A + * + * @description + * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate + * when the exact target state used in the `ui-sref` is active; no child states. + * + */ + $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate']; + function $StateRefActiveDirective($state, $stateParams, $interpolate) { + return { + restrict: "A", + controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { + var state, params, activeClass; + + // There probably isn't much point in $observing this + // uiSrefActive and uiSrefActiveEq share the same directive object with some + // slight difference in logic routing + activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope); + + // Allow uiSref to communicate with uiSrefActive[Equals] + this.$$setStateInfo = function (newState, newParams) { + state = $state.get(newState, stateContext($element)); + params = newParams; + update(); + }; + + $scope.$on('$stateChangeSuccess', update); + + // Update route state + function update() { + if (isMatch()) { + $element.addClass(activeClass); + } else { + $element.removeClass(activeClass); + } + } + + function isMatch() { + if (typeof $attrs.uiSrefActiveEq !== 'undefined') { + return state && $state.is(state.name, params); + } else { + return state && $state.includes(state.name, params); + } + } + }] + }; + } -angular.module('ui.router.state') - .directive('uiSref', $StateRefDirective) - .directive('uiSrefActive', $StateRefActiveDirective) - .directive('uiSrefActiveEq', $StateRefActiveDirective); + angular.module('ui.router.state') + .directive('uiSref', $StateRefDirective) + .directive('uiSrefActive', $StateRefActiveDirective) + .directive('uiSrefActiveEq', $StateRefActiveDirective); -/** - * @ngdoc filter - * @name ui.router.state.filter:isState - * - * @requires ui.router.state.$state - * - * @description - * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}. - */ -$IsStateFilter.$inject = ['$state']; -function $IsStateFilter($state) { - var isFilter = function (state) { - return $state.is(state); - }; - isFilter.$stateful = true; - return isFilter; -} + /** + * @ngdoc filter + * @name ui.router.state.filter:isState + * + * @requires ui.router.state.$state + * + * @description + * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}. + */ + $IsStateFilter.$inject = ['$state']; + function $IsStateFilter($state) { + var isFilter = function (state) { + return $state.is(state); + }; + isFilter.$stateful = true; + return isFilter; + } -/** - * @ngdoc filter - * @name ui.router.state.filter:includedByState - * - * @requires ui.router.state.$state - * - * @description - * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}. - */ -$IncludedByStateFilter.$inject = ['$state']; -function $IncludedByStateFilter($state) { - var includesFilter = function (state) { - return $state.includes(state); - }; - includesFilter.$stateful = true; - return includesFilter; -} + /** + * @ngdoc filter + * @name ui.router.state.filter:includedByState + * + * @requires ui.router.state.$state + * + * @description + * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}. + */ + $IncludedByStateFilter.$inject = ['$state']; + function $IncludedByStateFilter($state) { + var includesFilter = function (state) { + return $state.includes(state); + }; + includesFilter.$stateful = true; + return includesFilter; + } -angular.module('ui.router.state') - .filter('isState', $IsStateFilter) - .filter('includedByState', $IncludedByStateFilter); + angular.module('ui.router.state') + .filter('isState', $IsStateFilter) + .filter('includedByState', $IncludedByStateFilter); })(window, window.angular); \ No newline at end of file diff --git a/projects/webui/base/src/main/resources/js/libs/angularjs/angular.js b/projects/webui/base/src/main/resources/js/libs/angularjs/angular.js index 0d6d4d56..fd31f558 100644 --- a/projects/webui/base/src/main/resources/js/libs/angularjs/angular.js +++ b/projects/webui/base/src/main/resources/js/libs/angularjs/angular.js @@ -3,796 +3,827 @@ * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ -(function(window, document, undefined) {'use strict'; +(function (window, document, undefined) { + 'use strict'; -/** - * @description - * - * This object provides a utility for producing rich Error messages within - * Angular. It can be called as follows: - * - * var exampleMinErr = minErr('example'); - * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); - * - * The above creates an instance of minErr in the example namespace. The - * resulting error will have a namespaced error code of example.one. The - * resulting error will replace {0} with the value of foo, and {1} with the - * value of bar. The object is not restricted in the number of arguments it can - * take. - * - * If fewer arguments are specified than necessary for interpolation, the extra - * interpolation markers will be preserved in the final string. - * - * Since data will be parsed statically during a build step, some restrictions - * are applied with respect to how minErr instances are created and called. - * Instances should have names of the form namespaceMinErr for a minErr created - * using minErr('namespace') . Error codes, namespaces and template strings - * should all be static strings, not variables or general expressions. - * - * @param {string} module The namespace to use for the new minErr instance. - * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning - * error from returned function, for cases when a particular type of error is useful. - * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance - */ + /** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning + * error from returned function, for cases when a particular type of error is useful. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ -function minErr(module, ErrorConstructor) { - ErrorConstructor = ErrorConstructor || Error; - return function () { - var code = arguments[0], - prefix = '[' + (module ? module + ':' : '') + code + '] ', - template = arguments[1], - templateArgs = arguments, - stringify = function (obj) { - if (typeof obj === 'function') { - return obj.toString().replace(/ \{[\s\S]*$/, ''); - } else if (typeof obj === 'undefined') { - return 'undefined'; - } else if (typeof obj !== 'string') { - return JSON.stringify(obj); - } - return obj; - }, - message, i; - - message = prefix + template.replace(/\{\d+\}/g, function (match) { - var index = +match.slice(1, -1), arg; - - if (index + 2 < templateArgs.length) { - arg = templateArgs[index + 2]; - if (typeof arg === 'function') { - return arg.toString().replace(/ ?\{[\s\S]*$/, ''); - } else if (typeof arg === 'undefined') { - return 'undefined'; - } else if (typeof arg !== 'string') { - return toJson(arg); - } - return arg; - } - return match; - }); + function minErr(module, ErrorConstructor) { + ErrorConstructor = ErrorConstructor || Error; + return function () { + var code = arguments[0], + prefix = '[' + (module ? module + ':' : '') + code + '] ', + template = arguments[1], + templateArgs = arguments, + stringify = function (obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (typeof obj === 'undefined') { + return 'undefined'; + } else if (typeof obj !== 'string') { + return JSON.stringify(obj); + } + return obj; + }, + message, i; + + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; + + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (typeof arg === 'function') { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (typeof arg === 'undefined') { + return 'undefined'; + } else if (typeof arg !== 'string') { + return toJson(arg); + } + return arg; + } + return match; + }); - message = message + '\nhttp://errors.angularjs.org/1.3.0/' + - (module ? module + '/' : '') + code; - for (i = 2; i < arguments.length; i++) { - message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + - encodeURIComponent(stringify(arguments[i])); + message = message + '\nhttp://errors.angularjs.org/1.3.0/' + + (module ? module + '/' : '') + code; + for (i = 2; i < arguments.length; i++) { + message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' + + encodeURIComponent(stringify(arguments[i])); + } + return new ErrorConstructor(message); + }; } - return new ErrorConstructor(message); - }; -} - -/* We need to tell jshint what variables are being exported */ -/* global angular: true, - msie: true, - jqLite: true, - jQuery: true, - slice: true, - splice: true, - push: true, - toString: true, - ngMinErr: true, - angularModule: true, - uid: true, - REGEX_STRING_REGEXP: true, - VALIDITY_STATE_PROPERTY: true, - - lowercase: true, - uppercase: true, - manualLowercase: true, - manualUppercase: true, - nodeName_: true, - isArrayLike: true, - forEach: true, - sortedKeys: true, - forEachSorted: true, - reverseParams: true, - nextUid: true, - setHashKey: true, - extend: true, - int: true, - inherit: true, - noop: true, - identity: true, - valueFn: true, - isUndefined: true, - isDefined: true, - isObject: true, - isString: true, - isNumber: true, - isDate: true, - isArray: true, - isFunction: true, - isRegExp: true, - isWindow: true, - isScope: true, - isFile: true, - isBlob: true, - isBoolean: true, - isPromiseLike: true, - trim: true, - isElement: true, - makeMap: true, - size: true, - includes: true, - arrayRemove: true, - isLeafNode: true, - copy: true, - shallowCopy: true, - equals: true, - csp: true, - concat: true, - sliceArgs: true, - bind: true, - toJsonReplacer: true, - toJson: true, - fromJson: true, - startingTag: true, - tryDecodeURIComponent: true, - parseKeyValue: true, - toKeyValue: true, - encodeUriSegment: true, - encodeUriQuery: true, - angularInit: true, - bootstrap: true, - getTestability: true, - snake_case: true, - bindJQuery: true, - assertArg: true, - assertArgFn: true, - assertNotHasOwnProperty: true, - getter: true, - getBlockNodes: true, - hasOwnProperty: true, - createMap: true, - - NODE_TYPE_ELEMENT: true, - NODE_TYPE_TEXT: true, - NODE_TYPE_COMMENT: true, - NODE_TYPE_DOCUMENT: true, - NODE_TYPE_DOCUMENT_FRAGMENT: true, -*/ + + /* We need to tell jshint what variables are being exported */ + /* global angular: true, + msie: true, + jqLite: true, + jQuery: true, + slice: true, + splice: true, + push: true, + toString: true, + ngMinErr: true, + angularModule: true, + uid: true, + REGEX_STRING_REGEXP: true, + VALIDITY_STATE_PROPERTY: true, + + lowercase: true, + uppercase: true, + manualLowercase: true, + manualUppercase: true, + nodeName_: true, + isArrayLike: true, + forEach: true, + sortedKeys: true, + forEachSorted: true, + reverseParams: true, + nextUid: true, + setHashKey: true, + extend: true, + int: true, + inherit: true, + noop: true, + identity: true, + valueFn: true, + isUndefined: true, + isDefined: true, + isObject: true, + isString: true, + isNumber: true, + isDate: true, + isArray: true, + isFunction: true, + isRegExp: true, + isWindow: true, + isScope: true, + isFile: true, + isBlob: true, + isBoolean: true, + isPromiseLike: true, + trim: true, + isElement: true, + makeMap: true, + size: true, + includes: true, + arrayRemove: true, + isLeafNode: true, + copy: true, + shallowCopy: true, + equals: true, + csp: true, + concat: true, + sliceArgs: true, + bind: true, + toJsonReplacer: true, + toJson: true, + fromJson: true, + startingTag: true, + tryDecodeURIComponent: true, + parseKeyValue: true, + toKeyValue: true, + encodeUriSegment: true, + encodeUriQuery: true, + angularInit: true, + bootstrap: true, + getTestability: true, + snake_case: true, + bindJQuery: true, + assertArg: true, + assertArgFn: true, + assertNotHasOwnProperty: true, + getter: true, + getBlockNodes: true, + hasOwnProperty: true, + createMap: true, + + NODE_TYPE_ELEMENT: true, + NODE_TYPE_TEXT: true, + NODE_TYPE_COMMENT: true, + NODE_TYPE_DOCUMENT: true, + NODE_TYPE_DOCUMENT_FRAGMENT: true, + */ //////////////////////////////////// -/** - * @ngdoc module - * @name ng - * @module ng - * @description - * - * # ng (core module) - * The ng module is loaded by default when an AngularJS application is started. The module itself - * contains the essential components for an AngularJS application to function. The table below - * lists a high level breakdown of each of the services/factories, filters, directives and testing - * components available within this core module. - * - *
          - */ + /** + * @ngdoc module + * @name ng + * @module ng + * @description + * + * # ng (core module) + * The ng module is loaded by default when an AngularJS application is started. The module itself + * contains the essential components for an AngularJS application to function. The table below + * lists a high level breakdown of each of the services/factories, filters, directives and testing + * components available within this core module. + * + *
          + */ -var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; + var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; // The name of a form control's ValidityState property. // This is used so that it's possible for internal tests to create mock ValidityStates. -var VALIDITY_STATE_PROPERTY = 'validity'; + var VALIDITY_STATE_PROPERTY = 'validity'; -/** - * @ngdoc function - * @name angular.lowercase - * @module ng - * @kind function - * - * @description Converts the specified string to lowercase. - * @param {string} string String to be converted to lowercase. - * @returns {string} Lowercased string. - */ -var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; -var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * @ngdoc function + * @name angular.lowercase + * @module ng + * @kind function + * + * @description Converts the specified string to lowercase. + * @param {string} string String to be converted to lowercase. + * @returns {string} Lowercased string. + */ + var lowercase = function (string) { + return isString(string) ? string.toLowerCase() : string; + }; + var hasOwnProperty = Object.prototype.hasOwnProperty; -/** - * @ngdoc function - * @name angular.uppercase - * @module ng - * @kind function - * - * @description Converts the specified string to uppercase. - * @param {string} string String to be converted to uppercase. - * @returns {string} Uppercased string. - */ -var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; + /** + * @ngdoc function + * @name angular.uppercase + * @module ng + * @kind function + * + * @description Converts the specified string to uppercase. + * @param {string} string String to be converted to uppercase. + * @returns {string} Uppercased string. + */ + var uppercase = function (string) { + return isString(string) ? string.toUpperCase() : string; + }; -var manualLowercase = function(s) { - /* jshint bitwise: false */ - return isString(s) - ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) - : s; -}; -var manualUppercase = function(s) { - /* jshint bitwise: false */ - return isString(s) - ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) - : s; -}; + var manualLowercase = function (s) { + /* jshint bitwise: false */ + return isString(s) + ? s.replace(/[A-Z]/g, function (ch) { + return String.fromCharCode(ch.charCodeAt(0) | 32); + }) + : s; + }; + var manualUppercase = function (s) { + /* jshint bitwise: false */ + return isString(s) + ? s.replace(/[a-z]/g, function (ch) { + return String.fromCharCode(ch.charCodeAt(0) & ~32); + }) + : s; + }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. -if ('i' !== 'I'.toLowerCase()) { - lowercase = manualLowercase; - uppercase = manualUppercase; -} - - -var /** holds major version number for IE or NaN for real browsers */ - msie, - jqLite, // delay binding since jQuery could be loaded after us. - jQuery, // delay binding - slice = [].slice, - splice = [].splice, - push = [].push, - toString = Object.prototype.toString, - ngMinErr = minErr('ng'), - - /** @name angular */ - angular = window.angular || (window.angular = {}), - angularModule, - uid = 0; + if ('i' !== 'I'.toLowerCase()) { + lowercase = manualLowercase; + uppercase = manualUppercase; + } -/** - * documentMode is an IE-only property - * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx - */ -msie = document.documentMode; + var /** holds major version number for IE or NaN for real browsers */ + msie, + jqLite, // delay binding since jQuery could be loaded after us. + jQuery, // delay binding + slice = [].slice, + splice = [].splice, + push = [].push, + toString = Object.prototype.toString, + ngMinErr = minErr('ng'), -/** - * @private - * @param {*} obj - * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, - * String ...) - */ -function isArrayLike(obj) { - if (obj == null || isWindow(obj)) { - return false; - } + /** @name angular */ + angular = window.angular || (window.angular = {}), + angularModule, + uid = 0; + + /** + * documentMode is an IE-only property + * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx + */ + msie = document.documentMode; - var length = obj.length; - if (obj.nodeType === NODE_TYPE_ELEMENT && length) { - return true; - } + /** + * @private + * @param {*} obj + * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, + * String ...) + */ + function isArrayLike(obj) { + if (obj == null || isWindow(obj)) { + return false; + } - return isString(obj) || isArray(obj) || length === 0 || - typeof length === 'number' && length > 0 && (length - 1) in obj; -} + var length = obj.length; -/** - * @ngdoc function - * @name angular.forEach - * @module ng - * @kind function - * - * @description - * Invokes the `iterator` function once for each item in `obj` collection, which can be either an - * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` - * is the value of an object property or an array element, `key` is the object property key or - * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. - * - * It is worth noting that `.forEach` does not iterate over inherited properties because it filters - * using the `hasOwnProperty` method. - * - ```js + if (obj.nodeType === NODE_TYPE_ELEMENT && length) { + return true; + } + + return isString(obj) || isArray(obj) || length === 0 || + typeof length === 'number' && length > 0 && (length - 1) in obj; + } + + /** + * @ngdoc function + * @name angular.forEach + * @module ng + * @kind function + * + * @description + * Invokes the `iterator` function once for each item in `obj` collection, which can be either an + * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` + * is the value of an object property or an array element, `key` is the object property key or + * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. + * + * It is worth noting that `.forEach` does not iterate over inherited properties because it filters + * using the `hasOwnProperty` method. + * + ```js var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); - ``` - * - * @param {Object|Array} obj Object to iterate over. - * @param {Function} iterator Iterator function. - * @param {Object=} context Object to become context (`this`) for the iterator function. - * @returns {Object|Array} Reference to `obj`. - */ + ``` + * + * @param {Object|Array} obj Object to iterate over. + * @param {Function} iterator Iterator function. + * @param {Object=} context Object to become context (`this`) for the iterator function. + * @returns {Object|Array} Reference to `obj`. + */ -function forEach(obj, iterator, context) { - var key, length; - if (obj) { - if (isFunction(obj)) { - for (key in obj) { - // Need to check if hasOwnProperty exists, - // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function - if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { - iterator.call(context, obj[key], key, obj); - } - } - } else if (isArray(obj) || isArrayLike(obj)) { - var isPrimitive = typeof obj !== 'object'; - for (key = 0, length = obj.length; key < length; key++) { - if (isPrimitive || key in obj) { - iterator.call(context, obj[key], key, obj); + function forEach(obj, iterator, context) { + var key, length; + if (obj) { + if (isFunction(obj)) { + for (key in obj) { + // Need to check if hasOwnProperty exists, + // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function + if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { + iterator.call(context, obj[key], key, obj); + } + } + } else if (isArray(obj) || isArrayLike(obj)) { + var isPrimitive = typeof obj !== 'object'; + for (key = 0, length = obj.length; key < length; key++) { + if (isPrimitive || key in obj) { + iterator.call(context, obj[key], key, obj); + } + } + } else if (obj.forEach && obj.forEach !== forEach) { + obj.forEach(iterator, context, obj); + } else { + for (key in obj) { + if (obj.hasOwnProperty(key)) { + iterator.call(context, obj[key], key, obj); + } + } + } } - } - } else if (obj.forEach && obj.forEach !== forEach) { - obj.forEach(iterator, context, obj); - } else { - for (key in obj) { - if (obj.hasOwnProperty(key)) { - iterator.call(context, obj[key], key, obj); + return obj; + } + + function sortedKeys(obj) { + var keys = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys.push(key); + } } - } + return keys.sort(); } - } - return obj; -} - -function sortedKeys(obj) { - var keys = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - keys.push(key); + + function forEachSorted(obj, iterator, context) { + var keys = sortedKeys(obj); + for (var i = 0; i < keys.length; i++) { + iterator.call(context, obj[keys[i]], keys[i]); + } + return keys; } - } - return keys.sort(); -} -function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); - for ( var i = 0; i < keys.length; i++) { - iterator.call(context, obj[keys[i]], keys[i]); - } - return keys; -} + /** + * when using forEach the params are value, key, but it is often useful to have key, value. + * @param {function(string, *)} iteratorFn + * @returns {function(*, string)} + */ + function reverseParams(iteratorFn) { + return function (value, key) { + iteratorFn(key, value); + }; + } -/** - * when using forEach the params are value, key, but it is often useful to have key, value. - * @param {function(string, *)} iteratorFn - * @returns {function(*, string)} - */ -function reverseParams(iteratorFn) { - return function(value, key) { iteratorFn(key, value); }; -} + /** + * A consistent way of creating unique IDs in angular. + * + * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before + * we hit number precision issues in JavaScript. + * + * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M + * + * @returns {number} an unique alpha-numeric string + */ + function nextUid() { + return ++uid; + } -/** - * A consistent way of creating unique IDs in angular. - * - * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before - * we hit number precision issues in JavaScript. - * - * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M - * - * @returns {number} an unique alpha-numeric string - */ -function nextUid() { - return ++uid; -} + /** + * Set or clear the hashkey for an object. + * @param obj object + * @param h the hashkey (!truthy to delete the hashkey) + */ + function setHashKey(obj, h) { + if (h) { + obj.$$hashKey = h; + } + else { + delete obj.$$hashKey; + } + } -/** - * Set or clear the hashkey for an object. - * @param obj object - * @param h the hashkey (!truthy to delete the hashkey) - */ -function setHashKey(obj, h) { - if (h) { - obj.$$hashKey = h; - } - else { - delete obj.$$hashKey; - } -} + /** + * @ngdoc function + * @name angular.extend + * @module ng + * @kind function + * + * @description + * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) + * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so + * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. + * + * @param {Object} dst Destination object. + * @param {...Object} src Source object(s). + * @returns {Object} Reference to `dst`. + */ + function extend(dst) { + var h = dst.$$hashKey; + + for (var i = 1, ii = arguments.length; i < ii; i++) { + var obj = arguments[i]; + if (obj) { + var keys = Object.keys(obj); + for (var j = 0, jj = keys.length; j < jj; j++) { + var key = keys[j]; + dst[key] = obj[key]; + } + } + } -/** - * @ngdoc function - * @name angular.extend - * @module ng - * @kind function - * - * @description - * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) - * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so - * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. - * - * @param {Object} dst Destination object. - * @param {...Object} src Source object(s). - * @returns {Object} Reference to `dst`. - */ -function extend(dst) { - var h = dst.$$hashKey; - - for (var i = 1, ii = arguments.length; i < ii; i++) { - var obj = arguments[i]; - if (obj) { - var keys = Object.keys(obj); - for (var j = 0, jj = keys.length; j < jj; j++) { - var key = keys[j]; - dst[key] = obj[key]; - } + setHashKey(dst, h); + return dst; } - } - - setHashKey(dst, h); - return dst; -} -function int(str) { - return parseInt(str, 10); -} + function int(str) { + return parseInt(str, 10); + } -function inherit(parent, extra) { - return extend(new (extend(function() {}, {prototype:parent}))(), extra); -} + function inherit(parent, extra) { + return extend(new (extend(function () { + }, {prototype: parent}))(), extra); + } -/** - * @ngdoc function - * @name angular.noop - * @module ng - * @kind function - * - * @description - * A function that performs no operations. This function can be useful when writing code in the - * functional style. - ```js + /** + * @ngdoc function + * @name angular.noop + * @module ng + * @kind function + * + * @description + * A function that performs no operations. This function can be useful when writing code in the + * functional style. + ```js function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } - ``` - */ -function noop() {} -noop.$inject = []; + ``` + */ + function noop() { + } + noop.$inject = []; -/** - * @ngdoc function - * @name angular.identity - * @module ng - * @kind function - * - * @description - * A function that returns its first argument. This function is useful when writing code in the - * functional style. - * - ```js + + /** + * @ngdoc function + * @name angular.identity + * @module ng + * @kind function + * + * @description + * A function that returns its first argument. This function is useful when writing code in the + * functional style. + * + ```js function transformer(transformationFn, value) { return (transformationFn || angular.identity)(value); }; - ``` - */ -function identity($) {return $;} -identity.$inject = []; - + ``` + */ + function identity($) { + return $; + } -function valueFn(value) {return function() {return value;};} + identity.$inject = []; -/** - * @ngdoc function - * @name angular.isUndefined - * @module ng - * @kind function - * - * @description - * Determines if a reference is undefined. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is undefined. - */ -function isUndefined(value){return typeof value === 'undefined';} + function valueFn(value) { + return function () { + return value; + }; + } -/** - * @ngdoc function - * @name angular.isDefined - * @module ng - * @kind function - * - * @description - * Determines if a reference is defined. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is defined. - */ -function isDefined(value){return typeof value !== 'undefined';} + /** + * @ngdoc function + * @name angular.isUndefined + * @module ng + * @kind function + * + * @description + * Determines if a reference is undefined. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is undefined. + */ + function isUndefined(value) { + return typeof value === 'undefined'; + } -/** - * @ngdoc function - * @name angular.isObject - * @module ng - * @kind function - * - * @description - * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not - * considered to be objects. Note that JavaScript arrays are objects. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is an `Object` but not `null`. - */ -function isObject(value){ - // http://jsperf.com/isobject4 - return value !== null && typeof value === 'object'; -} + /** + * @ngdoc function + * @name angular.isDefined + * @module ng + * @kind function + * + * @description + * Determines if a reference is defined. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is defined. + */ + function isDefined(value) { + return typeof value !== 'undefined'; + } -/** - * @ngdoc function - * @name angular.isString - * @module ng - * @kind function - * - * @description - * Determines if a reference is a `String`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `String`. - */ -function isString(value){return typeof value === 'string';} + /** + * @ngdoc function + * @name angular.isObject + * @module ng + * @kind function + * + * @description + * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not + * considered to be objects. Note that JavaScript arrays are objects. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Object` but not `null`. + */ + function isObject(value) { + // http://jsperf.com/isobject4 + return value !== null && typeof value === 'object'; + } -/** - * @ngdoc function - * @name angular.isNumber - * @module ng - * @kind function - * - * @description - * Determines if a reference is a `Number`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Number`. - */ -function isNumber(value){return typeof value === 'number';} + /** + * @ngdoc function + * @name angular.isString + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `String`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `String`. + */ + function isString(value) { + return typeof value === 'string'; + } -/** - * @ngdoc function - * @name angular.isDate - * @module ng - * @kind function - * - * @description - * Determines if a value is a date. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Date`. - */ -function isDate(value) { - return toString.call(value) === '[object Date]'; -} + /** + * @ngdoc function + * @name angular.isNumber + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `Number`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Number`. + */ + function isNumber(value) { + return typeof value === 'number'; + } -/** - * @ngdoc function - * @name angular.isArray - * @module ng - * @kind function - * - * @description - * Determines if a reference is an `Array`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is an `Array`. - */ -var isArray = Array.isArray; + /** + * @ngdoc function + * @name angular.isDate + * @module ng + * @kind function + * + * @description + * Determines if a value is a date. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Date`. + */ + function isDate(value) { + return toString.call(value) === '[object Date]'; + } -/** - * @ngdoc function - * @name angular.isFunction - * @module ng - * @kind function - * - * @description - * Determines if a reference is a `Function`. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `Function`. - */ -function isFunction(value){return typeof value === 'function';} + /** + * @ngdoc function + * @name angular.isArray + * @module ng + * @kind function + * + * @description + * Determines if a reference is an `Array`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Array`. + */ + var isArray = Array.isArray; -/** - * Determines if a value is a regular expression object. - * - * @private - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a `RegExp`. - */ -function isRegExp(value) { - return toString.call(value) === '[object RegExp]'; -} + /** + * @ngdoc function + * @name angular.isFunction + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `Function`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Function`. + */ + function isFunction(value) { + return typeof value === 'function'; + } -/** - * Checks if `obj` is a window object. - * - * @private - * @param {*} obj Object to check - * @returns {boolean} True if `obj` is a window obj. - */ -function isWindow(obj) { - return obj && obj.window === obj; -} + /** + * Determines if a value is a regular expression object. + * + * @private + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `RegExp`. + */ + function isRegExp(value) { + return toString.call(value) === '[object RegExp]'; + } + + /** + * Checks if `obj` is a window object. + * + * @private + * @param {*} obj Object to check + * @returns {boolean} True if `obj` is a window obj. + */ + function isWindow(obj) { + return obj && obj.window === obj; + } -function isScope(obj) { - return obj && obj.$evalAsync && obj.$watch; -} + function isScope(obj) { + return obj && obj.$evalAsync && obj.$watch; + } -function isFile(obj) { - return toString.call(obj) === '[object File]'; -} + function isFile(obj) { + return toString.call(obj) === '[object File]'; + } -function isBlob(obj) { - return toString.call(obj) === '[object Blob]'; -} + function isBlob(obj) { + return toString.call(obj) === '[object Blob]'; + } -function isBoolean(value) { - return typeof value === 'boolean'; -} + function isBoolean(value) { + return typeof value === 'boolean'; + } -function isPromiseLike(obj) { - return obj && isFunction(obj.then); -} + function isPromiseLike(obj) { + return obj && isFunction(obj.then); + } -var trim = function(value) { - return isString(value) ? value.trim() : value; -}; + var trim = function (value) { + return isString(value) ? value.trim() : value; + }; -/** - * @ngdoc function - * @name angular.isElement - * @module ng - * @kind function - * - * @description - * Determines if a reference is a DOM element (or wrapped jQuery element). - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). - */ -function isElement(node) { - return !!(node && - (node.nodeName // we are a direct element - || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API -} -/** - * @param str 'key1,key2,...' - * @returns {object} in the form of {key1:true, key2:true, ...} - */ -function makeMap(str) { - var obj = {}, items = str.split(","), i; - for ( i = 0; i < items.length; i++ ) - obj[ items[i] ] = true; - return obj; -} + /** + * @ngdoc function + * @name angular.isElement + * @module ng + * @kind function + * + * @description + * Determines if a reference is a DOM element (or wrapped jQuery element). + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). + */ + function isElement(node) { + return !!(node && + (node.nodeName // we are a direct element + || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API + } + + /** + * @param str 'key1,key2,...' + * @returns {object} in the form of {key1:true, key2:true, ...} + */ + function makeMap(str) { + var obj = {}, items = str.split(","), i; + for (i = 0; i < items.length; i++) + obj[items[i]] = true; + return obj; + } -function nodeName_(element) { - return lowercase(element.nodeName || element[0].nodeName); -} + function nodeName_(element) { + return lowercase(element.nodeName || element[0].nodeName); + } -/** - * @description - * Determines the number of elements in an array, the number of properties an object has, or - * the length of a string. - * - * Note: This function is used to augment the Object type in Angular expressions. See - * {@link angular.Object} for more information about Angular arrays. - * - * @param {Object|Array|string} obj Object, array, or string to inspect. - * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object - * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. - */ -function size(obj, ownPropsOnly) { - var count = 0, key; - - if (isArray(obj) || isString(obj)) { - return obj.length; - } else if (isObject(obj)) { - for (key in obj) - if (!ownPropsOnly || obj.hasOwnProperty(key)) - count++; - } - - return count; -} - - -function includes(array, obj) { - return Array.prototype.indexOf.call(array, obj) != -1; -} - -function arrayRemove(array, value) { - var index = array.indexOf(value); - if (index >=0) - array.splice(index, 1); - return value; -} - -function isLeafNode (node) { - if (node) { - switch (nodeName_(node)) { - case "option": - case "pre": - case "title": - return true; + /** + * @description + * Determines the number of elements in an array, the number of properties an object has, or + * the length of a string. + * + * Note: This function is used to augment the Object type in Angular expressions. See + * {@link angular.Object} for more information about Angular arrays. + * + * @param {Object|Array|string} obj Object, array, or string to inspect. + * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object + * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. + */ + function size(obj, ownPropsOnly) { + var count = 0, key; + + if (isArray(obj) || isString(obj)) { + return obj.length; + } else if (isObject(obj)) { + for (key in obj) + if (!ownPropsOnly || obj.hasOwnProperty(key)) + count++; + } + + return count; } - } - return false; -} -/** - * @ngdoc function - * @name angular.copy - * @module ng - * @kind function - * - * @description - * Creates a deep copy of `source`, which should be an object or an array. - * - * * If no destination is supplied, a copy of the object or array is created. - * * If a destination is provided, all of its elements (for array) or properties (for objects) - * are deleted and then all elements/properties from the source are copied to it. - * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. - * * If `source` is identical to 'destination' an exception will be thrown. - * - * @param {*} source The source that will be used to make a copy. - * Can be any type, including primitives, `null`, and `undefined`. - * @param {(Object|Array)=} destination Destination into which the source is copied. If - * provided, must be of the same type as `source`. - * @returns {*} The copy or updated `destination`, if `destination` was specified. - * - * @example - - -
          -
          - Name:
          - E-mail:
          - Gender: male - female
          - - -
          -
          form = {{user | json}}
          -
          master = {{master | json}}
          -
          - - -
          -
          - */ -function copy(source, destination, stackSource, stackDest) { - if (isWindow(source) || isScope(source)) { - throw ngMinErr('cpws', - "Can't copy! Making copies of Window or Scope instances is not supported."); - } - - if (!destination) { - destination = source; - if (source) { - if (isArray(source)) { - destination = copy(source, [], stackSource, stackDest); - } else if (isDate(source)) { - destination = new Date(source.getTime()); - } else if (isRegExp(source)) { - destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); - destination.lastIndex = source.lastIndex; - } else if (isObject(source)) { - var emptyObject = Object.create(Object.getPrototypeOf(source)); - destination = copy(source, emptyObject, stackSource, stackDest); - } - } - } else { - if (source === destination) throw ngMinErr('cpi', - "Can't copy! Source and destination are identical."); - - stackSource = stackSource || []; - stackDest = stackDest || []; - - if (isObject(source)) { - var index = stackSource.indexOf(source); - if (index !== -1) return stackDest[index]; - - stackSource.push(source); - stackDest.push(destination); - } - - var result; - if (isArray(source)) { - destination.length = 0; - for ( var i = 0; i < source.length; i++) { - result = copy(source[i], null, stackSource, stackDest); - if (isObject(source[i])) { - stackSource.push(source[i]); - stackDest.push(result); - } - destination.push(result); - } - } else { - var h = destination.$$hashKey; - if (isArray(destination)) { - destination.length = 0; - } else { - forEach(destination, function(value, key) { - delete destination[key]; - }); - } - for ( var key in source) { - if(source.hasOwnProperty(key)) { - result = copy(source[key], null, stackSource, stackDest); - if (isObject(source[key])) { - stackSource.push(source[key]); - stackDest.push(result); - } - destination[key] = result; + + + + */ + function copy(source, destination, stackSource, stackDest) { + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', + "Can't copy! Making copies of Window or Scope instances is not supported."); } - } - setHashKey(destination,h); - } - - } - return destination; -} -/** - * Creates a shallow copy of an object, an array or a primitive. - * - * Assumes that there are no proto properties for objects. - */ -function shallowCopy(src, dst) { - if (isArray(src)) { - dst = dst || []; + if (!destination) { + destination = source; + if (source) { + if (isArray(source)) { + destination = copy(source, [], stackSource, stackDest); + } else if (isDate(source)) { + destination = new Date(source.getTime()); + } else if (isRegExp(source)) { + destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); + destination.lastIndex = source.lastIndex; + } else if (isObject(source)) { + var emptyObject = Object.create(Object.getPrototypeOf(source)); + destination = copy(source, emptyObject, stackSource, stackDest); + } + } + } else { + if (source === destination) throw ngMinErr('cpi', + "Can't copy! Source and destination are identical."); - for (var i = 0, ii = src.length; i < ii; i++) { - dst[i] = src[i]; - } - } else if (isObject(src)) { - dst = dst || {}; + stackSource = stackSource || []; + stackDest = stackDest || []; - for (var key in src) { - if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { - dst[key] = src[key]; - } - } - } + if (isObject(source)) { + var index = stackSource.indexOf(source); + if (index !== -1) return stackDest[index]; - return dst || src; -} + stackSource.push(source); + stackDest.push(destination); + } + var result; + if (isArray(source)) { + destination.length = 0; + for (var i = 0; i < source.length; i++) { + result = copy(source[i], null, stackSource, stackDest); + if (isObject(source[i])) { + stackSource.push(source[i]); + stackDest.push(result); + } + destination.push(result); + } + } else { + var h = destination.$$hashKey; + if (isArray(destination)) { + destination.length = 0; + } else { + forEach(destination, function (value, key) { + delete destination[key]; + }); + } + for (var key in source) { + if (source.hasOwnProperty(key)) { + result = copy(source[key], null, stackSource, stackDest); + if (isObject(source[key])) { + stackSource.push(source[key]); + stackDest.push(result); + } + destination[key] = result; + } + } + setHashKey(destination, h); + } -/** - * @ngdoc function - * @name angular.equals - * @module ng - * @kind function - * - * @description - * Determines if two objects or two values are equivalent. Supports value types, regular - * expressions, arrays and objects. - * - * Two objects or values are considered equivalent if at least one of the following is true: - * - * * Both objects or values pass `===` comparison. - * * Both objects or values are of the same type and all of their properties are equal by - * comparing them with `angular.equals`. - * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) - * * Both values represent the same regular expression (In JavaScript, - * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual - * representation matches). - * - * During a property comparison, properties of `function` type and properties with names - * that begin with `$` are ignored. - * - * Scope and DOMWindow objects are being compared only by identify (`===`). - * - * @param {*} o1 Object or value to compare. - * @param {*} o2 Object or value to compare. - * @returns {boolean} True if arguments are equal. - */ -function equals(o1, o2) { - if (o1 === o2) return true; - if (o1 === null || o2 === null) return false; - if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN - var t1 = typeof o1, t2 = typeof o2, length, key, keySet; - if (t1 == t2) { - if (t1 == 'object') { - if (isArray(o1)) { - if (!isArray(o2)) return false; - if ((length = o1.length) == o2.length) { - for(key=0; key 2 ? sliceArgs(arguments, 2) : []; - if (isFunction(fn) && !(fn instanceof RegExp)) { - return curryArgs.length - ? function() { - return arguments.length - ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) - : fn.apply(self, curryArgs); + for (var key in src) { + if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } } - : function() { - return arguments.length - ? fn.apply(self, arguments) - : fn.call(self); - }; - } else { - // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) - return fn; - } -} - -function toJsonReplacer(key, value) { - var val = value; - - if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { - val = undefined; - } else if (isWindow(value)) { - val = '$WINDOW'; - } else if (value && document === value) { - val = '$DOCUMENT'; - } else if (isScope(value)) { - val = '$SCOPE'; - } - - return val; -} + return dst || src; + } -/** - * @ngdoc function - * @name angular.toJson - * @module ng - * @kind function - * - * @description - * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be - * stripped since angular uses this notation internally. - * - * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. - * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. - * @returns {string|undefined} JSON-ified string representing `obj`. - */ -function toJson(obj, pretty) { - if (typeof obj === 'undefined') return undefined; - return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); -} + /** + * @ngdoc function + * @name angular.equals + * @module ng + * @kind function + * + * @description + * Determines if two objects or two values are equivalent. Supports value types, regular + * expressions, arrays and objects. + * + * Two objects or values are considered equivalent if at least one of the following is true: + * + * * Both objects or values pass `===` comparison. + * * Both objects or values are of the same type and all of their properties are equal by + * comparing them with `angular.equals`. + * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) + * * Both values represent the same regular expression (In JavaScript, + * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual + * representation matches). + * + * During a property comparison, properties of `function` type and properties with names + * that begin with `$` are ignored. + * + * Scope and DOMWindow objects are being compared only by identify (`===`). + * + * @param {*} o1 Object or value to compare. + * @param {*} o2 Object or value to compare. + * @returns {boolean} True if arguments are equal. + */ + function equals(o1, o2) { + if (o1 === o2) return true; + if (o1 === null || o2 === null) return false; + if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN + var t1 = typeof o1, t2 = typeof o2, length, key, keySet; + if (t1 == t2) { + if (t1 == 'object') { + if (isArray(o1)) { + if (!isArray(o2)) return false; + if ((length = o1.length) == o2.length) { + for (key = 0; key < length; key++) { + if (!equals(o1[key], o2[key])) return false; + } + return true; + } + } else if (isDate(o1)) { + if (!isDate(o2)) return false; + return equals(o1.getTime(), o2.getTime()); + } else if (isRegExp(o1) && isRegExp(o2)) { + return o1.toString() == o2.toString(); + } else { + if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false; + keySet = {}; + for (key in o1) { + if (key.charAt(0) === '$' || isFunction(o1[key])) continue; + if (!equals(o1[key], o2[key])) return false; + keySet[key] = true; + } + for (key in o2) { + if (!keySet.hasOwnProperty(key) && + key.charAt(0) !== '$' && + o2[key] !== undefined && !isFunction(o2[key])) return false; + } + return true; + } + } + } + return false; + } + var csp = function () { + if (isDefined(csp.isActive_)) return csp.isActive_; -/** - * @ngdoc function - * @name angular.fromJson - * @module ng - * @kind function - * - * @description - * Deserializes a JSON string. - * - * @param {string} json JSON string to deserialize. - * @returns {Object|Array|string|number} Deserialized thingy. - */ -function fromJson(json) { - return isString(json) - ? JSON.parse(json) - : json; -} + var active = !!(document.querySelector('[ng-csp]') || + document.querySelector('[data-ng-csp]')); + if (!active) { + try { + /* jshint -W031, -W054 */ + new Function(''); + /* jshint +W031, +W054 */ + } catch (e) { + active = true; + } + } -/** - * @returns {string} Returns the string representation of the element. - */ -function startingTag(element) { - element = jqLite(element).clone(); - try { - // turns out IE does not let you set .html() on elements which - // are not allowed to have children. So we just ignore it. - element.empty(); - } catch(e) {} - var elemHtml = jqLite('
          ').append(element).html(); - try { - return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : - elemHtml. - match(/^(<[^>]+>)/)[1]. - replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); - } catch(e) { - return lowercase(elemHtml); - } - -} + return (csp.isActive_ = active); + }; -///////////////////////////////////////////////// + function concat(array1, array2, index) { + return array1.concat(slice.call(array2, index)); + } -/** - * Tries to decode the URI component without throwing an exception. - * - * @private - * @param str value potential URI component to check. - * @returns {boolean} True if `value` can be decoded - * with the decodeURIComponent function. - */ -function tryDecodeURIComponent(value) { - try { - return decodeURIComponent(value); - } catch(e) { - // Ignore any invalid uri component - } -} + function sliceArgs(args, startIndex) { + return slice.call(args, startIndex || 0); + } -/** - * Parses an escaped url query string into key-value pairs. - * @returns {Object.} - */ -function parseKeyValue(/**string*/keyValue) { - var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue) { - if ( keyValue ) { - key_value = keyValue.replace(/\+/g,'%20').split('='); - key = tryDecodeURIComponent(key_value[0]); - if ( isDefined(key) ) { - var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; - if (!hasOwnProperty.call(obj, key)) { - obj[key] = val; - } else if(isArray(obj[key])) { - obj[key].push(val); + /* jshint -W101 */ + /** + * @ngdoc function + * @name angular.bind + * @module ng + * @kind function + * + * @description + * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for + * `fn`). You can supply optional `args` that are prebound to the function. This feature is also + * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as + * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). + * + * @param {Object} self Context which `fn` should be evaluated in. + * @param {function()} fn Function to be bound. + * @param {...*} args Optional arguments to be prebound to the `fn` function call. + * @returns {function()} Function that wraps the `fn` with all the specified bindings. + */ + /* jshint +W101 */ + function bind(self, fn) { + var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; + if (isFunction(fn) && !(fn instanceof RegExp)) { + return curryArgs.length + ? function () { + return arguments.length + ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) + : fn.apply(self, curryArgs); + } + : function () { + return arguments.length + ? fn.apply(self, arguments) + : fn.call(self); + }; } else { - obj[key] = [obj[key],val]; + // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) + return fn; } - } - } - }); - return obj; -} - -function toKeyValue(obj) { - var parts = []; - forEach(obj, function(value, key) { - if (isArray(value)) { - forEach(value, function(arrayValue) { - parts.push(encodeUriQuery(key, true) + - (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); - }); - } else { - parts.push(encodeUriQuery(key, true) + - (value === true ? '' : '=' + encodeUriQuery(value, true))); } - }); - return parts.length ? parts.join('&') : ''; -} -/** - * We need our custom method because encodeURIComponent is too aggressive and doesn't follow - * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path - * segments: - * segment = *pchar - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * pct-encoded = "%" HEXDIG HEXDIG - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ -function encodeUriSegment(val) { - return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); -} + function toJsonReplacer(key, value) { + var val = value; + if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { + val = undefined; + } else if (isWindow(value)) { + val = '$WINDOW'; + } else if (value && document === value) { + val = '$DOCUMENT'; + } else if (isScope(value)) { + val = '$SCOPE'; + } -/** - * This method is intended for encoding *key* or *value* parts of query component. We need a custom - * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be - * encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ -function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%3B/gi, ';'). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); -} - -var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; - -function getNgAttribute(element, ngAttr) { - var attr, i, ii = ngAttrPrefixes.length; - element = jqLite(element); - for (i=0; i` or `` tags. - * - * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` - * found in the document will be used to define the root element to auto-bootstrap as an - * application. To run multiple applications in an HTML document you must manually bootstrap them using - * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. - * - * You can specify an **AngularJS module** to be used as the root module for the application. This - * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and - * should contain the application code needed or have dependencies on other modules that will - * contain the code. See {@link angular.module} for more information. - * - * In the example below if the `ngApp` directive were not placed on the `html` element then the - * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` - * would not be resolved to `3`. - * - * `ngApp` is the easiest, and most common, way to bootstrap an application. - * - - -
          + + /** + * @ngdoc function + * @name angular.toJson + * @module ng + * @kind function + * + * @description + * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be + * stripped since angular uses this notation internally. + * + * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. + * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. + * @returns {string|undefined} JSON-ified string representing `obj`. + */ + function toJson(obj, pretty) { + if (typeof obj === 'undefined') return undefined; + return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); + } + + + /** + * @ngdoc function + * @name angular.fromJson + * @module ng + * @kind function + * + * @description + * Deserializes a JSON string. + * + * @param {string} json JSON string to deserialize. + * @returns {Object|Array|string|number} Deserialized thingy. + */ + function fromJson(json) { + return isString(json) + ? JSON.parse(json) + : json; + } + + + /** + * @returns {string} Returns the string representation of the element. + */ + function startingTag(element) { + element = jqLite(element).clone(); + try { + // turns out IE does not let you set .html() on elements which + // are not allowed to have children. So we just ignore it. + element.empty(); + } catch (e) { + } + var elemHtml = jqLite('
          ').append(element).html(); + try { + return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : + elemHtml. + match(/^(<[^>]+>)/)[1]. + replace(/^<([\w\-]+)/, function (match, nodeName) { + return '<' + lowercase(nodeName); + }); + } catch (e) { + return lowercase(elemHtml); + } + + } + + +///////////////////////////////////////////////// + + /** + * Tries to decode the URI component without throwing an exception. + * + * @private + * @param str value potential URI component to check. + * @returns {boolean} True if `value` can be decoded + * with the decodeURIComponent function. + */ + function tryDecodeURIComponent(value) { + try { + return decodeURIComponent(value); + } catch (e) { + // Ignore any invalid uri component + } + } + + + /** + * Parses an escaped url query string into key-value pairs. + * @returns {Object.} + */ + function parseKeyValue(/**string*/keyValue) { + var obj = {}, key_value, key; + forEach((keyValue || "").split('&'), function (keyValue) { + if (keyValue) { + key_value = keyValue.replace(/\+/g, '%20').split('='); + key = tryDecodeURIComponent(key_value[0]); + if (isDefined(key)) { + var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + if (!hasOwnProperty.call(obj, key)) { + obj[key] = val; + } else if (isArray(obj[key])) { + obj[key].push(val); + } else { + obj[key] = [obj[key], val]; + } + } + } + }); + return obj; + } + + function toKeyValue(obj) { + var parts = []; + forEach(obj, function (value, key) { + if (isArray(value)) { + forEach(value, function (arrayValue) { + parts.push(encodeUriQuery(key, true) + + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); + }); + } else { + parts.push(encodeUriQuery(key, true) + + (value === true ? '' : '=' + encodeUriQuery(value, true))); + } + }); + return parts.length ? parts.join('&') : ''; + } + + + /** + * We need our custom method because encodeURIComponent is too aggressive and doesn't follow + * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path + * segments: + * segment = *pchar + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * pct-encoded = "%" HEXDIG HEXDIG + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ + function encodeUriSegment(val) { + return encodeUriQuery(val, true). + replace(/%26/gi, '&'). + replace(/%3D/gi, '='). + replace(/%2B/gi, '+'); + } + + + /** + * This method is intended for encoding *key* or *value* parts of query component. We need a custom + * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be + * encoded per http://tools.ietf.org/html/rfc3986: + * query = *( pchar / "/" / "?" ) + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * pct-encoded = "%" HEXDIG HEXDIG + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ + function encodeUriQuery(val, pctEncodeSpaces) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%3B/gi, ';'). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + } + + var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; + + function getNgAttribute(element, ngAttr) { + var attr, i, ii = ngAttrPrefixes.length; + element = jqLite(element); + for (i = 0; i < ii; ++i) { + attr = ngAttrPrefixes[i] + ngAttr; + if (isString(attr = element.attr(attr))) { + return attr; + } + } + return null; + } + + /** + * @ngdoc directive + * @name ngApp + * @module ng + * + * @element ANY + * @param {angular.Module} ngApp an optional application + * {@link angular.module module} name to load. + * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be + * created in "strict-di" mode. This means that the application will fail to invoke functions which + * do not use explicit function annotation (and are thus unsuitable for minification), as described + * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in + * tracking down the root of these bugs. + * + * @description + * + * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive + * designates the **root element** of the application and is typically placed near the root element + * of the page - e.g. on the `` or `` tags. + * + * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` + * found in the document will be used to define the root element to auto-bootstrap as an + * application. To run multiple applications in an HTML document you must manually bootstrap them using + * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. + * + * You can specify an **AngularJS module** to be used as the root module for the application. This + * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and + * should contain the application code needed or have dependencies on other modules that will + * contain the code. See {@link angular.module} for more information. + * + * In the example below if the `ngApp` directive were not placed on the `html` element then the + * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` + * would not be resolved to `3`. + * + * `ngApp` is the easiest, and most common, way to bootstrap an application. + * + + +
          I can add: {{a}} + {{b}} = {{ a+b }} -
          -
          - - angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { +
          + + + angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { $scope.a = 1; $scope.b = 2; }); - - - * - * Using `ngStrictDi`, you would see something like this: - * - - -
          -
          - I can add: {{a}} + {{b}} = {{ a+b }} - -

          This renders because the controller does not fail to - instantiate, by using explicit annotation style (see - script.js for details) -

          -
          - -
          - Name:
          - Hello, {{name}}! - -

          This renders because the controller does not fail to - instantiate, by using explicit annotation style - (see script.js for details) -

          -
          - -
          - I can add: {{a}} + {{b}} = {{ a+b }} - -

          The controller could not be instantiated, due to relying - on automatic function annotations (which are disabled in - strict mode). As such, the content of this section is not - interpolated, and there should be an error in your web console. -

          -
          -
          -
          - - angular.module('ngAppStrictDemo', []) + +
          + * + * Using `ngStrictDi`, you would see something like this: + * + + +
          +
          + I can add: {{a}} + {{b}} = {{ a+b }} + +

          This renders because the controller does not fail to + instantiate, by using explicit annotation style (see + script.js for details) +

          +
          + +
          + Name:
          + Hello, {{name}}! + +

          This renders because the controller does not fail to + instantiate, by using explicit annotation style + (see script.js for details) +

          +
          + +
          + I can add: {{a}} + {{b}} = {{ a+b }} + +

          The controller could not be instantiated, due to relying + on automatic function annotations (which are disabled in + strict mode). As such, the content of this section is not + interpolated, and there should be an error in your web console. +

          +
          +
          +
          + + angular.module('ngAppStrictDemo', []) // BadController will fail to instantiate, due to relying on automatic function annotation, // rather than an explicit annotation .controller('BadController', function($scope) { @@ -1348,571 +1380,573 @@ function getNgAttribute(element, ngAttr) { $scope.name = "World"; } GoodController2.$inject = ['$scope']; - - - div[ng-controller] { + + + div[ng-controller] { margin-bottom: 1em; -webkit-border-radius: 4px; border-radius: 4px; border: 1px solid; padding: .5em; } - div[ng-controller^=Good] { + div[ng-controller^=Good] { border-color: #d6e9c6; background-color: #dff0d8; color: #3c763d; } - div[ng-controller^=Bad] { + div[ng-controller^=Bad] { border-color: #ebccd1; background-color: #f2dede; color: #a94442; margin-bottom: 0; } - -
          - */ -function angularInit(element, bootstrap) { - var appElement, - module, - config = {}; - - // The element `element` has priority over any other element - forEach(ngAttrPrefixes, function(prefix) { - var name = prefix + 'app'; - - if (!appElement && element.hasAttribute && element.hasAttribute(name)) { - appElement = element; - module = element.getAttribute(name); - } - }); - forEach(ngAttrPrefixes, function(prefix) { - var name = prefix + 'app'; - var candidate; + + + */ + function angularInit(element, bootstrap) { + var appElement, + module, + config = {}; + + // The element `element` has priority over any other element + forEach(ngAttrPrefixes, function (prefix) { + var name = prefix + 'app'; + + if (!appElement && element.hasAttribute && element.hasAttribute(name)) { + appElement = element; + module = element.getAttribute(name); + } + }); + forEach(ngAttrPrefixes, function (prefix) { + var name = prefix + 'app'; + var candidate; - if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { - appElement = candidate; - module = candidate.getAttribute(name); + if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { + appElement = candidate; + module = candidate.getAttribute(name); + } + }); + if (appElement) { + config.strictDi = getNgAttribute(appElement, "strict-di") !== null; + bootstrap(appElement, module ? [module] : [], config); + } } - }); - if (appElement) { - config.strictDi = getNgAttribute(appElement, "strict-di") !== null; - bootstrap(appElement, module ? [module] : [], config); - } -} -/** - * @ngdoc function - * @name angular.bootstrap - * @module ng - * @description - * Use this function to manually start up angular application. - * - * See: {@link guide/bootstrap Bootstrap} - * - * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually. - * They must use {@link ng.directive:ngApp ngApp}. - * - * Angular will detect if it has been loaded into the browser more than once and only allow the - * first loaded script to be bootstrapped and will report a warning to the browser console for - * each of the subsequent scripts. This prevents strange results in applications, where otherwise - * multiple instances of Angular try to work on the DOM. - * - * ```html - * - * - * - *
          - * {{greeting}} - *
          - * - * - * + * - * - * - * ``` - * - * @param {DOMElement} element DOM element which is the root of angular application. - * @param {Array=} modules an array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. - * See: {@link angular.module modules} - * @param {Object=} config an object for defining configuration options for the application. The - * following keys are supported: - * - * - `strictDi`: disable automatic function annotation for the application. This is meant to - * assist in finding bugs which break minified code. - * - * @returns {auto.$injector} Returns the newly created injector for this app. - */ -function bootstrap(element, modules, config) { - if (!isObject(config)) config = {}; - var defaultConfig = { - strictDi: false - }; - config = extend(defaultConfig, config); - var doBootstrap = function() { - element = jqLite(element); - - if (element.injector()) { - var tag = (element[0] === document) ? 'document' : startingTag(element); - //Encode angle brackets to prevent input from being sanitized to empty string #8683 - throw ngMinErr( - 'btstrpd', - "App Already Bootstrapped with this Element '{0}'", - tag.replace(//,'>')); - } - - modules = modules || []; - modules.unshift(['$provide', function($provide) { - $provide.value('$rootElement', element); - }]); + * angular.bootstrap(document, ['demo']); + * + * + * + * ``` + * + * @param {DOMElement} element DOM element which is the root of angular application. + * @param {Array=} modules an array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * See: {@link angular.module modules} + * @param {Object=} config an object for defining configuration options for the application. The + * following keys are supported: + * + * - `strictDi`: disable automatic function annotation for the application. This is meant to + * assist in finding bugs which break minified code. + * + * @returns {auto.$injector} Returns the newly created injector for this app. + */ + function bootstrap(element, modules, config) { + if (!isObject(config)) config = {}; + var defaultConfig = { + strictDi: false + }; + config = extend(defaultConfig, config); + var doBootstrap = function () { + element = jqLite(element); + + if (element.injector()) { + var tag = (element[0] === document) ? 'document' : startingTag(element); + //Encode angle brackets to prevent input from being sanitized to empty string #8683 + throw ngMinErr( + 'btstrpd', + "App Already Bootstrapped with this Element '{0}'", + tag.replace(//, '>')); + } - if (config.debugInfoEnabled) { - // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. - modules.push(['$compileProvider', function($compileProvider) { - $compileProvider.debugInfoEnabled(true); - }]); - } + modules = modules || []; + modules.unshift(['$provide', function ($provide) { + $provide.value('$rootElement', element); + }]); - modules.unshift('ng'); - var injector = createInjector(modules, config.strictDi); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', - function bootstrapApply(scope, element, compile, injector) { - scope.$apply(function() { - element.data('$injector', injector); - compile(element)(scope); - }); - }] - ); - return injector; - }; + if (config.debugInfoEnabled) { + // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. + modules.push(['$compileProvider', function ($compileProvider) { + $compileProvider.debugInfoEnabled(true); + }]); + } - var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; - var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; + modules.unshift('ng'); + var injector = createInjector(modules, config.strictDi); + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', + function bootstrapApply(scope, element, compile, injector) { + scope.$apply(function () { + element.data('$injector', injector); + compile(element)(scope); + }); + }] + ); + return injector; + }; - if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { - config.debugInfoEnabled = true; - window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); - } + var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; + var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; - if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { - return doBootstrap(); - } + if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { + config.debugInfoEnabled = true; + window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); + } - window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); - angular.resumeBootstrap = function(extraModules) { - forEach(extraModules, function(module) { - modules.push(module); - }); - doBootstrap(); - }; -} + if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { + return doBootstrap(); + } -/** - * @ngdoc function - * @name angular.reloadWithDebugInfo - * @module ng - * @description - * Use this function to reload the current application with debug information turned on. - * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. - * - * See {@link ng.$compileProvider#debugInfoEnabled} for more. - */ -function reloadWithDebugInfo() { - window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; - window.location.reload(); -} + window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); + angular.resumeBootstrap = function (extraModules) { + forEach(extraModules, function (module) { + modules.push(module); + }); + doBootstrap(); + }; + } -/** - * @name angular.getTestability - * @module ng - * @description - * Get the testability service for the instance of Angular on the given - * element. - * @param {DOMElement} element DOM element which is the root of angular application. - */ -function getTestability(rootElement) { - return angular.element(rootElement).injector().get('$$testability'); -} - -var SNAKE_CASE_REGEXP = /[A-Z]/g; -function snake_case(name, separator) { - separator = separator || '_'; - return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { - return (pos ? separator : '') + letter.toLowerCase(); - }); -} - -var bindJQueryFired = false; -var skipDestroyOnNextJQueryCleanData; -function bindJQuery() { - var originalCleanData; - - if (bindJQueryFired) { - return; - } - - // bind to jQuery if present; - jQuery = window.jQuery; - // Use jQuery if it exists with proper functionality, otherwise default to us. - // Angular 1.2+ requires jQuery 1.7+ for on()/off() support. - // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older - // versions. It will not work for sure with jQuery <1.7, though. - if (jQuery && jQuery.fn.on) { - jqLite = jQuery; - extend(jQuery.fn, { - scope: JQLitePrototype.scope, - isolateScope: JQLitePrototype.isolateScope, - controller: JQLitePrototype.controller, - injector: JQLitePrototype.injector, - inheritedData: JQLitePrototype.inheritedData - }); + /** + * @ngdoc function + * @name angular.reloadWithDebugInfo + * @module ng + * @description + * Use this function to reload the current application with debug information turned on. + * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. + * + * See {@link ng.$compileProvider#debugInfoEnabled} for more. + */ + function reloadWithDebugInfo() { + window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; + window.location.reload(); + } - // All nodes removed from the DOM via various jQuery APIs like .remove() - // are passed through jQuery.cleanData. Monkey-patch this method to fire - // the $destroy event on all removed nodes. - originalCleanData = jQuery.cleanData; - jQuery.cleanData = function(elems) { - var events; - if (!skipDestroyOnNextJQueryCleanData) { - for (var i = 0, elem; (elem = elems[i]) != null; i++) { - events = jQuery._data(elem, "events"); - if (events && events.$destroy) { - jQuery(elem).triggerHandler('$destroy'); - } - } - } else { - skipDestroyOnNextJQueryCleanData = false; - } - originalCleanData(elems); - }; - } else { - jqLite = JQLite; - } + /** + * @name angular.getTestability + * @module ng + * @description + * Get the testability service for the instance of Angular on the given + * element. + * @param {DOMElement} element DOM element which is the root of angular application. + */ + function getTestability(rootElement) { + return angular.element(rootElement).injector().get('$$testability'); + } - angular.element = jqLite; + var SNAKE_CASE_REGEXP = /[A-Z]/g; - // Prevent double-proxying. - bindJQueryFired = true; -} + function snake_case(name, separator) { + separator = separator || '_'; + return name.replace(SNAKE_CASE_REGEXP, function (letter, pos) { + return (pos ? separator : '') + letter.toLowerCase(); + }); + } -/** - * throw error if the argument is falsy. - */ -function assertArg(arg, name, reason) { - if (!arg) { - throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); - } - return arg; -} - -function assertArgFn(arg, name, acceptArrayAnnotation) { - if (acceptArrayAnnotation && isArray(arg)) { - arg = arg[arg.length - 1]; - } - - assertArg(isFunction(arg), name, 'not a function, got ' + - (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); - return arg; -} + var bindJQueryFired = false; + var skipDestroyOnNextJQueryCleanData; -/** - * throw error if the name given is hasOwnProperty - * @param {String} name the name to test - * @param {String} context the context in which the name is used, such as module or directive - */ -function assertNotHasOwnProperty(name, context) { - if (name === 'hasOwnProperty') { - throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); - } -} + function bindJQuery() { + var originalCleanData; -/** - * Return the value accessible from the object by path. Any undefined traversals are ignored - * @param {Object} obj starting object - * @param {String} path path to traverse - * @param {boolean} [bindFnToScope=true] - * @returns {Object} value as accessible by path - */ -//TODO(misko): this function needs to be removed -function getter(obj, path, bindFnToScope) { - if (!path) return obj; - var keys = path.split('.'); - var key; - var lastInstance = obj; - var len = keys.length; - - for (var i = 0; i < len; i++) { - key = keys[i]; - if (obj) { - obj = (lastInstance = obj)[key]; - } - } - if (!bindFnToScope && isFunction(obj)) { - return bind(lastInstance, obj); - } - return obj; -} + if (bindJQueryFired) { + return; + } -/** - * Return the DOM siblings between the first and last node in the given array. - * @param {Array} array like object - * @returns {jqLite} jqLite collection containing the nodes - */ -function getBlockNodes(nodes) { - // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original - // collection, otherwise update the original collection. - var node = nodes[0]; - var endNode = nodes[nodes.length - 1]; - var blockNodes = [node]; + // bind to jQuery if present; + jQuery = window.jQuery; + // Use jQuery if it exists with proper functionality, otherwise default to us. + // Angular 1.2+ requires jQuery 1.7+ for on()/off() support. + // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older + // versions. It will not work for sure with jQuery <1.7, though. + if (jQuery && jQuery.fn.on) { + jqLite = jQuery; + extend(jQuery.fn, { + scope: JQLitePrototype.scope, + isolateScope: JQLitePrototype.isolateScope, + controller: JQLitePrototype.controller, + injector: JQLitePrototype.injector, + inheritedData: JQLitePrototype.inheritedData + }); - do { - node = node.nextSibling; - if (!node) break; - blockNodes.push(node); - } while (node !== endNode); + // All nodes removed from the DOM via various jQuery APIs like .remove() + // are passed through jQuery.cleanData. Monkey-patch this method to fire + // the $destroy event on all removed nodes. + originalCleanData = jQuery.cleanData; + jQuery.cleanData = function (elems) { + var events; + if (!skipDestroyOnNextJQueryCleanData) { + for (var i = 0, elem; (elem = elems[i]) != null; i++) { + events = jQuery._data(elem, "events"); + if (events && events.$destroy) { + jQuery(elem).triggerHandler('$destroy'); + } + } + } else { + skipDestroyOnNextJQueryCleanData = false; + } + originalCleanData(elems); + }; + } else { + jqLite = JQLite; + } - return jqLite(blockNodes); -} + angular.element = jqLite; + // Prevent double-proxying. + bindJQueryFired = true; + } -/** - * Creates a new object without a prototype. This object is useful for lookup without having to - * guard against prototypically inherited properties via hasOwnProperty. - * - * Related micro-benchmarks: - * - http://jsperf.com/object-create2 - * - http://jsperf.com/proto-map-lookup/2 - * - http://jsperf.com/for-in-vs-object-keys2 - * - * @returns {Object} - */ -function createMap() { - return Object.create(null); -} + /** + * throw error if the argument is falsy. + */ + function assertArg(arg, name, reason) { + if (!arg) { + throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); + } + return arg; + } -var NODE_TYPE_ELEMENT = 1; -var NODE_TYPE_TEXT = 3; -var NODE_TYPE_COMMENT = 8; -var NODE_TYPE_DOCUMENT = 9; -var NODE_TYPE_DOCUMENT_FRAGMENT = 11; + function assertArgFn(arg, name, acceptArrayAnnotation) { + if (acceptArrayAnnotation && isArray(arg)) { + arg = arg[arg.length - 1]; + } -/** - * @ngdoc type - * @name angular.Module - * @module ng - * @description - * - * Interface for configuring angular {@link angular.module modules}. - */ + assertArg(isFunction(arg), name, 'not a function, got ' + + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); + return arg; + } -function setupModuleLoader(window) { + /** + * throw error if the name given is hasOwnProperty + * @param {String} name the name to test + * @param {String} context the context in which the name is used, such as module or directive + */ + function assertNotHasOwnProperty(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); + } + } - var $injectorMinErr = minErr('$injector'); - var ngMinErr = minErr('ng'); + /** + * Return the value accessible from the object by path. Any undefined traversals are ignored + * @param {Object} obj starting object + * @param {String} path path to traverse + * @param {boolean} [bindFnToScope=true] + * @returns {Object} value as accessible by path + */ +//TODO(misko): this function needs to be removed + function getter(obj, path, bindFnToScope) { + if (!path) return obj; + var keys = path.split('.'); + var key; + var lastInstance = obj; + var len = keys.length; + + for (var i = 0; i < len; i++) { + key = keys[i]; + if (obj) { + obj = (lastInstance = obj)[key]; + } + } + if (!bindFnToScope && isFunction(obj)) { + return bind(lastInstance, obj); + } + return obj; + } - function ensure(obj, name, factory) { - return obj[name] || (obj[name] = factory()); - } + /** + * Return the DOM siblings between the first and last node in the given array. + * @param {Array} array like object + * @returns {jqLite} jqLite collection containing the nodes + */ + function getBlockNodes(nodes) { + // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original + // collection, otherwise update the original collection. + var node = nodes[0]; + var endNode = nodes[nodes.length - 1]; + var blockNodes = [node]; - var angular = ensure(window, 'angular', Object); + do { + node = node.nextSibling; + if (!node) break; + blockNodes.push(node); + } while (node !== endNode); - // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap - angular.$$minErr = angular.$$minErr || minErr; + return jqLite(blockNodes); + } - return ensure(angular, 'module', function() { - /** @type {Object.} */ - var modules = {}; /** - * @ngdoc function - * @name angular.module - * @module ng - * @description + * Creates a new object without a prototype. This object is useful for lookup without having to + * guard against prototypically inherited properties via hasOwnProperty. * - * The `angular.module` is a global place for creating, registering and retrieving Angular - * modules. - * All modules (angular core or 3rd party) that should be available to an application must be - * registered using this mechanism. + * Related micro-benchmarks: + * - http://jsperf.com/object-create2 + * - http://jsperf.com/proto-map-lookup/2 + * - http://jsperf.com/for-in-vs-object-keys2 * - * When passed two or more arguments, a new module is created. If passed only one argument, an - * existing module (the name passed as the first argument to `module`) is retrieved. - * - * - * # Module - * - * A module is a collection of services, directives, controllers, filters, and configuration information. - * `angular.module` is used to configure the {@link auto.$injector $injector}. - * - * ```js - * // Create a new module - * var myModule = angular.module('myModule', []); - * - * // register a new service - * myModule.value('appName', 'MyCoolApp'); + * @returns {Object} + */ + function createMap() { + return Object.create(null); + } + + var NODE_TYPE_ELEMENT = 1; + var NODE_TYPE_TEXT = 3; + var NODE_TYPE_COMMENT = 8; + var NODE_TYPE_DOCUMENT = 9; + var NODE_TYPE_DOCUMENT_FRAGMENT = 11; + + /** + * @ngdoc type + * @name angular.Module + * @module ng + * @description * - * // configure existing services inside initialization blocks. - * myModule.config(['$locationProvider', function($locationProvider) { + * Interface for configuring angular {@link angular.module modules}. + */ + + function setupModuleLoader(window) { + + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function () { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @module ng + * @description + * + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be + * registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an + * existing module (the name passed as the first argument to `module`) is retrieved. + * + * + * # Module + * + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. + * + * ```js + * // Create a new module + * var myModule = angular.module('myModule', []); + * + * // register a new service + * myModule.value('appName', 'MyCoolApp'); + * + * // configure existing services inside initialization blocks. + * myModule.config(['$locationProvider', function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }]); - * ``` - * - * Then you can create an injector and load your modules like this: - * - * ```js - * var injector = angular.injector(['ng', 'myModule']) - * ``` - * - * However it's more likely that you'll just use - * {@link ng.directive:ngApp ngApp} or - * {@link angular.bootstrap} to simplify this process for you. - * - * @param {!string} name The name of the module to create or retrieve. - * @param {!Array.=} requires If specified then new module is being created. If - * unspecified then the module is being retrieved for further configuration. - * @param {Function=} configFn Optional configuration function for the module. Same as - * {@link angular.Module#config Module#config()}. - * @returns {module} new module with the {@link angular.Module} api. - */ - return function module(name, requires, configFn) { - var assertNotHasOwnProperty = function(name, context) { - if (name === 'hasOwnProperty') { - throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); - } - }; + * ``` + * + * Then you can create an injector and load your modules like this: + * + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` + * + * However it's more likely that you'll just use + * {@link ng.directive:ngApp ngApp} or + * {@link angular.bootstrap} to simplify this process for you. + * + * @param {!string} name The name of the module to create or retrieve. + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as + * {@link angular.Module#config Module#config()}. + * @returns {module} new module with the {@link angular.Module} api. + */ + return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function (name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; - assertNotHasOwnProperty(name, 'module'); - if (requires && modules.hasOwnProperty(name)) { - modules[name] = null; - } - return ensure(modules, name, function() { - if (!requires) { - throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + - "the module name or forgot to load it. If registering a module ensure that you " + - "specify the dependencies as the second argument.", name); - } + assertNotHasOwnProperty(name, 'module'); + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function () { + if (!requires) { + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); + } - /** @type {!Array.>} */ - var invokeQueue = []; - - /** @type {!Array.} */ - var configBlocks = []; - - /** @type {!Array.} */ - var runBlocks = []; - - var config = invokeLater('$injector', 'invoke', 'push', configBlocks); - - /** @type {angular.Module} */ - var moduleInstance = { - // Private state - _invokeQueue: invokeQueue, - _configBlocks: configBlocks, - _runBlocks: runBlocks, - - /** - * @ngdoc property - * @name angular.Module#requires - * @module ng - * - * @description - * Holds the list of modules which the injector will load before the current module is - * loaded. - */ - requires: requires, - - /** - * @ngdoc property - * @name angular.Module#name - * @module ng - * - * @description - * Name of the module. - */ - name: name, - - - /** - * @ngdoc method - * @name angular.Module#provider - * @module ng - * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the - * service. - * @description - * See {@link auto.$provide#provider $provide.provider()}. - */ - provider: invokeLater('$provide', 'provider'), - - /** - * @ngdoc method - * @name angular.Module#factory - * @module ng - * @param {string} name service name - * @param {Function} providerFunction Function for creating new instance of the service. - * @description - * See {@link auto.$provide#factory $provide.factory()}. - */ - factory: invokeLater('$provide', 'factory'), - - /** - * @ngdoc method - * @name angular.Module#service - * @module ng - * @param {string} name service name - * @param {Function} constructor A constructor function that will be instantiated. - * @description - * See {@link auto.$provide#service $provide.service()}. - */ - service: invokeLater('$provide', 'service'), - - /** - * @ngdoc method - * @name angular.Module#value - * @module ng - * @param {string} name service name - * @param {*} object Service instance object. - * @description - * See {@link auto.$provide#value $provide.value()}. - */ - value: invokeLater('$provide', 'value'), - - /** - * @ngdoc method - * @name angular.Module#constant - * @module ng - * @param {string} name constant name - * @param {*} object Constant value. - * @description - * Because the constant are fixed, they get applied before other provide methods. - * See {@link auto.$provide#constant $provide.constant()}. - */ - constant: invokeLater('$provide', 'constant', 'unshift'), - - /** - * @ngdoc method - * @name angular.Module#animation - * @module ng - * @param {string} name animation name - * @param {Function} animationFactory Factory function for creating new instance of an - * animation. - * @description - * - * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. - * - * - * Defines an animation hook that can be later used with - * {@link ngAnimate.$animate $animate} service and directives that use this service. - * - * ```js - * module.animation('.animation-name', function($inject1, $inject2) { + /** @type {!Array.>} */ + var invokeQueue = []; + + /** @type {!Array.} */ + var configBlocks = []; + + /** @type {!Array.} */ + var runBlocks = []; + + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); + + /** @type {angular.Module} */ + var moduleInstance = { + // Private state + _invokeQueue: invokeQueue, + _configBlocks: configBlocks, + _runBlocks: runBlocks, + + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, + + /** + * @ngdoc property + * @name angular.Module#name + * @module ng + * + * @description + * Name of the module. + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @module ng + * @param {string} name service name + * @param {Function} providerType Construction function for creating new instance of the + * service. + * @description + * See {@link auto.$provide#provider $provide.provider()}. + */ + provider: invokeLater('$provide', 'provider'), + + /** + * @ngdoc method + * @name angular.Module#factory + * @module ng + * @param {string} name service name + * @param {Function} providerFunction Function for creating new instance of the service. + * @description + * See {@link auto.$provide#factory $provide.factory()}. + */ + factory: invokeLater('$provide', 'factory'), + + /** + * @ngdoc method + * @name angular.Module#service + * @module ng + * @param {string} name service name + * @param {Function} constructor A constructor function that will be instantiated. + * @description + * See {@link auto.$provide#service $provide.service()}. + */ + service: invokeLater('$provide', 'service'), + + /** + * @ngdoc method + * @name angular.Module#value + * @module ng + * @param {string} name service name + * @param {*} object Service instance object. + * @description + * See {@link auto.$provide#value $provide.value()}. + */ + value: invokeLater('$provide', 'value'), + + /** + * @ngdoc method + * @name angular.Module#constant + * @module ng + * @param {string} name constant name + * @param {*} object Constant value. + * @description + * Because the constant are fixed, they get applied before other provide methods. + * See {@link auto.$provide#constant $provide.constant()}. + */ + constant: invokeLater('$provide', 'constant', 'unshift'), + + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link ngAnimate.$animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation @@ -1923,1802 +1957,1813 @@ function setupModuleLoader(window) { * } * } * }) - * ``` - * - * See {@link ng.$animateProvider#register $animateProvider.register()} and - * {@link ngAnimate ngAnimate module} for more information. - */ - animation: invokeLater('$animateProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#filter - * @module ng - * @param {string} name Filter name. - * @param {Function} filterFactory Factory function for creating new instance of filter. - * @description - * See {@link ng.$filterProvider#register $filterProvider.register()}. - */ - filter: invokeLater('$filterProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#controller - * @module ng - * @param {string|Object} name Controller name, or an object map of controllers where the - * keys are the names and the values are the constructors. - * @param {Function} constructor Controller constructor function. - * @description - * See {@link ng.$controllerProvider#register $controllerProvider.register()}. - */ - controller: invokeLater('$controllerProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#directive - * @module ng - * @param {string|Object} name Directive name, or an object map of directives where the - * keys are the names and the values are the factories. - * @param {Function} directiveFactory Factory function for creating new instance of - * directives. - * @description - * See {@link ng.$compileProvider#directive $compileProvider.directive()}. - */ - directive: invokeLater('$compileProvider', 'directive'), - - /** - * @ngdoc method - * @name angular.Module#config - * @module ng - * @param {Function} configFn Execute this function on module load. Useful for service - * configuration. - * @description - * Use this method to register work which needs to be performed on module loading. - * For more about how to configure services, see - * {@link providers#provider-recipe Provider Recipe}. - */ - config: config, - - /** - * @ngdoc method - * @name angular.Module#run - * @module ng - * @param {Function} initializationFn Execute this function after injector creation. - * Useful for application initialization. - * @description - * Use this method to register work which should be performed when the injector is done - * loading all modules. - */ - run: function(block) { - runBlocks.push(block); - return this; - } - }; + * ``` + * + * See {@link ng.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#filter + * @module ng + * @param {string} name Filter name. + * @param {Function} filterFactory Factory function for creating new instance of filter. + * @description + * See {@link ng.$filterProvider#register $filterProvider.register()}. + */ + filter: invokeLater('$filterProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#controller + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLater('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. + * @param {Function} directiveFactory Factory function for creating new instance of + * directives. + * @description + * See {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + directive: invokeLater('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#config + * @module ng + * @param {Function} configFn Execute this function on module load. Useful for service + * configuration. + * @description + * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#provider-recipe Provider Recipe}. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @module ng + * @param {Function} initializationFn Execute this function after injector creation. + * Useful for application initialization. + * @description + * Use this method to register work which should be performed when the injector is done + * loading all modules. + */ + run: function (block) { + runBlocks.push(block); + return this; + } + }; + + if (configFn) { + config(configFn); + } - if (configFn) { - config(configFn); - } + return moduleInstance; + + /** + * @param {string} provider + * @param {string} method + * @param {String=} insertMethod + * @returns {angular.Module} + */ + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; + return function () { + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + }); + }; + }); - return moduleInstance; + } - /** - * @param {string} provider - * @param {string} method - * @param {String=} insertMethod - * @returns {angular.Module} - */ - function invokeLater(provider, method, insertMethod, queue) { - if (!queue) queue = invokeQueue; - return function() { - queue[insertMethod || 'push']([provider, method, arguments]); - return moduleInstance; - }; - } - }); + /* global angularModule: true, + version: true, + + $LocaleProvider, + $CompileProvider, + + htmlAnchorDirective, + inputDirective, + inputDirective, + formDirective, + scriptDirective, + selectDirective, + styleDirective, + optionDirective, + ngBindDirective, + ngBindHtmlDirective, + ngBindTemplateDirective, + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective, + ngCspDirective, + ngCloakDirective, + ngControllerDirective, + ngFormDirective, + ngHideDirective, + ngIfDirective, + ngIncludeDirective, + ngIncludeFillContentDirective, + ngInitDirective, + ngNonBindableDirective, + ngPluralizeDirective, + ngRepeatDirective, + ngShowDirective, + ngStyleDirective, + ngSwitchDirective, + ngSwitchWhenDirective, + ngSwitchDefaultDirective, + ngOptionsDirective, + ngTranscludeDirective, + ngModelDirective, + ngListDirective, + ngChangeDirective, + patternDirective, + patternDirective, + requiredDirective, + requiredDirective, + minlengthDirective, + minlengthDirective, + maxlengthDirective, + maxlengthDirective, + ngValueDirective, + ngModelOptionsDirective, + ngAttributeAliasDirectives, + ngEventDirectives, + + $AnchorScrollProvider, + $AnimateProvider, + $BrowserProvider, + $CacheFactoryProvider, + $ControllerProvider, + $DocumentProvider, + $ExceptionHandlerProvider, + $FilterProvider, + $InterpolateProvider, + $IntervalProvider, + $HttpProvider, + $HttpBackendProvider, + $LocationProvider, + $LogProvider, + $ParseProvider, + $RootScopeProvider, + $QProvider, + $$QProvider, + $$SanitizeUriProvider, + $SceProvider, + $SceDelegateProvider, + $SnifferProvider, + $TemplateCacheProvider, + $TemplateRequestProvider, + $$TestabilityProvider, + $TimeoutProvider, + $$RAFProvider, + $$AsyncCallbackProvider, + $WindowProvider + */ + + + /** + * @ngdoc object + * @name angular.version + * @module ng + * @description + * An object that contains information about the current AngularJS version. This object has the + * following properties: + * + * - `full` – `{string}` – Full version string, such as "0.9.18". + * - `major` – `{number}` – Major version number, such as "0". + * - `minor` – `{number}` – Minor version number, such as "9". + * - `dot` – `{number}` – Dot version number, such as "18". + * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". + */ + var version = { + full: '1.3.0', // all of these placeholder strings will be replaced by grunt's + major: 1, // package task + minor: 3, + dot: 0, + codeName: 'superluminal-nudge' }; - }); -} - -/* global angularModule: true, - version: true, - - $LocaleProvider, - $CompileProvider, - - htmlAnchorDirective, - inputDirective, - inputDirective, - formDirective, - scriptDirective, - selectDirective, - styleDirective, - optionDirective, - ngBindDirective, - ngBindHtmlDirective, - ngBindTemplateDirective, - ngClassDirective, - ngClassEvenDirective, - ngClassOddDirective, - ngCspDirective, - ngCloakDirective, - ngControllerDirective, - ngFormDirective, - ngHideDirective, - ngIfDirective, - ngIncludeDirective, - ngIncludeFillContentDirective, - ngInitDirective, - ngNonBindableDirective, - ngPluralizeDirective, - ngRepeatDirective, - ngShowDirective, - ngStyleDirective, - ngSwitchDirective, - ngSwitchWhenDirective, - ngSwitchDefaultDirective, - ngOptionsDirective, - ngTranscludeDirective, - ngModelDirective, - ngListDirective, - ngChangeDirective, - patternDirective, - patternDirective, - requiredDirective, - requiredDirective, - minlengthDirective, - minlengthDirective, - maxlengthDirective, - maxlengthDirective, - ngValueDirective, - ngModelOptionsDirective, - ngAttributeAliasDirectives, - ngEventDirectives, - - $AnchorScrollProvider, - $AnimateProvider, - $BrowserProvider, - $CacheFactoryProvider, - $ControllerProvider, - $DocumentProvider, - $ExceptionHandlerProvider, - $FilterProvider, - $InterpolateProvider, - $IntervalProvider, - $HttpProvider, - $HttpBackendProvider, - $LocationProvider, - $LogProvider, - $ParseProvider, - $RootScopeProvider, - $QProvider, - $$QProvider, - $$SanitizeUriProvider, - $SceProvider, - $SceDelegateProvider, - $SnifferProvider, - $TemplateCacheProvider, - $TemplateRequestProvider, - $$TestabilityProvider, - $TimeoutProvider, - $$RAFProvider, - $$AsyncCallbackProvider, - $WindowProvider -*/ + function publishExternalAPI(angular) { + extend(angular, { + 'bootstrap': bootstrap, + 'copy': copy, + 'extend': extend, + 'equals': equals, + 'element': jqLite, + 'forEach': forEach, + 'injector': createInjector, + 'noop': noop, + 'bind': bind, + 'toJson': toJson, + 'fromJson': fromJson, + 'identity': identity, + 'isUndefined': isUndefined, + 'isDefined': isDefined, + 'isString': isString, + 'isFunction': isFunction, + 'isObject': isObject, + 'isNumber': isNumber, + 'isElement': isElement, + 'isArray': isArray, + 'version': version, + 'isDate': isDate, + 'lowercase': lowercase, + 'uppercase': uppercase, + 'callbacks': {counter: 0}, + 'getTestability': getTestability, + '$$minErr': minErr, + '$$csp': csp, + 'reloadWithDebugInfo': reloadWithDebugInfo + }); -/** - * @ngdoc object - * @name angular.version - * @module ng - * @description - * An object that contains information about the current AngularJS version. This object has the - * following properties: - * - * - `full` – `{string}` – Full version string, such as "0.9.18". - * - `major` – `{number}` – Major version number, such as "0". - * - `minor` – `{number}` – Minor version number, such as "9". - * - `dot` – `{number}` – Dot version number, such as "18". - * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". - */ -var version = { - full: '1.3.0', // all of these placeholder strings will be replaced by grunt's - major: 1, // package task - minor: 3, - dot: 0, - codeName: 'superluminal-nudge' -}; - - -function publishExternalAPI(angular){ - extend(angular, { - 'bootstrap': bootstrap, - 'copy': copy, - 'extend': extend, - 'equals': equals, - 'element': jqLite, - 'forEach': forEach, - 'injector': createInjector, - 'noop': noop, - 'bind': bind, - 'toJson': toJson, - 'fromJson': fromJson, - 'identity': identity, - 'isUndefined': isUndefined, - 'isDefined': isDefined, - 'isString': isString, - 'isFunction': isFunction, - 'isObject': isObject, - 'isNumber': isNumber, - 'isElement': isElement, - 'isArray': isArray, - 'version': version, - 'isDate': isDate, - 'lowercase': lowercase, - 'uppercase': uppercase, - 'callbacks': {counter: 0}, - 'getTestability': getTestability, - '$$minErr': minErr, - '$$csp': csp, - 'reloadWithDebugInfo': reloadWithDebugInfo - }); + angularModule = setupModuleLoader(window); + try { + angularModule('ngLocale'); + } catch (e) { + angularModule('ngLocale', []).provider('$locale', $LocaleProvider); + } - angularModule = setupModuleLoader(window); - try { - angularModule('ngLocale'); - } catch (e) { - angularModule('ngLocale', []).provider('$locale', $LocaleProvider); - } - - angularModule('ng', ['ngLocale'], ['$provide', - function ngModule($provide) { - // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. - $provide.provider({ - $$sanitizeUri: $$SanitizeUriProvider - }); - $provide.provider('$compile', $CompileProvider). - directive({ - a: htmlAnchorDirective, - input: inputDirective, - textarea: inputDirective, - form: formDirective, - script: scriptDirective, - select: selectDirective, - style: styleDirective, - option: optionDirective, - ngBind: ngBindDirective, - ngBindHtml: ngBindHtmlDirective, - ngBindTemplate: ngBindTemplateDirective, - ngClass: ngClassDirective, - ngClassEven: ngClassEvenDirective, - ngClassOdd: ngClassOddDirective, - ngCloak: ngCloakDirective, - ngController: ngControllerDirective, - ngForm: ngFormDirective, - ngHide: ngHideDirective, - ngIf: ngIfDirective, - ngInclude: ngIncludeDirective, - ngInit: ngInitDirective, - ngNonBindable: ngNonBindableDirective, - ngPluralize: ngPluralizeDirective, - ngRepeat: ngRepeatDirective, - ngShow: ngShowDirective, - ngStyle: ngStyleDirective, - ngSwitch: ngSwitchDirective, - ngSwitchWhen: ngSwitchWhenDirective, - ngSwitchDefault: ngSwitchDefaultDirective, - ngOptions: ngOptionsDirective, - ngTransclude: ngTranscludeDirective, - ngModel: ngModelDirective, - ngList: ngListDirective, - ngChange: ngChangeDirective, - pattern: patternDirective, - ngPattern: patternDirective, - required: requiredDirective, - ngRequired: requiredDirective, - minlength: minlengthDirective, - ngMinlength: minlengthDirective, - maxlength: maxlengthDirective, - ngMaxlength: maxlengthDirective, - ngValue: ngValueDirective, - ngModelOptions: ngModelOptionsDirective - }). - directive({ - ngInclude: ngIncludeFillContentDirective - }). - directive(ngAttributeAliasDirectives). - directive(ngEventDirectives); - $provide.provider({ - $anchorScroll: $AnchorScrollProvider, - $animate: $AnimateProvider, - $browser: $BrowserProvider, - $cacheFactory: $CacheFactoryProvider, - $controller: $ControllerProvider, - $document: $DocumentProvider, - $exceptionHandler: $ExceptionHandlerProvider, - $filter: $FilterProvider, - $interpolate: $InterpolateProvider, - $interval: $IntervalProvider, - $http: $HttpProvider, - $httpBackend: $HttpBackendProvider, - $location: $LocationProvider, - $log: $LogProvider, - $parse: $ParseProvider, - $rootScope: $RootScopeProvider, - $q: $QProvider, - $$q: $$QProvider, - $sce: $SceProvider, - $sceDelegate: $SceDelegateProvider, - $sniffer: $SnifferProvider, - $templateCache: $TemplateCacheProvider, - $templateRequest: $TemplateRequestProvider, - $$testability: $$TestabilityProvider, - $timeout: $TimeoutProvider, - $window: $WindowProvider, - $$rAF: $$RAFProvider, - $$asyncCallback : $$AsyncCallbackProvider - }); + angularModule('ng', ['ngLocale'], ['$provide', + function ngModule($provide) { + // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. + $provide.provider({ + $$sanitizeUri: $$SanitizeUriProvider + }); + $provide.provider('$compile', $CompileProvider). + directive({ + a: htmlAnchorDirective, + input: inputDirective, + textarea: inputDirective, + form: formDirective, + script: scriptDirective, + select: selectDirective, + style: styleDirective, + option: optionDirective, + ngBind: ngBindDirective, + ngBindHtml: ngBindHtmlDirective, + ngBindTemplate: ngBindTemplateDirective, + ngClass: ngClassDirective, + ngClassEven: ngClassEvenDirective, + ngClassOdd: ngClassOddDirective, + ngCloak: ngCloakDirective, + ngController: ngControllerDirective, + ngForm: ngFormDirective, + ngHide: ngHideDirective, + ngIf: ngIfDirective, + ngInclude: ngIncludeDirective, + ngInit: ngInitDirective, + ngNonBindable: ngNonBindableDirective, + ngPluralize: ngPluralizeDirective, + ngRepeat: ngRepeatDirective, + ngShow: ngShowDirective, + ngStyle: ngStyleDirective, + ngSwitch: ngSwitchDirective, + ngSwitchWhen: ngSwitchWhenDirective, + ngSwitchDefault: ngSwitchDefaultDirective, + ngOptions: ngOptionsDirective, + ngTransclude: ngTranscludeDirective, + ngModel: ngModelDirective, + ngList: ngListDirective, + ngChange: ngChangeDirective, + pattern: patternDirective, + ngPattern: patternDirective, + required: requiredDirective, + ngRequired: requiredDirective, + minlength: minlengthDirective, + ngMinlength: minlengthDirective, + maxlength: maxlengthDirective, + ngMaxlength: maxlengthDirective, + ngValue: ngValueDirective, + ngModelOptions: ngModelOptionsDirective + }). + directive({ + ngInclude: ngIncludeFillContentDirective + }). + directive(ngAttributeAliasDirectives). + directive(ngEventDirectives); + $provide.provider({ + $anchorScroll: $AnchorScrollProvider, + $animate: $AnimateProvider, + $browser: $BrowserProvider, + $cacheFactory: $CacheFactoryProvider, + $controller: $ControllerProvider, + $document: $DocumentProvider, + $exceptionHandler: $ExceptionHandlerProvider, + $filter: $FilterProvider, + $interpolate: $InterpolateProvider, + $interval: $IntervalProvider, + $http: $HttpProvider, + $httpBackend: $HttpBackendProvider, + $location: $LocationProvider, + $log: $LogProvider, + $parse: $ParseProvider, + $rootScope: $RootScopeProvider, + $q: $QProvider, + $$q: $$QProvider, + $sce: $SceProvider, + $sceDelegate: $SceDelegateProvider, + $sniffer: $SnifferProvider, + $templateCache: $TemplateCacheProvider, + $templateRequest: $TemplateRequestProvider, + $$testability: $$TestabilityProvider, + $timeout: $TimeoutProvider, + $window: $WindowProvider, + $$rAF: $$RAFProvider, + $$asyncCallback: $$AsyncCallbackProvider + }); + } + ]); } - ]); -} -/* global JQLitePrototype: true, - addEventListenerFn: true, - removeEventListenerFn: true, - BOOLEAN_ATTR: true, - ALIASED_ATTR: true, -*/ + /* global JQLitePrototype: true, + addEventListenerFn: true, + removeEventListenerFn: true, + BOOLEAN_ATTR: true, + ALIASED_ATTR: true, + */ ////////////////////////////////// //JQLite ////////////////////////////////// -/** - * @ngdoc function - * @name angular.element - * @module ng - * @kind function - * - * @description - * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. - * - * If jQuery is available, `angular.element` is an alias for the - * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` - * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." - * - *
          jqLite is a tiny, API-compatible subset of jQuery that allows - * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most - * commonly needed functionality with the goal of having a very small footprint.
          - * - * To use jQuery, simply load it before `DOMContentLoaded` event fired. - * - *
          **Note:** all element references in Angular are always wrapped with jQuery or - * jqLite; they are never raw DOM references.
          - * - * ## Angular's jqLite - * jqLite provides only the following jQuery methods: - * - * - [`addClass()`](http://api.jquery.com/addClass/) - * - [`after()`](http://api.jquery.com/after/) - * - [`append()`](http://api.jquery.com/append/) - * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters - * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData - * - [`children()`](http://api.jquery.com/children/) - Does not support selectors - * - [`clone()`](http://api.jquery.com/clone/) - * - [`contents()`](http://api.jquery.com/contents/) - * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()` - * - [`data()`](http://api.jquery.com/data/) - * - [`detach()`](http://api.jquery.com/detach/) - * - [`empty()`](http://api.jquery.com/empty/) - * - [`eq()`](http://api.jquery.com/eq/) - * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name - * - [`hasClass()`](http://api.jquery.com/hasClass/) - * - [`html()`](http://api.jquery.com/html/) - * - [`next()`](http://api.jquery.com/next/) - Does not support selectors - * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData - * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors - * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors - * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors - * - [`prepend()`](http://api.jquery.com/prepend/) - * - [`prop()`](http://api.jquery.com/prop/) - * - [`ready()`](http://api.jquery.com/ready/) - * - [`remove()`](http://api.jquery.com/remove/) - * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - * - [`removeClass()`](http://api.jquery.com/removeClass/) - * - [`removeData()`](http://api.jquery.com/removeData/) - * - [`replaceWith()`](http://api.jquery.com/replaceWith/) - * - [`text()`](http://api.jquery.com/text/) - * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. - * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces - * - [`val()`](http://api.jquery.com/val/) - * - [`wrap()`](http://api.jquery.com/wrap/) - * - * ## jQuery/jqLite Extras - * Angular also provides the following additional methods and events to both jQuery and jqLite: - * - * ### Events - * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event - * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM - * element before it is removed. - * - * ### Methods - * - `controller(name)` - retrieves the controller of the current element or its parent. By default - * retrieves controller associated with the `ngController` directive. If `name` is provided as - * camelCase directive name, then the controller for this directive will be retrieved (e.g. - * `'ngModel'`). - * - `injector()` - retrieves the injector of the current element or its parent. - * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current - * element or its parent. - * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the - * current element. This getter should be used only on elements that contain a directive which starts a new isolate - * scope. Calling `scope()` on this element always returns the original non-isolate scope. - * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top - * parent element is reached. - * - * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. - * @returns {Object} jQuery object. - */ + /** + * @ngdoc function + * @name angular.element + * @module ng + * @kind function + * + * @description + * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. + * + * If jQuery is available, `angular.element` is an alias for the + * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` + * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + * + *
          jqLite is a tiny, API-compatible subset of jQuery that allows + * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most + * commonly needed functionality with the goal of having a very small footprint.
          + * + * To use jQuery, simply load it before `DOMContentLoaded` event fired. + * + *
          **Note:** all element references in Angular are always wrapped with jQuery or + * jqLite; they are never raw DOM references.
          + * + * ## Angular's jqLite + * jqLite provides only the following jQuery methods: + * + * - [`addClass()`](http://api.jquery.com/addClass/) + * - [`after()`](http://api.jquery.com/after/) + * - [`append()`](http://api.jquery.com/append/) + * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters + * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData + * - [`children()`](http://api.jquery.com/children/) - Does not support selectors + * - [`clone()`](http://api.jquery.com/clone/) + * - [`contents()`](http://api.jquery.com/contents/) + * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()` + * - [`data()`](http://api.jquery.com/data/) + * - [`detach()`](http://api.jquery.com/detach/) + * - [`empty()`](http://api.jquery.com/empty/) + * - [`eq()`](http://api.jquery.com/eq/) + * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name + * - [`hasClass()`](http://api.jquery.com/hasClass/) + * - [`html()`](http://api.jquery.com/html/) + * - [`next()`](http://api.jquery.com/next/) - Does not support selectors + * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData + * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors + * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors + * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors + * - [`prepend()`](http://api.jquery.com/prepend/) + * - [`prop()`](http://api.jquery.com/prop/) + * - [`ready()`](http://api.jquery.com/ready/) + * - [`remove()`](http://api.jquery.com/remove/) + * - [`removeAttr()`](http://api.jquery.com/removeAttr/) + * - [`removeClass()`](http://api.jquery.com/removeClass/) + * - [`removeData()`](http://api.jquery.com/removeData/) + * - [`replaceWith()`](http://api.jquery.com/replaceWith/) + * - [`text()`](http://api.jquery.com/text/) + * - [`toggleClass()`](http://api.jquery.com/toggleClass/) + * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. + * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces + * - [`val()`](http://api.jquery.com/val/) + * - [`wrap()`](http://api.jquery.com/wrap/) + * + * ## jQuery/jqLite Extras + * Angular also provides the following additional methods and events to both jQuery and jqLite: + * + * ### Events + * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event + * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM + * element before it is removed. + * + * ### Methods + * - `controller(name)` - retrieves the controller of the current element or its parent. By default + * retrieves controller associated with the `ngController` directive. If `name` is provided as + * camelCase directive name, then the controller for this directive will be retrieved (e.g. + * `'ngModel'`). + * - `injector()` - retrieves the injector of the current element or its parent. + * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current + * element or its parent. + * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the + * current element. This getter should be used only on elements that contain a directive which starts a new isolate + * scope. Calling `scope()` on this element always returns the original non-isolate scope. + * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top + * parent element is reached. + * + * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. + * @returns {Object} jQuery object. + */ -JQLite.expando = 'ng339'; + JQLite.expando = 'ng339'; -var jqCache = JQLite.cache = {}, - jqId = 1, - addEventListenerFn = function(element, type, fn) { - element.addEventListener(type, fn, false); - }, - removeEventListenerFn = function(element, type, fn) { - element.removeEventListener(type, fn, false); - }; + var jqCache = JQLite.cache = {}, + jqId = 1, + addEventListenerFn = function (element, type, fn) { + element.addEventListener(type, fn, false); + }, + removeEventListenerFn = function (element, type, fn) { + element.removeEventListener(type, fn, false); + }; -/* - * !!! This is an undocumented "private" function !!! - */ -JQLite._data = function(node) { - //jQuery always returns an object on cache miss - return this.cache[node[this.expando]] || {}; -}; + /* + * !!! This is an undocumented "private" function !!! + */ + JQLite._data = function (node) { + //jQuery always returns an object on cache miss + return this.cache[node[this.expando]] || {}; + }; -function jqNextId() { return ++jqId; } + function jqNextId() { + return ++jqId; + } -var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; -var MOZ_HACK_REGEXP = /^moz([A-Z])/; -var MOUSE_EVENT_MAP= { mouseleave : "mouseout", mouseenter : "mouseover"}; -var jqLiteMinErr = minErr('jqLite'); + var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; + var MOZ_HACK_REGEXP = /^moz([A-Z])/; + var MOUSE_EVENT_MAP = {mouseleave: "mouseout", mouseenter: "mouseover"}; + var jqLiteMinErr = minErr('jqLite'); -/** - * Converts snake_case to camelCase. - * Also there is special case for Moz prefix starting with upper case letter. - * @param name Name to normalize - */ -function camelCase(name) { - return name. - replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { - return offset ? letter.toUpperCase() : letter; - }). - replace(MOZ_HACK_REGEXP, 'Moz$1'); -} - -var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; -var HTML_REGEXP = /<|&#?\w+;/; -var TAG_NAME_REGEXP = /<([\w:]+)/; -var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; - -var wrapMap = { - 'option': [1, ''], - - 'thead': [1, '', '
          '], - 'col': [2, '', '
          '], - 'tr': [2, '', '
          '], - 'td': [3, '', '
          '], - '_default': [0, "", ""] -}; - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - - -function jqLiteIsTextNode(html) { - return !HTML_REGEXP.test(html); -} - -function jqLiteAcceptsData(node) { - // The window object can accept data but has no nodeType - // Otherwise we are only interested in elements (1) and documents (9) - var nodeType = node.nodeType; - return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; -} - -function jqLiteBuildFragment(html, context) { - var tmp, tag, wrap, - fragment = context.createDocumentFragment(), - nodes = [], i; - - if (jqLiteIsTextNode(html)) { - // Convert non-html into a text node - nodes.push(context.createTextNode(html)); - } else { - // Convert html into DOM nodes - tmp = tmp || fragment.appendChild(context.createElement("div")); - tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); - wrap = wrapMap[tag] || wrapMap._default; - tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; - - // Descend through wrappers to the right content - i = wrap[0]; - while (i--) { - tmp = tmp.lastChild; + /** + * Converts snake_case to camelCase. + * Also there is special case for Moz prefix starting with upper case letter. + * @param name Name to normalize + */ + function camelCase(name) { + return name. + replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) { + return offset ? letter.toUpperCase() : letter; + }). + replace(MOZ_HACK_REGEXP, 'Moz$1'); } - nodes = concat(nodes, tmp.childNodes); + var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; + var HTML_REGEXP = /<|&#?\w+;/; + var TAG_NAME_REGEXP = /<([\w:]+)/; + var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; - tmp = fragment.firstChild; - tmp.textContent = ""; - } + var wrapMap = { + 'option': [1, ''], - // Remove wrapper from fragment - fragment.textContent = ""; - fragment.innerHTML = ""; // Clear inner HTML - forEach(nodes, function(node) { - fragment.appendChild(node); - }); + 'thead': [1, '', '
          '], + 'col': [2, '', '
          '], + 'tr': [2, '', '
          '], + 'td': [3, '', '
          '], + '_default': [0, "", ""] + }; - return fragment; -} + wrapMap.optgroup = wrapMap.option; + wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; + wrapMap.th = wrapMap.td; -function jqLiteParseHTML(html, context) { - context = context || document; - var parsed; - if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { - return [context.createElement(parsed[1])]; - } + function jqLiteIsTextNode(html) { + return !HTML_REGEXP.test(html); + } - if ((parsed = jqLiteBuildFragment(html, context))) { - return parsed.childNodes; - } + function jqLiteAcceptsData(node) { + // The window object can accept data but has no nodeType + // Otherwise we are only interested in elements (1) and documents (9) + var nodeType = node.nodeType; + return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; + } - return []; -} + function jqLiteBuildFragment(html, context) { + var tmp, tag, wrap, + fragment = context.createDocumentFragment(), + nodes = [], i; -///////////////////////////////////////////// -function JQLite(element) { - if (element instanceof JQLite) { - return element; - } - - var argIsString; - - if (isString(element)) { - element = trim(element); - argIsString = true; - } - if (!(this instanceof JQLite)) { - if (argIsString && element.charAt(0) != '<') { - throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); - } - return new JQLite(element); - } - - if (argIsString) { - jqLiteAddNodes(this, jqLiteParseHTML(element)); - } else { - jqLiteAddNodes(this, element); - } -} - -function jqLiteClone(element) { - return element.cloneNode(true); -} - -function jqLiteDealoc(element, onlyDescendants){ - if (!onlyDescendants) jqLiteRemoveData(element); - - if (element.querySelectorAll) { - var descendants = element.querySelectorAll('*'); - for (var i = 0, l = descendants.length; i < l; i++) { - jqLiteRemoveData(descendants[i]); + if (jqLiteIsTextNode(html)) { + // Convert non-html into a text node + nodes.push(context.createTextNode(html)); + } else { + // Convert html into DOM nodes + tmp = tmp || fragment.appendChild(context.createElement("div")); + tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); + wrap = wrapMap[tag] || wrapMap._default; + tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; + + // Descend through wrappers to the right content + i = wrap[0]; + while (i--) { + tmp = tmp.lastChild; + } + + nodes = concat(nodes, tmp.childNodes); + + tmp = fragment.firstChild; + tmp.textContent = ""; + } + + // Remove wrapper from fragment + fragment.textContent = ""; + fragment.innerHTML = ""; // Clear inner HTML + forEach(nodes, function (node) { + fragment.appendChild(node); + }); + + return fragment; } - } -} -function jqLiteOff(element, type, fn, unsupported) { - if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); + function jqLiteParseHTML(html, context) { + context = context || document; + var parsed; - var expandoStore = jqLiteExpandoStore(element); - var events = expandoStore && expandoStore.events; - var handle = expandoStore && expandoStore.handle; + if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { + return [context.createElement(parsed[1])]; + } - if (!handle) return; //no listeners registered + if ((parsed = jqLiteBuildFragment(html, context))) { + return parsed.childNodes; + } - if (!type) { - for (type in events) { - if (type !== '$destroy') { - removeEventListenerFn(element, type, handle); - } - delete events[type]; + return []; } - } else { - forEach(type.split(' '), function(type) { - if (isDefined(fn)) { - var listenerFns = events[type]; - arrayRemove(listenerFns || [], fn); - if (listenerFns && listenerFns.length > 0) { - return; + +///////////////////////////////////////////// + function JQLite(element) { + if (element instanceof JQLite) { + return element; } - } - removeEventListenerFn(element, type, handle); - delete events[type]; - }); - } -} + var argIsString; -function jqLiteRemoveData(element, name) { - var expandoId = element.ng339; - var expandoStore = expandoId && jqCache[expandoId]; + if (isString(element)) { + element = trim(element); + argIsString = true; + } + if (!(this instanceof JQLite)) { + if (argIsString && element.charAt(0) != '<') { + throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); + } + return new JQLite(element); + } - if (expandoStore) { - if (name) { - delete expandoStore.data[name]; - return; + if (argIsString) { + jqLiteAddNodes(this, jqLiteParseHTML(element)); + } else { + jqLiteAddNodes(this, element); + } } - if (expandoStore.handle) { - if (expandoStore.events.$destroy) { - expandoStore.handle({}, '$destroy'); - } - jqLiteOff(element); + function jqLiteClone(element) { + return element.cloneNode(true); } - delete jqCache[expandoId]; - element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it - } -} + function jqLiteDealoc(element, onlyDescendants) { + if (!onlyDescendants) jqLiteRemoveData(element); -function jqLiteExpandoStore(element, createIfNecessary) { - var expandoId = element.ng339, - expandoStore = expandoId && jqCache[expandoId]; - - if (createIfNecessary && !expandoStore) { - element.ng339 = expandoId = jqNextId(); - expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; - } + if (element.querySelectorAll) { + var descendants = element.querySelectorAll('*'); + for (var i = 0, l = descendants.length; i < l; i++) { + jqLiteRemoveData(descendants[i]); + } + } + } - return expandoStore; -} + function jqLiteOff(element, type, fn, unsupported) { + if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); + var expandoStore = jqLiteExpandoStore(element); + var events = expandoStore && expandoStore.events; + var handle = expandoStore && expandoStore.handle; -function jqLiteData(element, key, value) { - if (jqLiteAcceptsData(element)) { + if (!handle) return; //no listeners registered - var isSimpleSetter = isDefined(value); - var isSimpleGetter = !isSimpleSetter && key && !isObject(key); - var massGetter = !key; - var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); - var data = expandoStore && expandoStore.data; + if (!type) { + for (type in events) { + if (type !== '$destroy') { + removeEventListenerFn(element, type, handle); + } + delete events[type]; + } + } else { + forEach(type.split(' '), function (type) { + if (isDefined(fn)) { + var listenerFns = events[type]; + arrayRemove(listenerFns || [], fn); + if (listenerFns && listenerFns.length > 0) { + return; + } + } - if (isSimpleSetter) { // data('key', value) - data[key] = value; - } else { - if (massGetter) { // data() - return data; - } else { - if (isSimpleGetter) { // data('key') - // don't force creation of expandoStore if it doesn't exist yet - return data && data[key]; - } else { // mass-setter: data({key1: val1, key2: val2}) - extend(data, key); + removeEventListenerFn(element, type, handle); + delete events[type]; + }); } - } } - } -} - -function jqLiteHasClass(element, selector) { - if (!element.getAttribute) return false; - return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). - indexOf( " " + selector + " " ) > -1); -} - -function jqLiteRemoveClass(element, cssClasses) { - if (cssClasses && element.setAttribute) { - forEach(cssClasses.split(' '), function(cssClass) { - element.setAttribute('class', trim( - (" " + (element.getAttribute('class') || '') + " ") - .replace(/[\n\t]/g, " ") - .replace(" " + trim(cssClass) + " ", " ")) - ); - }); - } -} - -function jqLiteAddClass(element, cssClasses) { - if (cssClasses && element.setAttribute) { - var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') - .replace(/[\n\t]/g, " "); - - forEach(cssClasses.split(' '), function(cssClass) { - cssClass = trim(cssClass); - if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { - existingClasses += cssClass + ' '; - } - }); - element.setAttribute('class', trim(existingClasses)); - } -} + function jqLiteRemoveData(element, name) { + var expandoId = element.ng339; + var expandoStore = expandoId && jqCache[expandoId]; + if (expandoStore) { + if (name) { + delete expandoStore.data[name]; + return; + } -function jqLiteAddNodes(root, elements) { - // THIS CODE IS VERY HOT. Don't make changes without benchmarking. + if (expandoStore.handle) { + if (expandoStore.events.$destroy) { + expandoStore.handle({}, '$destroy'); + } + jqLiteOff(element); + } + delete jqCache[expandoId]; + element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it + } + } - if (elements) { - // if a Node (the most common case) - if (elements.nodeType) { - root[root.length++] = elements; - } else { - var length = elements.length; + function jqLiteExpandoStore(element, createIfNecessary) { + var expandoId = element.ng339, + expandoStore = expandoId && jqCache[expandoId]; - // if an Array or NodeList and not a Window - if (typeof length === 'number' && elements.window !== elements) { - if (length) { - for (var i = 0; i < length; i++) { - root[root.length++] = elements[i]; - } + if (createIfNecessary && !expandoStore) { + element.ng339 = expandoId = jqNextId(); + expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; } - } else { - root[root.length++] = elements; - } + + return expandoStore; } - } -} -function jqLiteController(element, name) { - return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); -} + function jqLiteData(element, key, value) { + if (jqLiteAcceptsData(element)) { -function jqLiteInheritedData(element, name, value) { - // if element is the document object work with the html element instead - // this makes $(document).scope() possible - if(element.nodeType == NODE_TYPE_DOCUMENT) { - element = element.documentElement; - } - var names = isArray(name) ? name : [name]; + var isSimpleSetter = isDefined(value); + var isSimpleGetter = !isSimpleSetter && key && !isObject(key); + var massGetter = !key; + var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); + var data = expandoStore && expandoStore.data; - while (element) { - for (var i = 0, ii = names.length; i < ii; i++) { - if ((value = jqLite.data(element, names[i])) !== undefined) return value; + if (isSimpleSetter) { // data('key', value) + data[key] = value; + } else { + if (massGetter) { // data() + return data; + } else { + if (isSimpleGetter) { // data('key') + // don't force creation of expandoStore if it doesn't exist yet + return data && data[key]; + } else { // mass-setter: data({key1: val1, key2: val2}) + extend(data, key); + } + } + } + } } - // If dealing with a document fragment node with a host element, and no parent, use the host - // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM - // to lookup parent controllers. - element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); - } -} - -function jqLiteEmpty(element) { - jqLiteDealoc(element, true); - while (element.firstChild) { - element.removeChild(element.firstChild); - } -} - -function jqLiteRemove(element, keepData) { - if (!keepData) jqLiteDealoc(element); - var parent = element.parentNode; - if (parent) parent.removeChild(element); -} - - -function jqLiteDocumentLoaded(action, win) { - win = win || window; - if (win.document.readyState === 'complete') { - // Force the action to be run async for consistent behaviour - // from the action's point of view - // i.e. it will definitely not be in a $apply - win.setTimeout(action); - } else { - // No need to unbind this handler as load is only ever called once - jqLite(win).on('load', action); - } -} - -////////////////////////////////////////// -// Functions which are declared directly. -////////////////////////////////////////// -var JQLitePrototype = JQLite.prototype = { - ready: function(fn) { - var fired = false; - - function trigger() { - if (fired) return; - fired = true; - fn(); + function jqLiteHasClass(element, selector) { + if (!element.getAttribute) return false; + return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). + indexOf(" " + selector + " ") > -1); } - // check if document is already loaded - if (document.readyState === 'complete'){ - setTimeout(trigger); - } else { - this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - // jshint -W064 - JQLite(window).on('load', trigger); // fallback to window.onload for others - // jshint +W064 - this.on('DOMContentLoaded', trigger); + function jqLiteRemoveClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { + forEach(cssClasses.split(' '), function (cssClass) { + element.setAttribute('class', trim( + (" " + (element.getAttribute('class') || '') + " ") + .replace(/[\n\t]/g, " ") + .replace(" " + trim(cssClass) + " ", " ")) + ); + }); + } } - }, - toString: function() { - var value = []; - forEach(this, function(e){ value.push('' + e);}); - return '[' + value.join(', ') + ']'; - }, - - eq: function(index) { - return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); - }, - - length: 0, - push: push, - sort: [].sort, - splice: [].splice -}; -////////////////////////////////////////// -// Functions iterating getter/setters. -// these functions return self on setter and -// value on get. -////////////////////////////////////////// -var BOOLEAN_ATTR = {}; -forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { - BOOLEAN_ATTR[lowercase(value)] = value; -}); -var BOOLEAN_ELEMENTS = {}; -forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { - BOOLEAN_ELEMENTS[value] = true; -}); -var ALIASED_ATTR = { - 'ngMinlength' : 'minlength', - 'ngMaxlength' : 'maxlength', - 'ngMin' : 'min', - 'ngMax' : 'max', - 'ngPattern' : 'pattern' -}; - -function getBooleanAttrName(element, name) { - // check dom last since we will most likely fail on name - var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; - - // booleanAttr is here twice to minimize DOM access - return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; -} - -function getAliasedAttrName(element, name) { - var nodeName = element.nodeName; - return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name]; -} - -forEach({ - data: jqLiteData, - removeData: jqLiteRemoveData -}, function(fn, name) { - JQLite[name] = fn; -}); - -forEach({ - data: jqLiteData, - inheritedData: jqLiteInheritedData, - - scope: function(element) { - // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); - }, - - isolateScope: function(element) { - // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); - }, - - controller: jqLiteController, - - injector: function(element) { - return jqLiteInheritedData(element, '$injector'); - }, - - removeAttr: function(element, name) { - element.removeAttribute(name); - }, - - hasClass: jqLiteHasClass, - - css: function(element, name, value) { - name = camelCase(name); - - if (isDefined(value)) { - element.style[name] = value; - } else { - return element.style[name]; - } - }, - - attr: function(element, name, value){ - var lowercasedName = lowercase(name); - if (BOOLEAN_ATTR[lowercasedName]) { - if (isDefined(value)) { - if (!!value) { - element[name] = true; - element.setAttribute(name, lowercasedName); - } else { - element[name] = false; - element.removeAttribute(lowercasedName); + function jqLiteAddClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { + var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') + .replace(/[\n\t]/g, " "); + + forEach(cssClasses.split(' '), function (cssClass) { + cssClass = trim(cssClass); + if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { + existingClasses += cssClass + ' '; + } + }); + + element.setAttribute('class', trim(existingClasses)); } - } else { - return (element[name] || - (element.attributes.getNamedItem(name)|| noop).specified) - ? lowercasedName - : undefined; - } - } else if (isDefined(value)) { - element.setAttribute(name, value); - } else if (element.getAttribute) { - // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code - // some elements (e.g. Document) don't have get attribute, so return undefined - var ret = element.getAttribute(name, 2); - // normalize non-existing attributes to undefined (as jQuery) - return ret === null ? undefined : ret; } - }, - prop: function(element, name, value) { - if (isDefined(value)) { - element[name] = value; - } else { - return element[name]; - } - }, - text: (function() { - getText.$dv = ''; - return getText; + function jqLiteAddNodes(root, elements) { + // THIS CODE IS VERY HOT. Don't make changes without benchmarking. - function getText(element, value) { - if (isUndefined(value)) { - var nodeType = element.nodeType; - return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; - } - element.textContent = value; - } - })(), - - val: function(element, value) { - if (isUndefined(value)) { - if (element.multiple && nodeName_(element) === 'select') { - var result = []; - forEach(element.options, function (option) { - if (option.selected) { - result.push(option.value || option.text); - } - }); - return result.length === 0 ? null : result; - } - return element.value; - } - element.value = value; - }, + if (elements) { - html: function(element, value) { - if (isUndefined(value)) { - return element.innerHTML; - } - jqLiteDealoc(element, true); - element.innerHTML = value; - }, - - empty: jqLiteEmpty -}, function(fn, name){ - /** - * Properties: writes return selection, reads return first value - */ - JQLite.prototype[name] = function(arg1, arg2) { - var i, key; - var nodeCount = this.length; - - // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it - // in a way that survives minification. - // jqLiteEmpty takes no arguments but is a setter. - if (fn !== jqLiteEmpty && - (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { - if (isObject(arg1)) { - - // we are a write, but the object properties are the key/values - for (i = 0; i < nodeCount; i++) { - if (fn === jqLiteData) { - // data() takes the whole object in jQuery - fn(this[i], arg1); - } else { - for (key in arg1) { - fn(this[i], key, arg1[key]); + // if a Node (the most common case) + if (elements.nodeType) { + root[root.length++] = elements; + } else { + var length = elements.length; + + // if an Array or NodeList and not a Window + if (typeof length === 'number' && elements.window !== elements) { + if (length) { + for (var i = 0; i < length; i++) { + root[root.length++] = elements[i]; + } + } + } else { + root[root.length++] = elements; + } } - } } - // return self for chaining - return this; - } else { - // we are a read, so read the first child. - // TODO: do we still need this? - var value = fn.$dv; - // Only if we have $dv do we iterate over all, otherwise it is just the first element. - var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; - for (var j = 0; j < jj; j++) { - var nodeValue = fn(this[j], arg1, arg2); - value = value ? value + nodeValue : nodeValue; - } - return value; - } - } else { - // we are a write, so apply to all children - for (i = 0; i < nodeCount; i++) { - fn(this[i], arg1, arg2); - } - // return self for chaining - return this; } - }; -}); - -function createEventHandler(element, events) { - var eventHandler = function (event, type) { - // jQuery specific api - event.isDefaultPrevented = function() { - return event.defaultPrevented; - }; - - var eventFns = events[type || event.type]; - var eventFnsLength = eventFns ? eventFns.length : 0; - if (!eventFnsLength) return; - if (isUndefined(event.immediatePropagationStopped)) { - var originalStopImmediatePropagation = event.stopImmediatePropagation; - event.stopImmediatePropagation = function() { - event.immediatePropagationStopped = true; + function jqLiteController(element, name) { + return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); + } - if (event.stopPropagation) { - event.stopPropagation(); + function jqLiteInheritedData(element, name, value) { + // if element is the document object work with the html element instead + // this makes $(document).scope() possible + if (element.nodeType == NODE_TYPE_DOCUMENT) { + element = element.documentElement; } + var names = isArray(name) ? name : [name]; + + while (element) { + for (var i = 0, ii = names.length; i < ii; i++) { + if ((value = jqLite.data(element, names[i])) !== undefined) return value; + } - if (originalStopImmediatePropagation) { - originalStopImmediatePropagation.call(event); + // If dealing with a document fragment node with a host element, and no parent, use the host + // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM + // to lookup parent controllers. + element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); } - }; } - event.isImmediatePropagationStopped = function() { - return event.immediatePropagationStopped === true; - }; + function jqLiteEmpty(element) { + jqLiteDealoc(element, true); + while (element.firstChild) { + element.removeChild(element.firstChild); + } + } - // Copy event handlers in case event handlers array is modified during execution. - if ((eventFnsLength > 1)) { - eventFns = shallowCopy(eventFns); + function jqLiteRemove(element, keepData) { + if (!keepData) jqLiteDealoc(element); + var parent = element.parentNode; + if (parent) parent.removeChild(element); } - for (var i = 0; i < eventFnsLength; i++) { - if (!event.isImmediatePropagationStopped()) { - eventFns[i].call(element, event); - } + + function jqLiteDocumentLoaded(action, win) { + win = win || window; + if (win.document.readyState === 'complete') { + // Force the action to be run async for consistent behaviour + // from the action's point of view + // i.e. it will definitely not be in a $apply + win.setTimeout(action); + } else { + // No need to unbind this handler as load is only ever called once + jqLite(win).on('load', action); + } } - }; - // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all - // events on `element` - eventHandler.elem = element; - return eventHandler; -} +////////////////////////////////////////// +// Functions which are declared directly. +////////////////////////////////////////// + var JQLitePrototype = JQLite.prototype = { + ready: function (fn) { + var fired = false; + + function trigger() { + if (fired) return; + fired = true; + fn(); + } + + // check if document is already loaded + if (document.readyState === 'complete') { + setTimeout(trigger); + } else { + this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 + // we can not use jqLite since we are not done loading and jQuery could be loaded later. + // jshint -W064 + JQLite(window).on('load', trigger); // fallback to window.onload for others + // jshint +W064 + this.on('DOMContentLoaded', trigger); + } + }, + toString: function () { + var value = []; + forEach(this, function (e) { + value.push('' + e); + }); + return '[' + value.join(', ') + ']'; + }, + + eq: function (index) { + return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); + }, + + length: 0, + push: push, + sort: [].sort, + splice: [].splice + }; ////////////////////////////////////////// -// Functions iterating traversal. -// These functions chain results into a single -// selector. +// Functions iterating getter/setters. +// these functions return self on setter and +// value on get. ////////////////////////////////////////// -forEach({ - removeData: jqLiteRemoveData, + var BOOLEAN_ATTR = {}; + forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function (value) { + BOOLEAN_ATTR[lowercase(value)] = value; + }); + var BOOLEAN_ELEMENTS = {}; + forEach('input,select,option,textarea,button,form,details'.split(','), function (value) { + BOOLEAN_ELEMENTS[value] = true; + }); + var ALIASED_ATTR = { + 'ngMinlength': 'minlength', + 'ngMaxlength': 'maxlength', + 'ngMin': 'min', + 'ngMax': 'max', + 'ngPattern': 'pattern' + }; - on: function jqLiteOn(element, type, fn, unsupported){ - if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); + function getBooleanAttrName(element, name) { + // check dom last since we will most likely fail on name + var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; - // Do not add event handlers to non-elements because they will not be cleaned up. - if (!jqLiteAcceptsData(element)) { - return; + // booleanAttr is here twice to minimize DOM access + return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; } - var expandoStore = jqLiteExpandoStore(element, true); - var events = expandoStore.events; - var handle = expandoStore.handle; - - if (!handle) { - handle = expandoStore.handle = createEventHandler(element, events); + function getAliasedAttrName(element, name) { + var nodeName = element.nodeName; + return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name]; } - // http://jsperf.com/string-indexof-vs-split - var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; - var i = types.length; + forEach({ + data: jqLiteData, + removeData: jqLiteRemoveData + }, function (fn, name) { + JQLite[name] = fn; + }); - while (i--) { - type = types[i]; - var eventFns = events[type]; + forEach({ + data: jqLiteData, + inheritedData: jqLiteInheritedData, - if (!eventFns) { - events[type] = []; + scope: function (element) { + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); + }, - if (type === 'mouseenter' || type === 'mouseleave') { - // Refer to jQuery's implementation of mouseenter & mouseleave - // Read about mouseenter and mouseleave: - // http://www.quirksmode.org/js/events_mouse.html#link8 + isolateScope: function (element) { + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); + }, - jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) { - var target = this, related = event.relatedTarget; - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !target.contains(related)) ){ - handle(event, type); - } - }); + controller: jqLiteController, - } else { - if (type !== '$destroy') { - addEventListenerFn(element, type, handle); - } - } - eventFns = events[type]; - } - eventFns.push(fn); - } - }, + injector: function (element) { + return jqLiteInheritedData(element, '$injector'); + }, - off: jqLiteOff, + removeAttr: function (element, name) { + element.removeAttribute(name); + }, - one: function(element, type, fn) { - element = jqLite(element); + hasClass: jqLiteHasClass, - //add the listener twice so that when it is called - //you can remove the original function and still be - //able to call element.off(ev, fn) normally - element.on(type, function onFn() { - element.off(type, fn); - element.off(type, onFn); - }); - element.on(type, fn); - }, - - replaceWith: function(element, replaceNode) { - var index, parent = element.parentNode; - jqLiteDealoc(element); - forEach(new JQLite(replaceNode), function(node){ - if (index) { - parent.insertBefore(node, index.nextSibling); - } else { - parent.replaceChild(node, element); - } - index = node; - }); - }, + css: function (element, name, value) { + name = camelCase(name); + + if (isDefined(value)) { + element.style[name] = value; + } else { + return element.style[name]; + } + }, + + attr: function (element, name, value) { + var lowercasedName = lowercase(name); + if (BOOLEAN_ATTR[lowercasedName]) { + if (isDefined(value)) { + if (!!value) { + element[name] = true; + element.setAttribute(name, lowercasedName); + } else { + element[name] = false; + element.removeAttribute(lowercasedName); + } + } else { + return (element[name] || + (element.attributes.getNamedItem(name) || noop).specified) + ? lowercasedName + : undefined; + } + } else if (isDefined(value)) { + element.setAttribute(name, value); + } else if (element.getAttribute) { + // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code + // some elements (e.g. Document) don't have get attribute, so return undefined + var ret = element.getAttribute(name, 2); + // normalize non-existing attributes to undefined (as jQuery) + return ret === null ? undefined : ret; + } + }, + + prop: function (element, name, value) { + if (isDefined(value)) { + element[name] = value; + } else { + return element[name]; + } + }, + + text: (function () { + getText.$dv = ''; + return getText; + + function getText(element, value) { + if (isUndefined(value)) { + var nodeType = element.nodeType; + return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; + } + element.textContent = value; + } + })(), + + val: function (element, value) { + if (isUndefined(value)) { + if (element.multiple && nodeName_(element) === 'select') { + var result = []; + forEach(element.options, function (option) { + if (option.selected) { + result.push(option.value || option.text); + } + }); + return result.length === 0 ? null : result; + } + return element.value; + } + element.value = value; + }, - children: function(element) { - var children = []; - forEach(element.childNodes, function(element){ - if (element.nodeType === NODE_TYPE_ELEMENT) - children.push(element); + html: function (element, value) { + if (isUndefined(value)) { + return element.innerHTML; + } + jqLiteDealoc(element, true); + element.innerHTML = value; + }, + + empty: jqLiteEmpty + }, function (fn, name) { + /** + * Properties: writes return selection, reads return first value + */ + JQLite.prototype[name] = function (arg1, arg2) { + var i, key; + var nodeCount = this.length; + + // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it + // in a way that survives minification. + // jqLiteEmpty takes no arguments but is a setter. + if (fn !== jqLiteEmpty && + (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { + if (isObject(arg1)) { + + // we are a write, but the object properties are the key/values + for (i = 0; i < nodeCount; i++) { + if (fn === jqLiteData) { + // data() takes the whole object in jQuery + fn(this[i], arg1); + } else { + for (key in arg1) { + fn(this[i], key, arg1[key]); + } + } + } + // return self for chaining + return this; + } else { + // we are a read, so read the first child. + // TODO: do we still need this? + var value = fn.$dv; + // Only if we have $dv do we iterate over all, otherwise it is just the first element. + var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; + for (var j = 0; j < jj; j++) { + var nodeValue = fn(this[j], arg1, arg2); + value = value ? value + nodeValue : nodeValue; + } + return value; + } + } else { + // we are a write, so apply to all children + for (i = 0; i < nodeCount; i++) { + fn(this[i], arg1, arg2); + } + // return self for chaining + return this; + } + }; }); - return children; - }, - contents: function(element) { - return element.contentDocument || element.childNodes || []; - }, + function createEventHandler(element, events) { + var eventHandler = function (event, type) { + // jQuery specific api + event.isDefaultPrevented = function () { + return event.defaultPrevented; + }; - append: function(element, node) { - var nodeType = element.nodeType; - if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; + var eventFns = events[type || event.type]; + var eventFnsLength = eventFns ? eventFns.length : 0; - node = new JQLite(node); + if (!eventFnsLength) return; - for (var i = 0, ii = node.length; i < ii; i++) { - var child = node[i]; - element.appendChild(child); - } - }, + if (isUndefined(event.immediatePropagationStopped)) { + var originalStopImmediatePropagation = event.stopImmediatePropagation; + event.stopImmediatePropagation = function () { + event.immediatePropagationStopped = true; - prepend: function(element, node) { - if (element.nodeType === NODE_TYPE_ELEMENT) { - var index = element.firstChild; - forEach(new JQLite(node), function(child){ - element.insertBefore(child, index); - }); - } - }, + if (event.stopPropagation) { + event.stopPropagation(); + } - wrap: function(element, wrapNode) { - wrapNode = jqLite(wrapNode).eq(0).clone()[0]; - var parent = element.parentNode; - if (parent) { - parent.replaceChild(wrapNode, element); - } - wrapNode.appendChild(element); - }, + if (originalStopImmediatePropagation) { + originalStopImmediatePropagation.call(event); + } + }; + } - remove: jqLiteRemove, + event.isImmediatePropagationStopped = function () { + return event.immediatePropagationStopped === true; + }; - detach: function(element) { - jqLiteRemove(element, true); - }, + // Copy event handlers in case event handlers array is modified during execution. + if ((eventFnsLength > 1)) { + eventFns = shallowCopy(eventFns); + } - after: function(element, newElement) { - var index = element, parent = element.parentNode; - newElement = new JQLite(newElement); + for (var i = 0; i < eventFnsLength; i++) { + if (!event.isImmediatePropagationStopped()) { + eventFns[i].call(element, event); + } + } + }; - for (var i = 0, ii = newElement.length; i < ii; i++) { - var node = newElement[i]; - parent.insertBefore(node, index.nextSibling); - index = node; + // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all + // events on `element` + eventHandler.elem = element; + return eventHandler; } - }, - addClass: jqLiteAddClass, - removeClass: jqLiteRemoveClass, +////////////////////////////////////////// +// Functions iterating traversal. +// These functions chain results into a single +// selector. +////////////////////////////////////////// + forEach({ + removeData: jqLiteRemoveData, - toggleClass: function(element, selector, condition) { - if (selector) { - forEach(selector.split(' '), function(className){ - var classCondition = condition; - if (isUndefined(classCondition)) { - classCondition = !jqLiteHasClass(element, className); - } - (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); - }); - } - }, - - parent: function(element) { - var parent = element.parentNode; - return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; - }, - - next: function(element) { - return element.nextElementSibling; - }, - - find: function(element, selector) { - if (element.getElementsByTagName) { - return element.getElementsByTagName(selector); - } else { - return []; - } - }, - - clone: jqLiteClone, - - triggerHandler: function(element, event, extraParameters) { - - var dummyEvent, eventFnsCopy, handlerArgs; - var eventName = event.type || event; - var expandoStore = jqLiteExpandoStore(element); - var events = expandoStore && expandoStore.events; - var eventFns = events && events[eventName]; - - if (eventFns) { - // Create a dummy event to pass to the handlers - dummyEvent = { - preventDefault: function() { this.defaultPrevented = true; }, - isDefaultPrevented: function() { return this.defaultPrevented === true; }, - stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, - isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, - stopPropagation: noop, - type: eventName, - target: element - }; + on: function jqLiteOn(element, type, fn, unsupported) { + if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); - // If a custom event was provided then extend our dummy event with it - if (event.type) { - dummyEvent = extend(dummyEvent, event); - } + // Do not add event handlers to non-elements because they will not be cleaned up. + if (!jqLiteAcceptsData(element)) { + return; + } + + var expandoStore = jqLiteExpandoStore(element, true); + var events = expandoStore.events; + var handle = expandoStore.handle; + + if (!handle) { + handle = expandoStore.handle = createEventHandler(element, events); + } + + // http://jsperf.com/string-indexof-vs-split + var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; + var i = types.length; + + while (i--) { + type = types[i]; + var eventFns = events[type]; + + if (!eventFns) { + events[type] = []; + + if (type === 'mouseenter' || type === 'mouseleave') { + // Refer to jQuery's implementation of mouseenter & mouseleave + // Read about mouseenter and mouseleave: + // http://www.quirksmode.org/js/events_mouse.html#link8 + + jqLiteOn(element, MOUSE_EVENT_MAP[type], function (event) { + var target = this, related = event.relatedTarget; + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if (!related || (related !== target && !target.contains(related))) { + handle(event, type); + } + }); + + } else { + if (type !== '$destroy') { + addEventListenerFn(element, type, handle); + } + } + eventFns = events[type]; + } + eventFns.push(fn); + } + }, + + off: jqLiteOff, + + one: function (element, type, fn) { + element = jqLite(element); + + //add the listener twice so that when it is called + //you can remove the original function and still be + //able to call element.off(ev, fn) normally + element.on(type, function onFn() { + element.off(type, fn); + element.off(type, onFn); + }); + element.on(type, fn); + }, + + replaceWith: function (element, replaceNode) { + var index, parent = element.parentNode; + jqLiteDealoc(element); + forEach(new JQLite(replaceNode), function (node) { + if (index) { + parent.insertBefore(node, index.nextSibling); + } else { + parent.replaceChild(node, element); + } + index = node; + }); + }, + + children: function (element) { + var children = []; + forEach(element.childNodes, function (element) { + if (element.nodeType === NODE_TYPE_ELEMENT) + children.push(element); + }); + return children; + }, + + contents: function (element) { + return element.contentDocument || element.childNodes || []; + }, + + append: function (element, node) { + var nodeType = element.nodeType; + if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; + + node = new JQLite(node); + + for (var i = 0, ii = node.length; i < ii; i++) { + var child = node[i]; + element.appendChild(child); + } + }, + + prepend: function (element, node) { + if (element.nodeType === NODE_TYPE_ELEMENT) { + var index = element.firstChild; + forEach(new JQLite(node), function (child) { + element.insertBefore(child, index); + }); + } + }, + + wrap: function (element, wrapNode) { + wrapNode = jqLite(wrapNode).eq(0).clone()[0]; + var parent = element.parentNode; + if (parent) { + parent.replaceChild(wrapNode, element); + } + wrapNode.appendChild(element); + }, + + remove: jqLiteRemove, + + detach: function (element) { + jqLiteRemove(element, true); + }, + + after: function (element, newElement) { + var index = element, parent = element.parentNode; + newElement = new JQLite(newElement); + + for (var i = 0, ii = newElement.length; i < ii; i++) { + var node = newElement[i]; + parent.insertBefore(node, index.nextSibling); + index = node; + } + }, + + addClass: jqLiteAddClass, + removeClass: jqLiteRemoveClass, + + toggleClass: function (element, selector, condition) { + if (selector) { + forEach(selector.split(' '), function (className) { + var classCondition = condition; + if (isUndefined(classCondition)) { + classCondition = !jqLiteHasClass(element, className); + } + (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); + }); + } + }, + + parent: function (element) { + var parent = element.parentNode; + return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; + }, + + next: function (element) { + return element.nextElementSibling; + }, + + find: function (element, selector) { + if (element.getElementsByTagName) { + return element.getElementsByTagName(selector); + } else { + return []; + } + }, + + clone: jqLiteClone, + + triggerHandler: function (element, event, extraParameters) { + + var dummyEvent, eventFnsCopy, handlerArgs; + var eventName = event.type || event; + var expandoStore = jqLiteExpandoStore(element); + var events = expandoStore && expandoStore.events; + var eventFns = events && events[eventName]; + + if (eventFns) { + // Create a dummy event to pass to the handlers + dummyEvent = { + preventDefault: function () { + this.defaultPrevented = true; + }, + isDefaultPrevented: function () { + return this.defaultPrevented === true; + }, + stopImmediatePropagation: function () { + this.immediatePropagationStopped = true; + }, + isImmediatePropagationStopped: function () { + return this.immediatePropagationStopped === true; + }, + stopPropagation: noop, + type: eventName, + target: element + }; + + // If a custom event was provided then extend our dummy event with it + if (event.type) { + dummyEvent = extend(dummyEvent, event); + } - // Copy event handlers in case event handlers array is modified during execution. - eventFnsCopy = shallowCopy(eventFns); - handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; + // Copy event handlers in case event handlers array is modified during execution. + eventFnsCopy = shallowCopy(eventFns); + handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; - forEach(eventFnsCopy, function(fn) { - if (!dummyEvent.isImmediatePropagationStopped()) { - fn.apply(element, handlerArgs); + forEach(eventFnsCopy, function (fn) { + if (!dummyEvent.isImmediatePropagationStopped()) { + fn.apply(element, handlerArgs); + } + }); + } } - }); - } - } -}, function(fn, name){ - /** - * chaining functions - */ - JQLite.prototype[name] = function(arg1, arg2, arg3) { - var value; - - for(var i = 0, ii = this.length; i < ii; i++) { - if (isUndefined(value)) { - value = fn(this[i], arg1, arg2, arg3); - if (isDefined(value)) { - // any function which returns a value needs to be wrapped - value = jqLite(value); + }, function (fn, name) { + /** + * chaining functions + */ + JQLite.prototype[name] = function (arg1, arg2, arg3) { + var value; + + for (var i = 0, ii = this.length; i < ii; i++) { + if (isUndefined(value)) { + value = fn(this[i], arg1, arg2, arg3); + if (isDefined(value)) { + // any function which returns a value needs to be wrapped + value = jqLite(value); + } + } else { + jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); + } + } + return isDefined(value) ? value : this; + }; + + // bind legacy bind/unbind to on/off + JQLite.prototype.bind = JQLite.prototype.on; + JQLite.prototype.unbind = JQLite.prototype.off; + }); + + /** + * Computes a hash of an 'obj'. + * Hash of a: + * string is string + * number is number as string + * object is either result of calling $$hashKey function on the object or uniquely generated id, + * that is also assigned to the $$hashKey property of the object. + * + * @param obj + * @returns {string} hash string such that the same input will have the same hash string. + * The resulting string key is in 'type:hashKey' format. + */ + function hashKey(obj, nextUidFn) { + var key = obj && obj.$$hashKey; + + if (key) { + if (typeof key === 'function') { + key = obj.$$hashKey(); + } + return key; } - } else { - jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); - } - } - return isDefined(value) ? value : this; - }; - // bind legacy bind/unbind to on/off - JQLite.prototype.bind = JQLite.prototype.on; - JQLite.prototype.unbind = JQLite.prototype.off; -}); + var objType = typeof obj; + if (objType == 'function' || (objType == 'object' && obj !== null)) { + key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); + } else { + key = objType + ':' + obj; + } -/** - * Computes a hash of an 'obj'. - * Hash of a: - * string is string - * number is number as string - * object is either result of calling $$hashKey function on the object or uniquely generated id, - * that is also assigned to the $$hashKey property of the object. - * - * @param obj - * @returns {string} hash string such that the same input will have the same hash string. - * The resulting string key is in 'type:hashKey' format. - */ -function hashKey(obj, nextUidFn) { - var key = obj && obj.$$hashKey; + return key; + } - if (key) { - if (typeof key === 'function') { - key = obj.$$hashKey(); + /** + * HashMap which can use objects as keys + */ + function HashMap(array, isolatedUid) { + if (isolatedUid) { + var uid = 0; + this.nextUid = function () { + return ++uid; + }; + } + forEach(array, this.put, this); } - return key; - } - var objType = typeof obj; - if (objType == 'function' || (objType == 'object' && obj !== null)) { - key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); - } else { - key = objType + ':' + obj; - } + HashMap.prototype = { + /** + * Store key value pair + * @param key key to store can be any type + * @param value value to store can be any type + */ + put: function (key, value) { + this[hashKey(key, this.nextUid)] = value; + }, - return key; -} + /** + * @param key + * @returns {Object} the value for the key + */ + get: function (key) { + return this[hashKey(key, this.nextUid)]; + }, -/** - * HashMap which can use objects as keys - */ -function HashMap(array, isolatedUid) { - if (isolatedUid) { - var uid = 0; - this.nextUid = function() { - return ++uid; + /** + * Remove the key/value pair + * @param key + */ + remove: function (key) { + var value = this[key = hashKey(key, this.nextUid)]; + delete this[key]; + return value; + } }; - } - forEach(array, this.put, this); -} -HashMap.prototype = { - /** - * Store key value pair - * @param key key to store can be any type - * @param value value to store can be any type - */ - put: function(key, value) { - this[hashKey(key, this.nextUid)] = value; - }, - - /** - * @param key - * @returns {Object} the value for the key - */ - get: function(key) { - return this[hashKey(key, this.nextUid)]; - }, - - /** - * Remove the key/value pair - * @param key - */ - remove: function(key) { - var value = this[key = hashKey(key, this.nextUid)]; - delete this[key]; - return value; - } -}; -/** - * @ngdoc function - * @module ng - * @name angular.injector - * @kind function - * - * @description - * Creates an injector object that can be used for retrieving services as well as for - * dependency injection (see {@link guide/di dependency injection}). - * + /** + * @ngdoc function + * @module ng + * @name angular.injector + * @kind function + * + * @description + * Creates an injector object that can be used for retrieving services as well as for + * dependency injection (see {@link guide/di dependency injection}). + * - * @param {Array.} modules A list of module functions or their aliases. See - * {@link angular.module}. The `ng` module must be explicitly added. - * @returns {injector} Injector object. See {@link auto.$injector $injector}. - * - * @example - * Typical usage - * ```js - * // create an injector - * var $injector = angular.injector(['ng']); - * - * // use the injector to kick off your application - * // use the type inference to auto inject arguments, or use implicit injection - * $injector.invoke(function($rootScope, $compile, $document) { + * @param {Array.} modules A list of module functions or their aliases. See + * {@link angular.module}. The `ng` module must be explicitly added. + * @returns {injector} Injector object. See {@link auto.$injector $injector}. + * + * @example + * Typical usage + * ```js + * // create an injector + * var $injector = angular.injector(['ng']); + * + * // use the injector to kick off your application + * // use the type inference to auto inject arguments, or use implicit injection + * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); - * ``` - * - * Sometimes you want to get access to the injector of a currently running Angular app - * from outside Angular. Perhaps, you want to inject and compile some markup after the - * application has been bootstrapped. You can do this using the extra `injector()` added - * to JQuery/jqLite elements. See {@link angular.element}. - * - * *This is fairly rare but could be the case if a third party library is injecting the - * markup.* - * - * In the following example a new block of HTML containing a `ng-controller` - * directive is added to the end of the document body by JQuery. We then compile and link - * it into the current AngularJS scope. - * - * ```js - * var $div = $('
          {{content.label}}
          '); - * $(document.body).append($div); - * - * angular.element(document).injector().invoke(function($compile) { + * ``` + * + * Sometimes you want to get access to the injector of a currently running Angular app + * from outside Angular. Perhaps, you want to inject and compile some markup after the + * application has been bootstrapped. You can do this using the extra `injector()` added + * to JQuery/jqLite elements. See {@link angular.element}. + * + * *This is fairly rare but could be the case if a third party library is injecting the + * markup.* + * + * In the following example a new block of HTML containing a `ng-controller` + * directive is added to the end of the document body by JQuery. We then compile and link + * it into the current AngularJS scope. + * + * ```js + * var $div = $('
          {{content.label}}
          '); + * $(document.body).append($div); + * + * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); - * ``` - */ + * ``` + */ -/** - * @ngdoc module - * @name auto - * @description - * - * Implicit module which gets automatically added to each {@link auto.$injector $injector}. - */ + /** + * @ngdoc module + * @name auto + * @description + * + * Implicit module which gets automatically added to each {@link auto.$injector $injector}. + */ -var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; -var $injectorMinErr = minErr('$injector'); - -function anonFn(fn) { - // For anonymous functions, showing at the very least the function signature can help in - // debugging. - var fnText = fn.toString().replace(STRIP_COMMENTS, ''), - args = fnText.match(FN_ARGS); - if (args) { - return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; - } - return 'fn'; -} - -function annotate(fn, strictDi, name) { - var $inject, - fnText, - argDecl, - last; - - if (typeof fn === 'function') { - if (!($inject = fn.$inject)) { - $inject = []; - if (fn.length) { - if (strictDi) { - if (!isString(name) || !name) { - name = fn.name || anonFn(fn); - } - throw $injectorMinErr('strictdi', - '{0} is not using explicit annotation and cannot be invoked in strict mode', name); + var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + var $injectorMinErr = minErr('$injector'); + + function anonFn(fn) { + // For anonymous functions, showing at the very least the function signature can help in + // debugging. + var fnText = fn.toString().replace(STRIP_COMMENTS, ''), + args = fnText.match(FN_ARGS); + if (args) { + return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } - fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_ARGS); - forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { - arg.replace(FN_ARG, function(all, underscore, name) { - $inject.push(name); - }); - }); - } - fn.$inject = $inject; + return 'fn'; + } + + function annotate(fn, strictDi, name) { + var $inject, + fnText, + argDecl, + last; + + if (typeof fn === 'function') { + if (!($inject = fn.$inject)) { + $inject = []; + if (fn.length) { + if (strictDi) { + if (!isString(name) || !name) { + name = fn.name || anonFn(fn); + } + throw $injectorMinErr('strictdi', + '{0} is not using explicit annotation and cannot be invoked in strict mode', name); + } + fnText = fn.toString().replace(STRIP_COMMENTS, ''); + argDecl = fnText.match(FN_ARGS); + forEach(argDecl[1].split(FN_ARG_SPLIT), function (arg) { + arg.replace(FN_ARG, function (all, underscore, name) { + $inject.push(name); + }); + }); + } + fn.$inject = $inject; + } + } else if (isArray(fn)) { + last = fn.length - 1; + assertArgFn(fn[last], 'fn'); + $inject = fn.slice(0, last); + } else { + assertArgFn(fn, 'fn', true); + } + return $inject; } - } else if (isArray(fn)) { - last = fn.length - 1; - assertArgFn(fn[last], 'fn'); - $inject = fn.slice(0, last); - } else { - assertArgFn(fn, 'fn', true); - } - return $inject; -} /////////////////////////////////////// -/** - * @ngdoc service - * @name $injector - * - * @description - * - * `$injector` is used to retrieve object instances as defined by - * {@link auto.$provide provider}, instantiate types, invoke methods, - * and load modules. - * - * The following always holds true: - * - * ```js - * var $injector = angular.injector(); - * expect($injector.get('$injector')).toBe($injector); - * expect($injector.invoke(function($injector) { + /** + * @ngdoc service + * @name $injector + * + * @description + * + * `$injector` is used to retrieve object instances as defined by + * {@link auto.$provide provider}, instantiate types, invoke methods, + * and load modules. + * + * The following always holds true: + * + * ```js + * var $injector = angular.injector(); + * expect($injector.get('$injector')).toBe($injector); + * expect($injector.invoke(function($injector) { * return $injector; * })).toBe($injector); - * ``` - * - * # Injection Function Annotation - * - * JavaScript does not have annotations, and annotations are needed for dependency injection. The - * following are all valid ways of annotating function with injection arguments and are equivalent. - * - * ```js - * // inferred (only works if code not minified/obfuscated) - * $injector.invoke(function(serviceA){}); - * - * // annotated - * function explicit(serviceA) {}; - * explicit.$inject = ['serviceA']; - * $injector.invoke(explicit); - * - * // inline - * $injector.invoke(['serviceA', function(serviceA){}]); - * ``` - * - * ## Inference - * - * In JavaScript calling `toString()` on a function returns the function definition. The definition - * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with - * minification, and obfuscation tools since these tools change the argument names. - * - * ## `$inject` Annotation - * By adding an `$inject` property onto a function the injection parameters can be specified. - * - * ## Inline - * As an array of injection names, where the last item in the array is the function to call. - */ - -/** - * @ngdoc method - * @name $injector#get - * - * @description - * Return an instance of the service. - * - * @param {string} name The name of the instance to retrieve. - * @return {*} The instance. - */ - -/** - * @ngdoc method - * @name $injector#invoke - * - * @description - * Invoke the method and supply the method arguments from the `$injector`. - * - * @param {!Function} fn The function to invoke. Function parameters are injected according to the - * {@link guide/di $inject Annotation} rules. - * @param {Object=} self The `this` for the invoked method. - * @param {Object=} locals Optional object. If preset then any argument names are read from this - * object first, before the `$injector` is consulted. - * @returns {*} the value returned by the invoked `fn` function. - */ + * ``` + * + * # Injection Function Annotation + * + * JavaScript does not have annotations, and annotations are needed for dependency injection. The + * following are all valid ways of annotating function with injection arguments and are equivalent. + * + * ```js + * // inferred (only works if code not minified/obfuscated) + * $injector.invoke(function(serviceA){}); + * + * // annotated + * function explicit(serviceA) {}; + * explicit.$inject = ['serviceA']; + * $injector.invoke(explicit); + * + * // inline + * $injector.invoke(['serviceA', function(serviceA){}]); + * ``` + * + * ## Inference + * + * In JavaScript calling `toString()` on a function returns the function definition. The definition + * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with + * minification, and obfuscation tools since these tools change the argument names. + * + * ## `$inject` Annotation + * By adding an `$inject` property onto a function the injection parameters can be specified. + * + * ## Inline + * As an array of injection names, where the last item in the array is the function to call. + */ -/** - * @ngdoc method - * @name $injector#has - * - * @description - * Allows the user to query if the particular service exists. - * - * @param {string} name Name of the service to query. - * @returns {boolean} `true` if injector has given service. - */ + /** + * @ngdoc method + * @name $injector#get + * + * @description + * Return an instance of the service. + * + * @param {string} name The name of the instance to retrieve. + * @return {*} The instance. + */ -/** - * @ngdoc method - * @name $injector#instantiate - * @description - * Create a new instance of JS type. The method takes a constructor function, invokes the new - * operator, and supplies all of the arguments to the constructor function as specified by the - * constructor annotation. - * - * @param {Function} Type Annotated constructor function. - * @param {Object=} locals Optional object. If preset then any argument names are read from this - * object first, before the `$injector` is consulted. - * @returns {Object} new instance of `Type`. - */ + /** + * @ngdoc method + * @name $injector#invoke + * + * @description + * Invoke the method and supply the method arguments from the `$injector`. + * + * @param {!Function} fn The function to invoke. Function parameters are injected according to the + * {@link guide/di $inject Annotation} rules. + * @param {Object=} self The `this` for the invoked method. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. + * @returns {*} the value returned by the invoked `fn` function. + */ -/** - * @ngdoc method - * @name $injector#annotate - * - * @description - * Returns an array of service names which the function is requesting for injection. This API is - * used by the injector to determine which services need to be injected into the function when the - * function is invoked. There are three ways in which the function can be annotated with the needed - * dependencies. - * - * # Argument names - * - * The simplest form is to extract the dependencies from the arguments of the function. This is done - * by converting the function into a string using `toString()` method and extracting the argument - * names. - * ```js - * // Given - * function MyController($scope, $route) { + /** + * @ngdoc method + * @name $injector#has + * + * @description + * Allows the user to query if the particular service exists. + * + * @param {string} name Name of the service to query. + * @returns {boolean} `true` if injector has given service. + */ + + /** + * @ngdoc method + * @name $injector#instantiate + * @description + * Create a new instance of JS type. The method takes a constructor function, invokes the new + * operator, and supplies all of the arguments to the constructor function as specified by the + * constructor annotation. + * + * @param {Function} Type Annotated constructor function. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. + * @returns {Object} new instance of `Type`. + */ + + /** + * @ngdoc method + * @name $injector#annotate + * + * @description + * Returns an array of service names which the function is requesting for injection. This API is + * used by the injector to determine which services need to be injected into the function when the + * function is invoked. There are three ways in which the function can be annotated with the needed + * dependencies. + * + * # Argument names + * + * The simplest form is to extract the dependencies from the arguments of the function. This is done + * by converting the function into a string using `toString()` method and extracting the argument + * names. + * ```js + * // Given + * function MyController($scope, $route) { * // ... * } - * - * // Then - * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); - * ``` - * - * This method does not work with code minification / obfuscation. For this reason the following - * annotation strategies are supported. - * - * # The `$inject` property - * - * If a function has an `$inject` property and its value is an array of strings, then the strings - * represent names of services to be injected into the function. - * ```js - * // Given - * var MyController = function(obfuscatedScope, obfuscatedRoute) { + * + * // Then + * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); + * ``` + * + * This method does not work with code minification / obfuscation. For this reason the following + * annotation strategies are supported. + * + * # The `$inject` property + * + * If a function has an `$inject` property and its value is an array of strings, then the strings + * represent names of services to be injected into the function. + * ```js + * // Given + * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } - * // Define function dependencies - * MyController['$inject'] = ['$scope', '$route']; - * - * // Then - * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); - * ``` - * - * # The array notation - * - * It is often desirable to inline Injected functions and that's when setting the `$inject` property - * is very inconvenient. In these situations using the array notation to specify the dependencies in - * a way that survives minification is a better choice: - * - * ```js - * // We wish to write this (not minification / obfuscation safe) - * injector.invoke(function($compile, $rootScope) { + * // Define function dependencies + * MyController['$inject'] = ['$scope', '$route']; + * + * // Then + * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); + * ``` + * + * # The array notation + * + * It is often desirable to inline Injected functions and that's when setting the `$inject` property + * is very inconvenient. In these situations using the array notation to specify the dependencies in + * a way that survives minification is a better choice: + * + * ```js + * // We wish to write this (not minification / obfuscation safe) + * injector.invoke(function($compile, $rootScope) { * // ... * }); - * - * // We are forced to write break inlining - * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { + * + * // We are forced to write break inlining + * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; - * tmpFn.$inject = ['$compile', '$rootScope']; - * injector.invoke(tmpFn); - * - * // To better support inline function the inline annotation is supported - * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { + * tmpFn.$inject = ['$compile', '$rootScope']; + * injector.invoke(tmpFn); + * + * // To better support inline function the inline annotation is supported + * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); - * - * // Therefore - * expect(injector.annotate( - * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) - * ).toEqual(['$compile', '$rootScope']); - * ``` - * - * @param {Function|Array.} fn Function for which dependent service names need to - * be retrieved as described above. - * - * @returns {Array.} The names of the services which the function requires. - */ - - + * + * // Therefore + * expect(injector.annotate( + * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) + * ).toEqual(['$compile', '$rootScope']); + * ``` + * + * @param {Function|Array.} fn Function for which dependent service names need to + * be retrieved as described above. + * + * @returns {Array.} The names of the services which the function requires. + */ -/** - * @ngdoc service - * @name $provide - * - * @description - * - * The {@link auto.$provide $provide} service has a number of methods for registering components - * with the {@link auto.$injector $injector}. Many of these functions are also exposed on - * {@link angular.Module}. - * - * An Angular **service** is a singleton object created by a **service factory**. These **service - * factories** are functions which, in turn, are created by a **service provider**. - * The **service providers** are constructor functions. When instantiated they must contain a - * property called `$get`, which holds the **service factory** function. - * - * When you request a service, the {@link auto.$injector $injector} is responsible for finding the - * correct **service provider**, instantiating it and then calling its `$get` **service factory** - * function to get the instance of the **service**. - * - * Often services have no configuration options and there is no need to add methods to the service - * provider. The provider will be no more than a constructor function with a `$get` property. For - * these cases the {@link auto.$provide $provide} service has additional helper methods to register - * services without specifying a provider. - * - * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the - * {@link auto.$injector $injector} - * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by - * providers and services. - * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by - * services, not providers. - * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, - * that will be wrapped in a **service provider** object, whose `$get` property will contain the - * given factory function. - * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` - * that will be wrapped in a **service provider** object, whose `$get` property will instantiate - * a new object using the given constructor function. - * - * See the individual methods for more information and examples. - */ + /** + * @ngdoc service + * @name $provide + * + * @description + * + * The {@link auto.$provide $provide} service has a number of methods for registering components + * with the {@link auto.$injector $injector}. Many of these functions are also exposed on + * {@link angular.Module}. + * + * An Angular **service** is a singleton object created by a **service factory**. These **service + * factories** are functions which, in turn, are created by a **service provider**. + * The **service providers** are constructor functions. When instantiated they must contain a + * property called `$get`, which holds the **service factory** function. + * + * When you request a service, the {@link auto.$injector $injector} is responsible for finding the + * correct **service provider**, instantiating it and then calling its `$get` **service factory** + * function to get the instance of the **service**. + * + * Often services have no configuration options and there is no need to add methods to the service + * provider. The provider will be no more than a constructor function with a `$get` property. For + * these cases the {@link auto.$provide $provide} service has additional helper methods to register + * services without specifying a provider. + * + * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the + * {@link auto.$injector $injector} + * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by + * providers and services. + * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by + * services, not providers. + * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, + * that will be wrapped in a **service provider** object, whose `$get` property will contain the + * given factory function. + * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` + * that will be wrapped in a **service provider** object, whose `$get` property will instantiate + * a new object using the given constructor function. + * + * See the individual methods for more information and examples. + */ -/** - * @ngdoc method - * @name $provide#provider - * @description - * - * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions - * are constructor functions, whose instances are responsible for "providing" a factory for a - * service. - * - * Service provider names start with the name of the service they provide followed by `Provider`. - * For example, the {@link ng.$log $log} service has a provider called - * {@link ng.$logProvider $logProvider}. - * - * Service provider objects can have additional methods which allow configuration of the provider - * and its service. Importantly, you can configure what kind of service is created by the `$get` - * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a - * method {@link ng.$logProvider#debugEnabled debugEnabled} - * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the - * console or not. - * - * @param {string} name The name of the instance. NOTE: the provider will be available under `name + - 'Provider'` key. - * @param {(Object|function())} provider If the provider is: - * - * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using - * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. - * - `Constructor`: a new instance of the provider will be created using - * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. - * - * @returns {Object} registered provider instance + /** + * @ngdoc method + * @name $provide#provider + * @description + * + * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions + * are constructor functions, whose instances are responsible for "providing" a factory for a + * service. + * + * Service provider names start with the name of the service they provide followed by `Provider`. + * For example, the {@link ng.$log $log} service has a provider called + * {@link ng.$logProvider $logProvider}. + * + * Service provider objects can have additional methods which allow configuration of the provider + * and its service. Importantly, you can configure what kind of service is created by the `$get` + * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a + * method {@link ng.$logProvider#debugEnabled debugEnabled} + * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the + * console or not. + * + * @param {string} name The name of the instance. NOTE: the provider will be available under `name + + 'Provider'` key. + * @param {(Object|function())} provider If the provider is: + * + * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using + * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. + * - `Constructor`: a new instance of the provider will be created using + * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. + * + * @returns {Object} registered provider instance - * @example - * - * The following example shows how to create a simple event tracking service and register it using - * {@link auto.$provide#provider $provide.provider()}. - * - * ```js - * // Define the eventTracker provider - * function EventTrackerProvider() { + * @example + * + * The following example shows how to create a simple event tracking service and register it using + * {@link auto.$provide#provider $provide.provider()}. + * + * ```js + * // Define the eventTracker provider + * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved @@ -3744,8 +3789,8 @@ function annotate(fn, strictDi, name) { * }; * }]; * } - * - * describe('eventTracker', function() { + * + * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { @@ -3773,493 +3818,498 @@ function annotate(fn, strictDi, name) { * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); - * ``` - */ + * ``` + */ -/** - * @ngdoc method - * @name $provide#factory - * @description - * - * Register a **service factory**, which will be called to return the service instance. - * This is short for registering a service where its provider consists of only a `$get` property, - * which is the given service factory function. - * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to - * configure your service in a provider. - * - * @param {string} name The name of the instance. - * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand - * for `$provide.provider(name, {$get: $getFn})`. - * @returns {Object} registered provider instance - * - * @example - * Here is an example of registering a service - * ```js - * $provide.factory('ping', ['$http', function($http) { + /** + * @ngdoc method + * @name $provide#factory + * @description + * + * Register a **service factory**, which will be called to return the service instance. + * This is short for registering a service where its provider consists of only a `$get` property, + * which is the given service factory function. + * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to + * configure your service in a provider. + * + * @param {string} name The name of the instance. + * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand + * for `$provide.provider(name, {$get: $getFn})`. + * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service + * ```js + * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); - * ``` - * You would then inject and use this service like this: - * ```js - * someModule.controller('Ctrl', ['ping', function(ping) { + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); - * ``` - */ + * ``` + */ -/** - * @ngdoc method - * @name $provide#service - * @description - * - * Register a **service constructor**, which will be invoked with `new` to create the service - * instance. - * This is short for registering a service where its provider's `$get` property is the service - * constructor function that will be used to instantiate the service instance. - * - * You should use {@link auto.$provide#service $provide.service(class)} if you define your service - * as a type/class. - * - * @param {string} name The name of the instance. - * @param {Function} constructor A class (constructor function) that will be instantiated. - * @returns {Object} registered provider instance - * - * @example - * Here is an example of registering a service using - * {@link auto.$provide#service $provide.service(class)}. - * ```js - * var Ping = function($http) { + /** + * @ngdoc method + * @name $provide#service + * @description + * + * Register a **service constructor**, which will be invoked with `new` to create the service + * instance. + * This is short for registering a service where its provider's `$get` property is the service + * constructor function that will be used to instantiate the service instance. + * + * You should use {@link auto.$provide#service $provide.service(class)} if you define your service + * as a type/class. + * + * @param {string} name The name of the instance. + * @param {Function} constructor A class (constructor function) that will be instantiated. + * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service using + * {@link auto.$provide#service $provide.service(class)}. + * ```js + * var Ping = function($http) { * this.$http = $http; * }; - * - * Ping.$inject = ['$http']; - * - * Ping.prototype.send = function() { + * + * Ping.$inject = ['$http']; + * + * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; - * $provide.service('ping', Ping); - * ``` - * You would then inject and use this service like this: - * ```js - * someModule.controller('Ctrl', ['ping', function(ping) { + * $provide.service('ping', Ping); + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); - * ``` - */ + * ``` + */ -/** - * @ngdoc method - * @name $provide#value - * @description - * - * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a - * number, an array, an object or a function. This is short for registering a service where its - * provider's `$get` property is a factory function that takes no arguments and returns the **value - * service**. - * - * Value services are similar to constant services, except that they cannot be injected into a - * module configuration function (see {@link angular.Module#config}) but they can be overridden by - * an Angular - * {@link auto.$provide#decorator decorator}. - * - * @param {string} name The name of the instance. - * @param {*} value The value. - * @returns {Object} registered provider instance - * - * @example - * Here are some examples of creating value services. - * ```js - * $provide.value('ADMIN_USER', 'admin'); - * - * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); - * - * $provide.value('halfOf', function(value) { + /** + * @ngdoc method + * @name $provide#value + * @description + * + * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a + * number, an array, an object or a function. This is short for registering a service where its + * provider's `$get` property is a factory function that takes no arguments and returns the **value + * service**. + * + * Value services are similar to constant services, except that they cannot be injected into a + * module configuration function (see {@link angular.Module#config}) but they can be overridden by + * an Angular + * {@link auto.$provide#decorator decorator}. + * + * @param {string} name The name of the instance. + * @param {*} value The value. + * @returns {Object} registered provider instance + * + * @example + * Here are some examples of creating value services. + * ```js + * $provide.value('ADMIN_USER', 'admin'); + * + * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); + * + * $provide.value('halfOf', function(value) { * return value / 2; * }); - * ``` - */ + * ``` + */ -/** - * @ngdoc method - * @name $provide#constant - * @description - * - * Register a **constant service**, such as a string, a number, an array, an object or a function, - * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be - * injected into a module configuration function (see {@link angular.Module#config}) and it cannot - * be overridden by an Angular {@link auto.$provide#decorator decorator}. - * - * @param {string} name The name of the constant. - * @param {*} value The constant value. - * @returns {Object} registered instance - * - * @example - * Here a some examples of creating constants: - * ```js - * $provide.constant('SHARD_HEIGHT', 306); - * - * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); - * - * $provide.constant('double', function(value) { + /** + * @ngdoc method + * @name $provide#constant + * @description + * + * Register a **constant service**, such as a string, a number, an array, an object or a function, + * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be + * injected into a module configuration function (see {@link angular.Module#config}) and it cannot + * be overridden by an Angular {@link auto.$provide#decorator decorator}. + * + * @param {string} name The name of the constant. + * @param {*} value The constant value. + * @returns {Object} registered instance + * + * @example + * Here a some examples of creating constants: + * ```js + * $provide.constant('SHARD_HEIGHT', 306); + * + * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); + * + * $provide.constant('double', function(value) { * return value * 2; * }); - * ``` - */ + * ``` + */ -/** - * @ngdoc method - * @name $provide#decorator - * @description - * - * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator - * intercepts the creation of a service, allowing it to override or modify the behaviour of the - * service. The object returned by the decorator may be the original service, or a new service - * object which replaces or wraps and delegates to the original service. - * - * @param {string} name The name of the service to decorate. - * @param {function()} decorator This function will be invoked when the service needs to be - * instantiated and should return the decorated service instance. The function is called using - * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. - * Local injection arguments: - * - * * `$delegate` - The original service instance, which can be monkey patched, configured, - * decorated or delegated to. - * - * @example - * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting - * calls to {@link ng.$log#error $log.warn()}. - * ```js - * $provide.decorator('$log', ['$delegate', function($delegate) { + /** + * @ngdoc method + * @name $provide#decorator + * @description + * + * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator + * intercepts the creation of a service, allowing it to override or modify the behaviour of the + * service. The object returned by the decorator may be the original service, or a new service + * object which replaces or wraps and delegates to the original service. + * + * @param {string} name The name of the service to decorate. + * @param {function()} decorator This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. The function is called using + * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. + * Local injection arguments: + * + * * `$delegate` - The original service instance, which can be monkey patched, configured, + * decorated or delegated to. + * + * @example + * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting + * calls to {@link ng.$log#error $log.warn()}. + * ```js + * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); - * ``` - */ - - -function createInjector(modulesToLoad, strictDi) { - strictDi = (strictDi === true); - var INSTANTIATING = {}, - providerSuffix = 'Provider', - path = [], - loadedModules = new HashMap([], true), - providerCache = { - $provide: { - provider: supportObject(provider), - factory: supportObject(factory), - service: supportObject(service), - value: supportObject(value), - constant: supportObject(constant), - decorator: decorator - } - }, - providerInjector = (providerCache.$injector = - createInternalInjector(providerCache, function() { - throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); - })), - instanceCache = {}, - instanceInjector = (instanceCache.$injector = - createInternalInjector(instanceCache, function(servicename) { - var provider = providerInjector.get(servicename + providerSuffix); - return instanceInjector.invoke(provider.$get, provider, undefined, servicename); - })); - - - forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); - - return instanceInjector; - - //////////////////////////////////// - // $provider - //////////////////////////////////// - - function supportObject(delegate) { - return function(key, value) { - if (isObject(key)) { - forEach(key, reverseParams(delegate)); - } else { - return delegate(key, value); - } - }; - } - - function provider(name, provider_) { - assertNotHasOwnProperty(name, 'service'); - if (isFunction(provider_) || isArray(provider_)) { - provider_ = providerInjector.instantiate(provider_); - } - if (!provider_.$get) { - throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); - } - return providerCache[name + providerSuffix] = provider_; - } - - function enforceReturnValue(name, factory) { - return function enforcedReturnValue() { - var result = instanceInjector.invoke(factory, this, undefined, name); - if (isUndefined(result)) { - throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); - } - return result; - }; - } - - function factory(name, factoryFn, enforce) { - return provider(name, { - $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn - }); - } + * ``` + */ - function service(name, constructor) { - return factory(name, ['$injector', function($injector) { - return $injector.instantiate(constructor); - }]); - } - function value(name, val) { return factory(name, valueFn(val), false); } + function createInjector(modulesToLoad, strictDi) { + strictDi = (strictDi === true); + var INSTANTIATING = {}, + providerSuffix = 'Provider', + path = [], + loadedModules = new HashMap([], true), + providerCache = { + $provide: { + provider: supportObject(provider), + factory: supportObject(factory), + service: supportObject(service), + value: supportObject(value), + constant: supportObject(constant), + decorator: decorator + } + }, + providerInjector = (providerCache.$injector = + createInternalInjector(providerCache, function () { + throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + })), + instanceCache = {}, + instanceInjector = (instanceCache.$injector = + createInternalInjector(instanceCache, function (servicename) { + var provider = providerInjector.get(servicename + providerSuffix); + return instanceInjector.invoke(provider.$get, provider, undefined, servicename); + })); + + + forEach(loadModules(modulesToLoad), function (fn) { + instanceInjector.invoke(fn || noop); + }); - function constant(name, value) { - assertNotHasOwnProperty(name, 'constant'); - providerCache[name] = value; - instanceCache[name] = value; - } + return instanceInjector; - function decorator(serviceName, decorFn) { - var origProvider = providerInjector.get(serviceName + providerSuffix), - orig$get = origProvider.$get; + //////////////////////////////////// + // $provider + //////////////////////////////////// - origProvider.$get = function() { - var origInstance = instanceInjector.invoke(orig$get, origProvider); - return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); - }; - } - - //////////////////////////////////// - // Module Loading - //////////////////////////////////// - function loadModules(modulesToLoad){ - var runBlocks = [], moduleFn; - forEach(modulesToLoad, function(module) { - if (loadedModules.get(module)) return; - loadedModules.put(module, true); - - function runInvokeQueue(queue) { - var i, ii; - for(i = 0, ii = queue.length; i < ii; i++) { - var invokeArgs = queue[i], - provider = providerInjector.get(invokeArgs[0]); - - provider[invokeArgs[1]].apply(provider, invokeArgs[2]); + function supportObject(delegate) { + return function (key, value) { + if (isObject(key)) { + forEach(key, reverseParams(delegate)); + } else { + return delegate(key, value); + } + }; } - } - try { - if (isString(module)) { - moduleFn = angularModule(module); - runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - runInvokeQueue(moduleFn._invokeQueue); - runInvokeQueue(moduleFn._configBlocks); - } else if (isFunction(module)) { - runBlocks.push(providerInjector.invoke(module)); - } else if (isArray(module)) { - runBlocks.push(providerInjector.invoke(module)); - } else { - assertArgFn(module, 'module'); - } - } catch (e) { - if (isArray(module)) { - module = module[module.length - 1]; + function provider(name, provider_) { + assertNotHasOwnProperty(name, 'service'); + if (isFunction(provider_) || isArray(provider_)) { + provider_ = providerInjector.instantiate(provider_); + } + if (!provider_.$get) { + throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); + } + return providerCache[name + providerSuffix] = provider_; } - if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { - // Safari & FF's stack traces don't contain error.message content - // unlike those of Chrome and IE - // So if stack doesn't contain message, we create a new string that contains both. - // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. - /* jshint -W022 */ - e = e.message + '\n' + e.stack; + + function enforceReturnValue(name, factory) { + return function enforcedReturnValue() { + var result = instanceInjector.invoke(factory, this, undefined, name); + if (isUndefined(result)) { + throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); + } + return result; + }; } - throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", - module, e.stack || e.message || e); - } - }); - return runBlocks; - } - //////////////////////////////////// - // internal Injector - //////////////////////////////////// + function factory(name, factoryFn, enforce) { + return provider(name, { + $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn + }); + } - function createInternalInjector(cache, factory) { + function service(name, constructor) { + return factory(name, ['$injector', function ($injector) { + return $injector.instantiate(constructor); + }]); + } - function getService(serviceName) { - if (cache.hasOwnProperty(serviceName)) { - if (cache[serviceName] === INSTANTIATING) { - throw $injectorMinErr('cdep', 'Circular dependency found: {0}', - serviceName + ' <- ' + path.join(' <- ')); + function value(name, val) { + return factory(name, valueFn(val), false); } - return cache[serviceName]; - } else { - try { - path.unshift(serviceName); - cache[serviceName] = INSTANTIATING; - return cache[serviceName] = factory(serviceName); - } catch (err) { - if (cache[serviceName] === INSTANTIATING) { - delete cache[serviceName]; - } - throw err; - } finally { - path.shift(); + + function constant(name, value) { + assertNotHasOwnProperty(name, 'constant'); + providerCache[name] = value; + instanceCache[name] = value; } - } - } - function invoke(fn, self, locals, serviceName) { - if (typeof locals === 'string') { - serviceName = locals; - locals = null; - } + function decorator(serviceName, decorFn) { + var origProvider = providerInjector.get(serviceName + providerSuffix), + orig$get = origProvider.$get; + + origProvider.$get = function () { + var origInstance = instanceInjector.invoke(orig$get, origProvider); + return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); + }; + } - var args = [], - $inject = annotate(fn, strictDi, serviceName), - length, i, - key; + //////////////////////////////////// + // Module Loading + //////////////////////////////////// + function loadModules(modulesToLoad) { + var runBlocks = [], moduleFn; + forEach(modulesToLoad, function (module) { + if (loadedModules.get(module)) return; + loadedModules.put(module, true); + + function runInvokeQueue(queue) { + var i, ii; + for (i = 0, ii = queue.length; i < ii; i++) { + var invokeArgs = queue[i], + provider = providerInjector.get(invokeArgs[0]); + + provider[invokeArgs[1]].apply(provider, invokeArgs[2]); + } + } - for(i = 0, length = $inject.length; i < length; i++) { - key = $inject[i]; - if (typeof key !== 'string') { - throw $injectorMinErr('itkn', - 'Incorrect injection token! Expected service name as string, got {0}', key); + try { + if (isString(module)) { + moduleFn = angularModule(module); + runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); + runInvokeQueue(moduleFn._invokeQueue); + runInvokeQueue(moduleFn._configBlocks); + } else if (isFunction(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else if (isArray(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else { + assertArgFn(module, 'module'); + } + } catch (e) { + if (isArray(module)) { + module = module[module.length - 1]; + } + if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + // Safari & FF's stack traces don't contain error.message content + // unlike those of Chrome and IE + // So if stack doesn't contain message, we create a new string that contains both. + // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. + /* jshint -W022 */ + e = e.message + '\n' + e.stack; + } + throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", + module, e.stack || e.message || e); + } + }); + return runBlocks; } - args.push( - locals && locals.hasOwnProperty(key) - ? locals[key] - : getService(key) - ); - } - if (isArray(fn)) { - fn = fn[length]; - } - // http://jsperf.com/angularjs-invoke-apply-vs-switch - // #5388 - return fn.apply(self, args); - } + //////////////////////////////////// + // internal Injector + //////////////////////////////////// + + function createInternalInjector(cache, factory) { + + function getService(serviceName) { + if (cache.hasOwnProperty(serviceName)) { + if (cache[serviceName] === INSTANTIATING) { + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', + serviceName + ' <- ' + path.join(' <- ')); + } + return cache[serviceName]; + } else { + try { + path.unshift(serviceName); + cache[serviceName] = INSTANTIATING; + return cache[serviceName] = factory(serviceName); + } catch (err) { + if (cache[serviceName] === INSTANTIATING) { + delete cache[serviceName]; + } + throw err; + } finally { + path.shift(); + } + } + } + + function invoke(fn, self, locals, serviceName) { + if (typeof locals === 'string') { + serviceName = locals; + locals = null; + } + + var args = [], + $inject = annotate(fn, strictDi, serviceName), + length, i, + key; + + for (i = 0, length = $inject.length; i < length; i++) { + key = $inject[i]; + if (typeof key !== 'string') { + throw $injectorMinErr('itkn', + 'Incorrect injection token! Expected service name as string, got {0}', key); + } + args.push( + locals && locals.hasOwnProperty(key) + ? locals[key] + : getService(key) + ); + } + if (isArray(fn)) { + fn = fn[length]; + } + + // http://jsperf.com/angularjs-invoke-apply-vs-switch + // #5388 + return fn.apply(self, args); + } + + function instantiate(Type, locals, serviceName) { + var Constructor = function () { + }, + instance, returnedValue; - function instantiate(Type, locals, serviceName) { - var Constructor = function() {}, - instance, returnedValue; + // Check if Type is annotated and use just the given function at n-1 as parameter + // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); + Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; + instance = new Constructor(); + returnedValue = invoke(Type, instance, locals, serviceName); - // Check if Type is annotated and use just the given function at n-1 as parameter - // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); - Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; - instance = new Constructor(); - returnedValue = invoke(Type, instance, locals, serviceName); + return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; + } - return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; + return { + invoke: invoke, + instantiate: instantiate, + get: getService, + annotate: annotate, + has: function (name) { + return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); + } + }; + } } - return { - invoke: invoke, - instantiate: instantiate, - get: getService, - annotate: annotate, - has: function(name) { - return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); - } - }; - } -} + createInjector.$$annotate = annotate; -createInjector.$$annotate = annotate; + /** + * @ngdoc provider + * @name $anchorScrollProvider + * + * @description + * Use `$anchorScrollProvider` to disable automatic scrolling whenever + * {@link ng.$location#hash $location.hash()} changes. + */ + function $AnchorScrollProvider() { -/** - * @ngdoc provider - * @name $anchorScrollProvider - * - * @description - * Use `$anchorScrollProvider` to disable automatic scrolling whenever - * {@link ng.$location#hash $location.hash()} changes. - */ -function $AnchorScrollProvider() { + var autoScrollingEnabled = true; - var autoScrollingEnabled = true; + /** + * @ngdoc method + * @name $anchorScrollProvider#disableAutoScrolling + * + * @description + * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically will detect changes to + * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
          + * Use this method to disable automatic scrolling. + * + * If automatic scrolling is disabled, one must explicitly call + * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the + * current hash. + */ + this.disableAutoScrolling = function () { + autoScrollingEnabled = false; + }; - /** - * @ngdoc method - * @name $anchorScrollProvider#disableAutoScrolling - * - * @description - * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically will detect changes to - * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
          - * Use this method to disable automatic scrolling. - * - * If automatic scrolling is disabled, one must explicitly call - * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the - * current hash. - */ - this.disableAutoScrolling = function() { - autoScrollingEnabled = false; - }; - - /** - * @ngdoc service - * @name $anchorScroll - * @kind function - * @requires $window - * @requires $location - * @requires $rootScope - * - * @description - * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and - * scrolls to the related element, according to the rules specified in the - * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). - * - * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to - * match any anchor whenever it changes. This can be disabled by calling - * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. - * - * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a - * vertical scroll-offset (either fixed or dynamic). - * - * @property {(number|function|jqLite)} yOffset - * If set, specifies a vertical scroll-offset. This is often useful when there are fixed - * positioned elements at the top of the page, such as navbars, headers etc. - * - * `yOffset` can be specified in various ways: - * - **number**: A fixed number of pixels to be used as offset.

          - * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return - * a number representing the offset (in pixels).

          - * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from - * the top of the page to the element's bottom will be used as offset.
          - * **Note**: The element will be taken into account only as long as its `position` is set to - * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust - * their height and/or positioning according to the viewport's size. - * - *
          - *
          - * In order for `yOffset` to work properly, scrolling should take place on the document's root and - * not some child element. - *
          - * - * @example - - + /** + * @ngdoc service + * @name $anchorScroll + * @kind function + * @requires $window + * @requires $location + * @requires $rootScope + * + * @description + * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and + * scrolls to the related element, according to the rules specified in the + * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). + * + * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to + * match any anchor whenever it changes. This can be disabled by calling + * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. + * + * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a + * vertical scroll-offset (either fixed or dynamic). + * + * @property {(number|function|jqLite)} yOffset + * If set, specifies a vertical scroll-offset. This is often useful when there are fixed + * positioned elements at the top of the page, such as navbars, headers etc. + * + * `yOffset` can be specified in various ways: + * - **number**: A fixed number of pixels to be used as offset.

          + * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return + * a number representing the offset (in pixels).

          + * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from + * the top of the page to the element's bottom will be used as offset.
          + * **Note**: The element will be taken into account only as long as its `position` is set to + * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust + * their height and/or positioning according to the viewport's size. + * + *
          + *
          + * In order for `yOffset` to work properly, scrolling should take place on the document's root and + * not some child element. + *
          + * + * @example + +
          - Go to bottom - You're at the bottom! + Go to bottom + You're at the bottom!
          -
          - + + angular.module('anchorScrollExample', []) - .controller('ScrollController', ['$scope', '$location', '$anchorScroll', - function ($scope, $location, $anchorScroll) { + .controller('ScrollController', ['$scope', '$location', '$anchorScroll', + function ($scope, $location, $anchorScroll) { $scope.gotoBottom = function() { // set the location.hash to the id of // the element you wish to scroll to. @@ -4269,8 +4319,8 @@ function $AnchorScrollProvider() { $anchorScroll(); }; }]); - - + + #scrollArea { height: 280px; overflow: auto; @@ -4280,32 +4330,32 @@ function $AnchorScrollProvider() { display: block; margin-top: 2000px; } - -
          - * - *
          - * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). - * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. - * - * @example - - + + + * + *
          + * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). + * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. + * + * @example + +
          - Anchor {{x}} of 5 + Anchor {{x}} of 5
          -
          - + + angular.module('anchorScrollOffsetExample', []) - .run(['$anchorScroll', function($anchorScroll) { + .run(['$anchorScroll', function($anchorScroll) { $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels }]) - .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', - function ($anchorScroll, $location, $scope) { + .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', + function ($anchorScroll, $location, $scope) { $scope.gotoAnchor = function(x) { var newHash = 'anchor' + x; if ($location.hash() !== newHash) { @@ -4319,9 +4369,9 @@ function $AnchorScrollProvider() { } }; } - ]); - - + ]); + + body { padding-top: 50px; } @@ -4342,148 +4392,150 @@ function $AnchorScrollProvider() { display: inline-block; margin: 5px 15px; } - -
          - */ - this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { - var document = $window.document; - var scrollScheduled = false; - - // Helper function to get first anchor from a NodeList - // (using `Array#some()` instead of `angular#forEach()` since it's more performant - // and working in all supported browsers.) - function getFirstAnchor(list) { - var result = null; - Array.prototype.some.call(list, function(element) { - if (nodeName_(element) === 'a') { - result = element; - return true; - } - }); - return result; - } +
          +
          + */ + this.$get = ['$window', '$location', '$rootScope', function ($window, $location, $rootScope) { + var document = $window.document; + var scrollScheduled = false; + + // Helper function to get first anchor from a NodeList + // (using `Array#some()` instead of `angular#forEach()` since it's more performant + // and working in all supported browsers.) + function getFirstAnchor(list) { + var result = null; + Array.prototype.some.call(list, function (element) { + if (nodeName_(element) === 'a') { + result = element; + return true; + } + }); + return result; + } - function getYOffset() { + function getYOffset() { - var offset = scroll.yOffset; + var offset = scroll.yOffset; - if (isFunction(offset)) { - offset = offset(); - } else if (isElement(offset)) { - var elem = offset[0]; - var style = $window.getComputedStyle(elem); - if (style.position !== 'fixed') { - offset = 0; - } else { - offset = elem.getBoundingClientRect().bottom; - } - } else if (!isNumber(offset)) { - offset = 0; - } + if (isFunction(offset)) { + offset = offset(); + } else if (isElement(offset)) { + var elem = offset[0]; + var style = $window.getComputedStyle(elem); + if (style.position !== 'fixed') { + offset = 0; + } else { + offset = elem.getBoundingClientRect().bottom; + } + } else if (!isNumber(offset)) { + offset = 0; + } - return offset; - } + return offset; + } - function scrollTo(elem) { - if (elem) { - elem.scrollIntoView(); - - var offset = getYOffset(); - - if (offset) { - // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. - // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the - // top of the viewport. - // - // IF the number of pixels from the top of `elem` to the end of the page's content is less - // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some - // way down the page. - // - // This is often the case for elements near the bottom of the page. - // - // In such cases we do not need to scroll the whole `offset` up, just the difference between - // the top of the element and the offset, which is enough to align the top of `elem` at the - // desired position. - var elemTop = elem.getBoundingClientRect().top; - $window.scrollBy(0, elemTop - offset); - } - } else { - $window.scrollTo(0, 0); - } - } + function scrollTo(elem) { + if (elem) { + elem.scrollIntoView(); + + var offset = getYOffset(); + + if (offset) { + // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. + // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the + // top of the viewport. + // + // IF the number of pixels from the top of `elem` to the end of the page's content is less + // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some + // way down the page. + // + // This is often the case for elements near the bottom of the page. + // + // In such cases we do not need to scroll the whole `offset` up, just the difference between + // the top of the element and the offset, which is enough to align the top of `elem` at the + // desired position. + var elemTop = elem.getBoundingClientRect().top; + $window.scrollBy(0, elemTop - offset); + } + } else { + $window.scrollTo(0, 0); + } + } - function scroll() { - var hash = $location.hash(), elm; + function scroll() { + var hash = $location.hash(), elm; - // empty hash, scroll to the top of the page - if (!hash) scrollTo(null); + // empty hash, scroll to the top of the page + if (!hash) scrollTo(null); - // element with given id - else if ((elm = document.getElementById(hash))) scrollTo(elm); + // element with given id + else if ((elm = document.getElementById(hash))) scrollTo(elm); - // first anchor with given name :-D - else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); + // first anchor with given name :-D + else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); - // no element and hash == 'top', scroll to the top of the page - else if (hash === 'top') scrollTo(null); - } + // no element and hash == 'top', scroll to the top of the page + else if (hash === 'top') scrollTo(null); + } - // does not scroll when user clicks on anchor link that is currently on - // (no url change, no $location.hash() change), browser native does scroll - if (autoScrollingEnabled) { - $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, - function autoScrollWatchAction(newVal, oldVal) { - // skip the initial scroll if $location.hash is empty - if (newVal === oldVal && newVal === '') return; + // does not scroll when user clicks on anchor link that is currently on + // (no url change, no $location.hash() change), browser native does scroll + if (autoScrollingEnabled) { + $rootScope.$watch(function autoScrollWatch() { + return $location.hash(); + }, + function autoScrollWatchAction(newVal, oldVal) { + // skip the initial scroll if $location.hash is empty + if (newVal === oldVal && newVal === '') return; + + jqLiteDocumentLoaded(function () { + $rootScope.$evalAsync(scroll); + }); + }); + } - jqLiteDocumentLoaded(function() { - $rootScope.$evalAsync(scroll); - }); - }); + return scroll; + }]; } - return scroll; - }]; -} - -var $animateMinErr = minErr('$animate'); + var $animateMinErr = minErr('$animate'); -/** - * @ngdoc provider - * @name $animateProvider - * - * @description - * Default implementation of $animate that doesn't perform any animations, instead just - * synchronously performs DOM - * updates and calls done() callbacks. - * - * In order to enable animations the ngAnimate module has to be loaded. - * - * To see the functional implementation check out src/ngAnimate/animate.js - */ -var $AnimateProvider = ['$provide', function($provide) { + /** + * @ngdoc provider + * @name $animateProvider + * + * @description + * Default implementation of $animate that doesn't perform any animations, instead just + * synchronously performs DOM + * updates and calls done() callbacks. + * + * In order to enable animations the ngAnimate module has to be loaded. + * + * To see the functional implementation check out src/ngAnimate/animate.js + */ + var $AnimateProvider = ['$provide', function ($provide) { - this.$$selectors = {}; + this.$$selectors = {}; - /** - * @ngdoc method - * @name $animateProvider#register - * - * @description - * Registers a new injectable animation factory function. The factory function produces the - * animation object which contains callback functions for each event that is expected to be - * animated. - * - * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` - * must be called once the element animation is complete. If a function is returned then the - * animation service will use this function to cancel the animation whenever a cancel event is - * triggered. - * - * - * ```js - * return { + /** + * @ngdoc method + * @name $animateProvider#register + * + * @description + * Registers a new injectable animation factory function. The factory function produces the + * animation object which contains callback functions for each event that is expected to be + * animated. + * + * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` + * must be called once the element animation is complete. If a function is returned then the + * animation service will use this function to cancel the animation whenever a cancel event is + * triggered. + * + * + * ```js + * return { * eventFn : function(element, done) { * //code to run the animation * //once complete, then run done() @@ -4492,861 +4544,870 @@ var $AnimateProvider = ['$provide', function($provide) { * } * } * } - * ``` - * - * @param {string} name The name of the animation. - * @param {Function} factory The factory function that will be executed to return the animation - * object. - */ - this.register = function(name, factory) { - var key = name + '-animation'; - if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', - "Expecting class selector starting with '.' got '{0}'.", name); - this.$$selectors[name.substr(1)] = key; - $provide.factory(key, factory); - }; - - /** - * @ngdoc method - * @name $animateProvider#classNameFilter - * - * @description - * Sets and/or returns the CSS class regular expression that is checked when performing - * an animation. Upon bootstrap the classNameFilter value is not set at all and will - * therefore enable $animate to attempt to perform an animation on any element. - * When setting the classNameFilter value, animations will only be performed on elements - * that successfully match the filter expression. This in turn can boost performance - * for low-powered devices as well as applications containing a lot of structural operations. - * @param {RegExp=} expression The className expression which will be checked against all animations - * @return {RegExp} The current CSS className expression value. If null then there is no expression value - */ - this.classNameFilter = function(expression) { - if(arguments.length === 1) { - this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; - } - return this.$$classNameFilter; - }; + * ``` + * + * @param {string} name The name of the animation. + * @param {Function} factory The factory function that will be executed to return the animation + * object. + */ + this.register = function (name, factory) { + var key = name + '-animation'; + if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', + "Expecting class selector starting with '.' got '{0}'.", name); + this.$$selectors[name.substr(1)] = key; + $provide.factory(key, factory); + }; - this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) { + /** + * @ngdoc method + * @name $animateProvider#classNameFilter + * + * @description + * Sets and/or returns the CSS class regular expression that is checked when performing + * an animation. Upon bootstrap the classNameFilter value is not set at all and will + * therefore enable $animate to attempt to perform an animation on any element. + * When setting the classNameFilter value, animations will only be performed on elements + * that successfully match the filter expression. This in turn can boost performance + * for low-powered devices as well as applications containing a lot of structural operations. + * @param {RegExp=} expression The className expression which will be checked against all animations + * @return {RegExp} The current CSS className expression value. If null then there is no expression value + */ + this.classNameFilter = function (expression) { + if (arguments.length === 1) { + this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; + } + return this.$$classNameFilter; + }; - var currentDefer; + this.$get = ['$$q', '$$asyncCallback', '$rootScope', function ($$q, $$asyncCallback, $rootScope) { - function runAnimationPostDigest(fn) { - var cancelFn, defer = $$q.defer(); - defer.promise.$$cancelFn = function ngAnimateMaybeCancel() { - cancelFn && cancelFn(); - }; + var currentDefer; - $rootScope.$$postDigest(function ngAnimatePostDigest() { - cancelFn = fn(function ngAnimateNotifyComplete() { - defer.resolve(); - }); - }); + function runAnimationPostDigest(fn) { + var cancelFn, defer = $$q.defer(); + defer.promise.$$cancelFn = function ngAnimateMaybeCancel() { + cancelFn && cancelFn(); + }; - return defer.promise; - } + $rootScope.$$postDigest(function ngAnimatePostDigest() { + cancelFn = fn(function ngAnimateNotifyComplete() { + defer.resolve(); + }); + }); - function resolveElementClasses(element, classes) { - var toAdd = [], toRemove = []; + return defer.promise; + } - var hasClasses = createMap(); - forEach((element.attr('class') || '').split(/\s+/), function(className) { - hasClasses[className] = true; - }); + function resolveElementClasses(element, classes) { + var toAdd = [], toRemove = []; - forEach(classes, function(status, className) { - var hasClass = hasClasses[className]; - - // If the most recent class manipulation (via $animate) was to remove the class, and the - // element currently has the class, the class is scheduled for removal. Otherwise, if - // the most recent class manipulation (via $animate) was to add the class, and the - // element does not currently have the class, the class is scheduled to be added. - if (status === false && hasClass) { - toRemove.push(className); - } else if (status === true && !hasClass) { - toAdd.push(className); - } - }); + var hasClasses = createMap(); + forEach((element.attr('class') || '').split(/\s+/), function (className) { + hasClasses[className] = true; + }); - return (toAdd.length + toRemove.length) > 0 && - [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null]; - } + forEach(classes, function (status, className) { + var hasClass = hasClasses[className]; + + // If the most recent class manipulation (via $animate) was to remove the class, and the + // element currently has the class, the class is scheduled for removal. Otherwise, if + // the most recent class manipulation (via $animate) was to add the class, and the + // element does not currently have the class, the class is scheduled to be added. + if (status === false && hasClass) { + toRemove.push(className); + } else if (status === true && !hasClass) { + toAdd.push(className); + } + }); - function cachedClassManipulation(cache, classes, op) { - for (var i=0, ii = classes.length; i < ii; ++i) { - var className = classes[i]; - cache[className] = op; - } - } + return (toAdd.length + toRemove.length) > 0 && + [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null]; + } - function asyncPromise() { - // only serve one instance of a promise in order to save CPU cycles - if (!currentDefer) { - currentDefer = $$q.defer(); - $$asyncCallback(function() { - currentDefer.resolve(); - currentDefer = null; - }); - } - return currentDefer.promise; - } + function cachedClassManipulation(cache, classes, op) { + for (var i = 0, ii = classes.length; i < ii; ++i) { + var className = classes[i]; + cache[className] = op; + } + } - function applyStyles(element, options) { - if (angular.isObject(options)) { - var styles = extend(options.from || {}, options.to || {}); - element.css(styles); - } - } + function asyncPromise() { + // only serve one instance of a promise in order to save CPU cycles + if (!currentDefer) { + currentDefer = $$q.defer(); + $$asyncCallback(function () { + currentDefer.resolve(); + currentDefer = null; + }); + } + return currentDefer.promise; + } - /** - * - * @ngdoc service - * @name $animate - * @description The $animate service provides rudimentary DOM manipulation functions to - * insert, remove and move elements within the DOM, as well as adding and removing classes. - * This service is the core service used by the ngAnimate $animator service which provides - * high-level animation hooks for CSS and JavaScript. - * - * $animate is available in the AngularJS core, however, the ngAnimate module must be included - * to enable full out animation support. Otherwise, $animate will only perform simple DOM - * manipulation operations. - * - * To learn more about enabling animation support, click here to visit the {@link ngAnimate + function applyStyles(element, options) { + if (angular.isObject(options)) { + var styles = extend(options.from || {}, options.to || {}); + element.css(styles); + } + } + + /** + * + * @ngdoc service + * @name $animate + * @description The $animate service provides rudimentary DOM manipulation functions to + * insert, remove and move elements within the DOM, as well as adding and removing classes. + * This service is the core service used by the ngAnimate $animator service which provides + * high-level animation hooks for CSS and JavaScript. + * + * $animate is available in the AngularJS core, however, the ngAnimate module must be included + * to enable full out animation support. Otherwise, $animate will only perform simple DOM + * manipulation operations. + * + * To learn more about enabling animation support, click here to visit the {@link ngAnimate * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service * page}. - */ - return { - animate : function(element, from, to) { - applyStyles(element, { from: from, to: to }); - return asyncPromise(); - }, - - /** - * - * @ngdoc method - * @name $animate#enter - * @kind function - * @description Inserts the element into the DOM either after the `after` element or - * as the first child within the `parent` element. When the function is called a promise - * is returned that will be resolved at a later time. - * @param {DOMElement} element the element which will be inserted into the DOM - * @param {DOMElement} parent the parent element which will append the element as - * a child (if the after element is not present) - * @param {DOMElement} after the sibling element which will append the element - * after itself - * @param {object=} options an optional collection of styles that will be applied to the element. - * @return {Promise} the animation callback promise - */ - enter : function(element, parent, after, options) { - applyStyles(element, options); - after ? after.after(element) - : parent.prepend(element); - return asyncPromise(); - }, - - /** - * - * @ngdoc method - * @name $animate#leave - * @kind function - * @description Removes the element from the DOM. When the function is called a promise - * is returned that will be resolved at a later time. - * @param {DOMElement} element the element which will be removed from the DOM - * @param {object=} options an optional collection of options that will be applied to the element. - * @return {Promise} the animation callback promise - */ - leave : function(element, options) { - element.remove(); - return asyncPromise(); - }, - - /** - * - * @ngdoc method - * @name $animate#move - * @kind function - * @description Moves the position of the provided element within the DOM to be placed - * either after the `after` element or inside of the `parent` element. When the function - * is called a promise is returned that will be resolved at a later time. - * - * @param {DOMElement} element the element which will be moved around within the - * DOM - * @param {DOMElement} parent the parent element where the element will be - * inserted into (if the after element is not present) - * @param {DOMElement} after the sibling element where the element will be - * positioned next to - * @param {object=} options an optional collection of options that will be applied to the element. - * @return {Promise} the animation callback promise - */ - move : function(element, parent, after, options) { - // Do not remove element before insert. Removing will cause data associated with the - // element to be dropped. Insert will implicitly do the remove. - return this.enter(element, parent, after, options); - }, - - /** - * - * @ngdoc method - * @name $animate#addClass - * @kind function - * @description Adds the provided className CSS class value to the provided element. - * When the function is called a promise is returned that will be resolved at a later time. - * @param {DOMElement} element the element which will have the className value - * added to it - * @param {string} className the CSS class which will be added to the element - * @param {object=} options an optional collection of options that will be applied to the element. - * @return {Promise} the animation callback promise - */ - addClass : function(element, className, options) { - return this.setClass(element, className, [], options); - }, - - $$addClassImmediately : function(element, className, options) { - element = jqLite(element); - className = !isString(className) + */ + return { + animate: function (element, from, to) { + applyStyles(element, {from: from, to: to}); + return asyncPromise(); + }, + + /** + * + * @ngdoc method + * @name $animate#enter + * @kind function + * @description Inserts the element into the DOM either after the `after` element or + * as the first child within the `parent` element. When the function is called a promise + * is returned that will be resolved at a later time. + * @param {DOMElement} element the element which will be inserted into the DOM + * @param {DOMElement} parent the parent element which will append the element as + * a child (if the after element is not present) + * @param {DOMElement} after the sibling element which will append the element + * after itself + * @param {object=} options an optional collection of styles that will be applied to the element. + * @return {Promise} the animation callback promise + */ + enter: function (element, parent, after, options) { + applyStyles(element, options); + after ? after.after(element) + : parent.prepend(element); + return asyncPromise(); + }, + + /** + * + * @ngdoc method + * @name $animate#leave + * @kind function + * @description Removes the element from the DOM. When the function is called a promise + * is returned that will be resolved at a later time. + * @param {DOMElement} element the element which will be removed from the DOM + * @param {object=} options an optional collection of options that will be applied to the element. + * @return {Promise} the animation callback promise + */ + leave: function (element, options) { + element.remove(); + return asyncPromise(); + }, + + /** + * + * @ngdoc method + * @name $animate#move + * @kind function + * @description Moves the position of the provided element within the DOM to be placed + * either after the `after` element or inside of the `parent` element. When the function + * is called a promise is returned that will be resolved at a later time. + * + * @param {DOMElement} element the element which will be moved around within the + * DOM + * @param {DOMElement} parent the parent element where the element will be + * inserted into (if the after element is not present) + * @param {DOMElement} after the sibling element where the element will be + * positioned next to + * @param {object=} options an optional collection of options that will be applied to the element. + * @return {Promise} the animation callback promise + */ + move: function (element, parent, after, options) { + // Do not remove element before insert. Removing will cause data associated with the + // element to be dropped. Insert will implicitly do the remove. + return this.enter(element, parent, after, options); + }, + + /** + * + * @ngdoc method + * @name $animate#addClass + * @kind function + * @description Adds the provided className CSS class value to the provided element. + * When the function is called a promise is returned that will be resolved at a later time. + * @param {DOMElement} element the element which will have the className value + * added to it + * @param {string} className the CSS class which will be added to the element + * @param {object=} options an optional collection of options that will be applied to the element. + * @return {Promise} the animation callback promise + */ + addClass: function (element, className, options) { + return this.setClass(element, className, [], options); + }, + + $$addClassImmediately: function (element, className, options) { + element = jqLite(element); + className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; - forEach(element, function (element) { - jqLiteAddClass(element, className); - }); - applyStyles(element, options); - return asyncPromise(); - }, - - /** - * - * @ngdoc method - * @name $animate#removeClass - * @kind function - * @description Removes the provided className CSS class value from the provided element. - * When the function is called a promise is returned that will be resolved at a later time. - * @param {DOMElement} element the element which will have the className value - * removed from it - * @param {string} className the CSS class which will be removed from the element - * @param {object=} options an optional collection of options that will be applied to the element. - * @return {Promise} the animation callback promise - */ - removeClass : function(element, className, options) { - return this.setClass(element, [], className, options); - }, - - $$removeClassImmediately : function(element, className, options) { - element = jqLite(element); - className = !isString(className) + forEach(element, function (element) { + jqLiteAddClass(element, className); + }); + applyStyles(element, options); + return asyncPromise(); + }, + + /** + * + * @ngdoc method + * @name $animate#removeClass + * @kind function + * @description Removes the provided className CSS class value from the provided element. + * When the function is called a promise is returned that will be resolved at a later time. + * @param {DOMElement} element the element which will have the className value + * removed from it + * @param {string} className the CSS class which will be removed from the element + * @param {object=} options an optional collection of options that will be applied to the element. + * @return {Promise} the animation callback promise + */ + removeClass: function (element, className, options) { + return this.setClass(element, [], className, options); + }, + + $$removeClassImmediately: function (element, className, options) { + element = jqLite(element); + className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; - forEach(element, function (element) { - jqLiteRemoveClass(element, className); - }); - applyStyles(element, options); - return asyncPromise(); - }, + forEach(element, function (element) { + jqLiteRemoveClass(element, className); + }); + applyStyles(element, options); + return asyncPromise(); + }, + + /** + * + * @ngdoc method + * @name $animate#setClass + * @kind function + * @description Adds and/or removes the given CSS classes to and from the element. + * When the function is called a promise is returned that will be resolved at a later time. + * @param {DOMElement} element the element which will have its CSS classes changed + * removed from it + * @param {string} add the CSS classes which will be added to the element + * @param {string} remove the CSS class which will be removed from the element + * @param {object=} options an optional collection of options that will be applied to the element. + * @return {Promise} the animation callback promise + */ + setClass: function (element, add, remove, options) { + var self = this; + var STORAGE_KEY = '$$animateClasses'; + var createdCache = false; + element = jqLite(element); + + var cache = element.data(STORAGE_KEY); + if (!cache) { + cache = { + classes: {}, + options: options + }; + createdCache = true; + } else if (options && cache.options) { + cache.options = angular.extend(cache.options || {}, options); + } - /** - * - * @ngdoc method - * @name $animate#setClass - * @kind function - * @description Adds and/or removes the given CSS classes to and from the element. - * When the function is called a promise is returned that will be resolved at a later time. - * @param {DOMElement} element the element which will have its CSS classes changed - * removed from it - * @param {string} add the CSS classes which will be added to the element - * @param {string} remove the CSS class which will be removed from the element - * @param {object=} options an optional collection of options that will be applied to the element. - * @return {Promise} the animation callback promise - */ - setClass : function(element, add, remove, options) { - var self = this; - var STORAGE_KEY = '$$animateClasses'; - var createdCache = false; - element = jqLite(element); + var classes = cache.classes; + + add = isArray(add) ? add : add.split(' '); + remove = isArray(remove) ? remove : remove.split(' '); + cachedClassManipulation(classes, add, true); + cachedClassManipulation(classes, remove, false); + + if (createdCache) { + cache.promise = runAnimationPostDigest(function (done) { + var cache = element.data(STORAGE_KEY); + element.removeData(STORAGE_KEY); + + // in the event that the element is removed before postDigest + // is run then the cache will be undefined and there will be + // no need anymore to add or remove and of the element classes + if (cache) { + var classes = resolveElementClasses(element, cache.classes); + if (classes) { + self.$$setClassImmediately(element, classes[0], classes[1], cache.options); + } + } + + done(); + }); + element.data(STORAGE_KEY, cache); + } - var cache = element.data(STORAGE_KEY); - if (!cache) { - cache = { - classes: {}, - options : options - }; - createdCache = true; - } else if (options && cache.options) { - cache.options = angular.extend(cache.options || {}, options); - } + return cache.promise; + }, - var classes = cache.classes; - - add = isArray(add) ? add : add.split(' '); - remove = isArray(remove) ? remove : remove.split(' '); - cachedClassManipulation(classes, add, true); - cachedClassManipulation(classes, remove, false); - - if (createdCache) { - cache.promise = runAnimationPostDigest(function(done) { - var cache = element.data(STORAGE_KEY); - element.removeData(STORAGE_KEY); - - // in the event that the element is removed before postDigest - // is run then the cache will be undefined and there will be - // no need anymore to add or remove and of the element classes - if (cache) { - var classes = resolveElementClasses(element, cache.classes); - if (classes) { - self.$$setClassImmediately(element, classes[0], classes[1], cache.options); - } + $$setClassImmediately: function (element, add, remove, options) { + add && this.$$addClassImmediately(element, add); + remove && this.$$removeClassImmediately(element, remove); + applyStyles(element, options); + return asyncPromise(); + }, + + enabled: noop, + cancel: noop + }; + }]; + }]; + + function $$AsyncCallbackProvider() { + this.$get = ['$$rAF', '$timeout', function ($$rAF, $timeout) { + return $$rAF.supported + ? function (fn) { + return $$rAF(fn); } + : function (fn) { + return $timeout(fn, 0, false); + }; + }]; + } - done(); - }); - element.data(STORAGE_KEY, cache); - } + /* global stripHash: true */ - return cache.promise; - }, + /** + * ! This is a private undocumented service ! + * + * @name $browser + * @requires $log + * @description + * This object has two goals: + * + * - hide all the global state in the browser caused by the window object + * - abstract away all the browser specific features and inconsistencies + * + * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` + * service, which can be used for convenient testing of the application without the interaction with + * the real browser apis. + */ + /** + * @param {object} window The global window object. + * @param {object} document jQuery wrapped document. + * @param {function()} XHR XMLHttpRequest constructor. + * @param {object} $log console.log or an object with the same interface. + * @param {object} $sniffer $sniffer service + */ + function Browser(window, document, $log, $sniffer) { + var self = this, + rawDocument = document[0], + location = window.location, + history = window.history, + setTimeout = window.setTimeout, + clearTimeout = window.clearTimeout, + pendingDeferIds = {}; + + self.isMock = false; + + var outstandingRequestCount = 0; + var outstandingRequestCallbacks = []; + + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = completeOutstandingRequest; + self.$$incOutstandingRequestCount = function () { + outstandingRequestCount++; + }; - $$setClassImmediately : function(element, add, remove, options) { - add && this.$$addClassImmediately(element, add); - remove && this.$$removeClassImmediately(element, remove); - applyStyles(element, options); - return asyncPromise(); - }, + /** + * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` + * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. + */ + function completeOutstandingRequest(fn) { + try { + fn.apply(null, sliceArgs(arguments, 1)); + } finally { + outstandingRequestCount--; + if (outstandingRequestCount === 0) { + while (outstandingRequestCallbacks.length) { + try { + outstandingRequestCallbacks.pop()(); + } catch (e) { + $log.error(e); + } + } + } + } + } - enabled : noop, - cancel : noop - }; - }]; -}]; - -function $$AsyncCallbackProvider(){ - this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { - return $$rAF.supported - ? function(fn) { return $$rAF(fn); } - : function(fn) { - return $timeout(fn, 0, false); - }; - }]; -} + /** + * @private + * Note: this method is used only by scenario runner + * TODO(vojta): prefix this method with $$ ? + * @param {function()} callback Function that will be called when no outstanding request + */ + self.notifyWhenNoOutstandingRequests = function (callback) { + // force browser to execute all pollFns - this is needed so that cookies and other pollers fire + // at some deterministic time in respect to the test runner's actions. Leaving things up to the + // regular poller would result in flaky tests. + forEach(pollFns, function (pollFn) { + pollFn(); + }); -/* global stripHash: true */ + if (outstandingRequestCount === 0) { + callback(); + } else { + outstandingRequestCallbacks.push(callback); + } + }; -/** - * ! This is a private undocumented service ! - * - * @name $browser - * @requires $log - * @description - * This object has two goals: - * - * - hide all the global state in the browser caused by the window object - * - abstract away all the browser specific features and inconsistencies - * - * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` - * service, which can be used for convenient testing of the application without the interaction with - * the real browser apis. - */ -/** - * @param {object} window The global window object. - * @param {object} document jQuery wrapped document. - * @param {function()} XHR XMLHttpRequest constructor. - * @param {object} $log console.log or an object with the same interface. - * @param {object} $sniffer $sniffer service - */ -function Browser(window, document, $log, $sniffer) { - var self = this, - rawDocument = document[0], - location = window.location, - history = window.history, - setTimeout = window.setTimeout, - clearTimeout = window.clearTimeout, - pendingDeferIds = {}; - - self.isMock = false; - - var outstandingRequestCount = 0; - var outstandingRequestCallbacks = []; - - // TODO(vojta): remove this temporary api - self.$$completeOutstandingRequest = completeOutstandingRequest; - self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; - - /** - * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` - * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. - */ - function completeOutstandingRequest(fn) { - try { - fn.apply(null, sliceArgs(arguments, 1)); - } finally { - outstandingRequestCount--; - if (outstandingRequestCount === 0) { - while(outstandingRequestCallbacks.length) { - try { - outstandingRequestCallbacks.pop()(); - } catch (e) { - $log.error(e); - } - } - } - } - } - - /** - * @private - * Note: this method is used only by scenario runner - * TODO(vojta): prefix this method with $$ ? - * @param {function()} callback Function that will be called when no outstanding request - */ - self.notifyWhenNoOutstandingRequests = function(callback) { - // force browser to execute all pollFns - this is needed so that cookies and other pollers fire - // at some deterministic time in respect to the test runner's actions. Leaving things up to the - // regular poller would result in flaky tests. - forEach(pollFns, function(pollFn){ pollFn(); }); - - if (outstandingRequestCount === 0) { - callback(); - } else { - outstandingRequestCallbacks.push(callback); - } - }; + ////////////////////////////////////////////////////////////// + // Poll Watcher API + ////////////////////////////////////////////////////////////// + var pollFns = [], + pollTimeout; - ////////////////////////////////////////////////////////////// - // Poll Watcher API - ////////////////////////////////////////////////////////////// - var pollFns = [], - pollTimeout; + /** + * @name $browser#addPollFn + * + * @param {function()} fn Poll function to add + * + * @description + * Adds a function to the list of functions that poller periodically executes, + * and starts polling if not started yet. + * + * @returns {function()} the added function + */ + self.addPollFn = function (fn) { + if (isUndefined(pollTimeout)) startPoller(100, setTimeout); + pollFns.push(fn); + return fn; + }; - /** - * @name $browser#addPollFn - * - * @param {function()} fn Poll function to add - * - * @description - * Adds a function to the list of functions that poller periodically executes, - * and starts polling if not started yet. - * - * @returns {function()} the added function - */ - self.addPollFn = function(fn) { - if (isUndefined(pollTimeout)) startPoller(100, setTimeout); - pollFns.push(fn); - return fn; - }; - - /** - * @param {number} interval How often should browser call poll functions (ms) - * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. - * - * @description - * Configures the poller to run in the specified intervals, using the specified - * setTimeout fn and kicks it off. - */ - function startPoller(interval, setTimeout) { - (function check() { - forEach(pollFns, function(pollFn){ pollFn(); }); - pollTimeout = setTimeout(check, interval); - })(); - } - - ////////////////////////////////////////////////////////////// - // URL API - ////////////////////////////////////////////////////////////// - - var cachedState, lastHistoryState, - lastBrowserUrl = location.href, - baseElement = document.find('base'), - reloadLocation = null; - - cacheState(); - lastHistoryState = cachedState; - - /** - * @name $browser#url - * - * @description - * GETTER: - * Without any argument, this method just returns current value of location.href. - * - * SETTER: - * With at least one argument, this method sets url to new value. - * If html5 history api supported, pushState/replaceState is used, otherwise - * location.href/location.replace is used. - * Returns its own instance to allow chaining - * - * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to change url. - * - * @param {string} url New url (when used as setter) - * @param {boolean=} replace Should new url replace current history record? - * @param {object=} state object to use with pushState/replaceState - */ - self.url = function(url, replace, state) { - // In modern browsers `history.state` is `null` by default; treating it separately - // from `undefined` would cause `$browser.url('/foo')` to change `history.state` - // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. - if (isUndefined(state)) { - state = null; - } + /** + * @param {number} interval How often should browser call poll functions (ms) + * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. + * + * @description + * Configures the poller to run in the specified intervals, using the specified + * setTimeout fn and kicks it off. + */ + function startPoller(interval, setTimeout) { + (function check() { + forEach(pollFns, function (pollFn) { + pollFn(); + }); + pollTimeout = setTimeout(check, interval); + })(); + } - // Android Browser BFCache causes location, history reference to become stale. - if (location !== window.location) location = window.location; - if (history !== window.history) history = window.history; + ////////////////////////////////////////////////////////////// + // URL API + ////////////////////////////////////////////////////////////// - // setter - if (url) { - var sameState = lastHistoryState === state; + var cachedState, lastHistoryState, + lastBrowserUrl = location.href, + baseElement = document.find('base'), + reloadLocation = null; - // Don't change anything if previous and current URLs and states match. This also prevents - // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. - // See https://github.com/angular/angular.js/commit/ffb2701 - if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { - return; - } - var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); - lastBrowserUrl = url; - lastHistoryState = state; - // Don't use history API if only the hash changed - // due to a bug in IE10/IE11 which leads - // to not firing a `hashchange` nor `popstate` event - // in some cases (see #9143). - if ($sniffer.history && (!sameBase || !sameState)) { - history[replace ? 'replaceState' : 'pushState'](state, '', url); cacheState(); - // Do the assignment again so that those two variables are referentially identical. lastHistoryState = cachedState; - } else { - if (!sameBase) { - reloadLocation = url; + + /** + * @name $browser#url + * + * @description + * GETTER: + * Without any argument, this method just returns current value of location.href. + * + * SETTER: + * With at least one argument, this method sets url to new value. + * If html5 history api supported, pushState/replaceState is used, otherwise + * location.href/location.replace is used. + * Returns its own instance to allow chaining + * + * NOTE: this api is intended for use only by the $location service. Please use the + * {@link ng.$location $location service} to change url. + * + * @param {string} url New url (when used as setter) + * @param {boolean=} replace Should new url replace current history record? + * @param {object=} state object to use with pushState/replaceState + */ + self.url = function (url, replace, state) { + // In modern browsers `history.state` is `null` by default; treating it separately + // from `undefined` would cause `$browser.url('/foo')` to change `history.state` + // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. + if (isUndefined(state)) { + state = null; + } + + // Android Browser BFCache causes location, history reference to become stale. + if (location !== window.location) location = window.location; + if (history !== window.history) history = window.history; + + // setter + if (url) { + var sameState = lastHistoryState === state; + + // Don't change anything if previous and current URLs and states match. This also prevents + // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. + // See https://github.com/angular/angular.js/commit/ffb2701 + if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { + return; + } + var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); + lastBrowserUrl = url; + lastHistoryState = state; + // Don't use history API if only the hash changed + // due to a bug in IE10/IE11 which leads + // to not firing a `hashchange` nor `popstate` event + // in some cases (see #9143). + if ($sniffer.history && (!sameBase || !sameState)) { + history[replace ? 'replaceState' : 'pushState'](state, '', url); + cacheState(); + // Do the assignment again so that those two variables are referentially identical. + lastHistoryState = cachedState; + } else { + if (!sameBase) { + reloadLocation = url; + } + if (replace) { + location.replace(url); + } else { + location.href = url; + } + } + return self; + // getter + } else { + // - reloadLocation is needed as browsers don't allow to read out + // the new location.href if a reload happened. + // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 + return reloadLocation || location.href.replace(/%27/g, "'"); + } + }; + + /** + * @name $browser#state + * + * @description + * This method is a getter. + * + * Return history.state or null if history.state is undefined. + * + * @returns {object} state + */ + self.state = function () { + return cachedState; + }; + + var urlChangeListeners = [], + urlChangeInit = false; + + function cacheStateAndFireUrlChange() { + cacheState(); + fireUrlChange(); } - if (replace) { - location.replace(url); - } else { - location.href = url; + + // This variable should be used *only* inside the cacheState function. + var lastCachedState = null; + + function cacheState() { + // This should be the only place in $browser where `history.state` is read. + cachedState = window.history.state; + cachedState = isUndefined(cachedState) ? null : cachedState; + + // Prevent callbacks fo fire twice if both hashchange & popstate were fired. + if (equals(cachedState, lastCachedState)) { + cachedState = lastCachedState; + } + lastCachedState = cachedState; } - } - return self; - // getter - } else { - // - reloadLocation is needed as browsers don't allow to read out - // the new location.href if a reload happened. - // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return reloadLocation || location.href.replace(/%27/g,"'"); - } - }; - /** - * @name $browser#state - * - * @description - * This method is a getter. - * - * Return history.state or null if history.state is undefined. - * - * @returns {object} state - */ - self.state = function() { - return cachedState; - }; - - var urlChangeListeners = [], - urlChangeInit = false; - - function cacheStateAndFireUrlChange() { - cacheState(); - fireUrlChange(); - } - - // This variable should be used *only* inside the cacheState function. - var lastCachedState = null; - function cacheState() { - // This should be the only place in $browser where `history.state` is read. - cachedState = window.history.state; - cachedState = isUndefined(cachedState) ? null : cachedState; - - // Prevent callbacks fo fire twice if both hashchange & popstate were fired. - if (equals(cachedState, lastCachedState)) { - cachedState = lastCachedState; - } - lastCachedState = cachedState; - } + function fireUrlChange() { + if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) { + return; + } - function fireUrlChange() { - if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) { - return; - } + lastBrowserUrl = self.url(); + lastHistoryState = cachedState; + forEach(urlChangeListeners, function (listener) { + listener(self.url(), cachedState); + }); + } - lastBrowserUrl = self.url(); - lastHistoryState = cachedState; - forEach(urlChangeListeners, function(listener) { - listener(self.url(), cachedState); - }); - } + /** + * @name $browser#onUrlChange + * + * @description + * Register callback function that will be called, when url changes. + * + * It's only called when the url is changed from outside of angular: + * - user types different url into address bar + * - user clicks on history (forward/back) button + * - user clicks on a link + * + * It's not called when url is changed by $browser.url() method + * + * The listener gets called with new url as parameter. + * + * NOTE: this api is intended for use only by the $location service. Please use the + * {@link ng.$location $location service} to monitor url changes in angular apps. + * + * @param {function(string)} listener Listener function to be called when url changes. + * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. + */ + self.onUrlChange = function (callback) { + // TODO(vojta): refactor to use node's syntax for events + if (!urlChangeInit) { + // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) + // don't fire popstate when user change the address bar and don't fire hashchange when url + // changed by push/replaceState + + // html5 history api - popstate event + if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); + // hashchange event + jqLite(window).on('hashchange', cacheStateAndFireUrlChange); + + urlChangeInit = true; + } - /** - * @name $browser#onUrlChange - * - * @description - * Register callback function that will be called, when url changes. - * - * It's only called when the url is changed from outside of angular: - * - user types different url into address bar - * - user clicks on history (forward/back) button - * - user clicks on a link - * - * It's not called when url is changed by $browser.url() method - * - * The listener gets called with new url as parameter. - * - * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to monitor url changes in angular apps. - * - * @param {function(string)} listener Listener function to be called when url changes. - * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. - */ - self.onUrlChange = function(callback) { - // TODO(vojta): refactor to use node's syntax for events - if (!urlChangeInit) { - // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) - // don't fire popstate when user change the address bar and don't fire hashchange when url - // changed by push/replaceState - - // html5 history api - popstate event - if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); - // hashchange event - jqLite(window).on('hashchange', cacheStateAndFireUrlChange); - - urlChangeInit = true; - } + urlChangeListeners.push(callback); + return callback; + }; - urlChangeListeners.push(callback); - return callback; - }; + /** + * Checks whether the url has changed outside of Angular. + * Needs to be exported to be able to check for changes that have been done in sync, + * as hashchange/popstate events fire in async. + */ + self.$$checkUrlChange = fireUrlChange; - /** - * Checks whether the url has changed outside of Angular. - * Needs to be exported to be able to check for changes that have been done in sync, - * as hashchange/popstate events fire in async. - */ - self.$$checkUrlChange = fireUrlChange; + ////////////////////////////////////////////////////////////// + // Misc API + ////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////// - // Misc API - ////////////////////////////////////////////////////////////// + /** + * @name $browser#baseHref + * + * @description + * Returns current + * (always relative - without domain) + * + * @returns {string} The current base href + */ + self.baseHref = function () { + var href = baseElement.attr('href'); + return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; + }; - /** - * @name $browser#baseHref - * - * @description - * Returns current - * (always relative - without domain) - * - * @returns {string} The current base href - */ - self.baseHref = function() { - var href = baseElement.attr('href'); - return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; - }; - - ////////////////////////////////////////////////////////////// - // Cookies API - ////////////////////////////////////////////////////////////// - var lastCookies = {}; - var lastCookieString = ''; - var cookiePath = self.baseHref(); - - function safeDecodeURIComponent(str) { - try { - return decodeURIComponent(str); - } catch (e) { - return str; - } - } + ////////////////////////////////////////////////////////////// + // Cookies API + ////////////////////////////////////////////////////////////// + var lastCookies = {}; + var lastCookieString = ''; + var cookiePath = self.baseHref(); - /** - * @name $browser#cookies - * - * @param {string=} name Cookie name - * @param {string=} value Cookie value - * - * @description - * The cookies method provides a 'private' low level access to browser cookies. - * It is not meant to be used directly, use the $cookie service instead. - * - * The return values vary depending on the arguments that the method was called with as follows: - * - * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify - * it - * - cookies(name, value) -> set name to value, if value is undefined delete the cookie - * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that - * way) - * - * @returns {Object} Hash of all cookies (if called without any parameter) - */ - self.cookies = function(name, value) { - var cookieLength, cookieArray, cookie, i, index; - - if (name) { - if (value === undefined) { - rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath + - ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; - } else { - if (isString(value)) { - cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + + function safeDecodeURIComponent(str) { + try { + return decodeURIComponent(str); + } catch (e) { + return str; + } + } + + /** + * @name $browser#cookies + * + * @param {string=} name Cookie name + * @param {string=} value Cookie value + * + * @description + * The cookies method provides a 'private' low level access to browser cookies. + * It is not meant to be used directly, use the $cookie service instead. + * + * The return values vary depending on the arguments that the method was called with as follows: + * + * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify + * it + * - cookies(name, value) -> set name to value, if value is undefined delete the cookie + * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that + * way) + * + * @returns {Object} Hash of all cookies (if called without any parameter) + */ + self.cookies = function (name, value) { + var cookieLength, cookieArray, cookie, i, index; + + if (name) { + if (value === undefined) { + rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath + + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; + } else { + if (isString(value)) { + cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=' + cookiePath).length + 1; - // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: - // - 300 cookies - // - 20 cookies per unique domain - // - 4096 bytes per cookie - if (cookieLength > 4096) { - $log.warn("Cookie '"+ name + - "' possibly not set or overflowed because it was too large ("+ - cookieLength + " > 4096 bytes)!"); - } - } - } - } else { - if (rawDocument.cookie !== lastCookieString) { - lastCookieString = rawDocument.cookie; - cookieArray = lastCookieString.split("; "); - lastCookies = {}; - - for (i = 0; i < cookieArray.length; i++) { - cookie = cookieArray[i]; - index = cookie.indexOf('='); - if (index > 0) { //ignore nameless cookies - name = safeDecodeURIComponent(cookie.substring(0, index)); - // the first value that is seen for a cookie is the most - // specific one. values for the same cookie name that - // follow are for less specific paths. - if (lastCookies[name] === undefined) { - lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); + // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: + // - 300 cookies + // - 20 cookies per unique domain + // - 4096 bytes per cookie + if (cookieLength > 4096) { + $log.warn("Cookie '" + name + + "' possibly not set or overflowed because it was too large (" + + cookieLength + " > 4096 bytes)!"); + } + } + } + } else { + if (rawDocument.cookie !== lastCookieString) { + lastCookieString = rawDocument.cookie; + cookieArray = lastCookieString.split("; "); + lastCookies = {}; + + for (i = 0; i < cookieArray.length; i++) { + cookie = cookieArray[i]; + index = cookie.indexOf('='); + if (index > 0) { //ignore nameless cookies + name = safeDecodeURIComponent(cookie.substring(0, index)); + // the first value that is seen for a cookie is the most + // specific one. values for the same cookie name that + // follow are for less specific paths. + if (lastCookies[name] === undefined) { + lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); + } + } + } + } + return lastCookies; } - } - } - } - return lastCookies; - } - }; + }; - /** - * @name $browser#defer - * @param {function()} fn A function, who's execution should be deferred. - * @param {number=} [delay=0] of milliseconds to defer the function execution. - * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. - * - * @description - * Executes a fn asynchronously via `setTimeout(fn, delay)`. - * - * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using - * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed - * via `$browser.defer.flush()`. - * - */ - self.defer = function(fn, delay) { - var timeoutId; - outstandingRequestCount++; - timeoutId = setTimeout(function() { - delete pendingDeferIds[timeoutId]; - completeOutstandingRequest(fn); - }, delay || 0); - pendingDeferIds[timeoutId] = true; - return timeoutId; - }; - - - /** - * @name $browser#defer.cancel - * - * @description - * Cancels a deferred task identified with `deferId`. - * - * @param {*} deferId Token returned by the `$browser.defer` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ - self.defer.cancel = function(deferId) { - if (pendingDeferIds[deferId]) { - delete pendingDeferIds[deferId]; - clearTimeout(deferId); - completeOutstandingRequest(noop); - return true; - } - return false; - }; + /** + * @name $browser#defer + * @param {function()} fn A function, who's execution should be deferred. + * @param {number=} [delay=0] of milliseconds to defer the function execution. + * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. + * + * @description + * Executes a fn asynchronously via `setTimeout(fn, delay)`. + * + * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using + * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed + * via `$browser.defer.flush()`. + * + */ + self.defer = function (fn, delay) { + var timeoutId; + outstandingRequestCount++; + timeoutId = setTimeout(function () { + delete pendingDeferIds[timeoutId]; + completeOutstandingRequest(fn); + }, delay || 0); + pendingDeferIds[timeoutId] = true; + return timeoutId; + }; + + + /** + * @name $browser#defer.cancel + * + * @description + * Cancels a deferred task identified with `deferId`. + * + * @param {*} deferId Token returned by the `$browser.defer` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + self.defer.cancel = function (deferId) { + if (pendingDeferIds[deferId]) { + delete pendingDeferIds[deferId]; + clearTimeout(deferId); + completeOutstandingRequest(noop); + return true; + } + return false; + }; -} + } -function $BrowserProvider(){ - this.$get = ['$window', '$log', '$sniffer', '$document', - function( $window, $log, $sniffer, $document){ - return new Browser($window, $document, $log, $sniffer); - }]; -} + function $BrowserProvider() { + this.$get = ['$window', '$log', '$sniffer', '$document', + function ($window, $log, $sniffer, $document) { + return new Browser($window, $document, $log, $sniffer); + }]; + } -/** - * @ngdoc service - * @name $cacheFactory - * - * @description - * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to - * them. - * - * ```js - * - * var cache = $cacheFactory('cacheId'); - * expect($cacheFactory.get('cacheId')).toBe(cache); - * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); - * - * cache.put("key", "value"); - * cache.put("another key", "another value"); - * - * // We've specified no options on creation - * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); - * - * ``` - * - * - * @param {string} cacheId Name or id of the newly created cache. - * @param {object=} options Options object that specifies the cache behavior. Properties: - * - * - `{number=}` `capacity` — turns the cache into LRU cache. - * - * @returns {object} Newly created cache object with the following set of methods: - * - * - `{object}` `info()` — Returns id, size, and options of cache. - * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns - * it. - * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. - * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. - * - `{void}` `removeAll()` — Removes all cached values. - * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. - * - * @example - + /** + * @ngdoc service + * @name $cacheFactory + * + * @description + * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to + * them. + * + * ```js + * + * var cache = $cacheFactory('cacheId'); + * expect($cacheFactory.get('cacheId')).toBe(cache); + * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); + * + * cache.put("key", "value"); + * cache.put("another key", "another value"); + * + * // We've specified no options on creation + * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); + * + * ``` + * + * + * @param {string} cacheId Name or id of the newly created cache. + * @param {object=} options Options object that specifies the cache behavior. Properties: + * + * - `{number=}` `capacity` — turns the cache into LRU cache. + * + * @returns {object} Newly created cache object with the following set of methods: + * + * - `{object}` `info()` — Returns id, size, and options of cache. + * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns + * it. + * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. + * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. + * - `{void}` `removeAll()` — Removes all cached values. + * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. + * + * @example + -
          - - - - -

          Cached Values

          -
          - - : - -
          +
          + + + + +

          Cached Values

          +
          + + : + +
          -

          Cache Info

          -
          - - : - -
          -
          +

          Cache Info

          +
          + + : + +
          +
          - angular.module('cacheExampleApp', []). - controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { + angular.module('cacheExampleApp', []). + controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { @@ -5358,50 +5419,50 @@ function $BrowserProvider(){ }]); - p { + p { margin: 10px 0 3px; } -
          - */ -function $CacheFactoryProvider() { +
          + */ + function $CacheFactoryProvider() { - this.$get = function() { - var caches = {}; + this.$get = function () { + var caches = {}; - function cacheFactory(cacheId, options) { - if (cacheId in caches) { - throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); - } + function cacheFactory(cacheId, options) { + if (cacheId in caches) { + throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); + } - var size = 0, - stats = extend({}, options, {id: cacheId}), - data = {}, - capacity = (options && options.capacity) || Number.MAX_VALUE, - lruHash = {}, - freshEnd = null, - staleEnd = null; - - /** - * @ngdoc type - * @name $cacheFactory.Cache - * - * @description - * A cache object used to store and retrieve data, primarily used by - * {@link $http $http} and the {@link ng.directive:script script} directive to cache - * templates and other data. - * - * ```js - * angular.module('superCache') - * .factory('superCache', ['$cacheFactory', function($cacheFactory) { + var size = 0, + stats = extend({}, options, {id: cacheId}), + data = {}, + capacity = (options && options.capacity) || Number.MAX_VALUE, + lruHash = {}, + freshEnd = null, + staleEnd = null; + + /** + * @ngdoc type + * @name $cacheFactory.Cache + * + * @description + * A cache object used to store and retrieve data, primarily used by + * {@link $http $http} and the {@link ng.directive:script script} directive to cache + * templates and other data. + * + * ```js + * angular.module('superCache') + * .factory('superCache', ['$cacheFactory', function($cacheFactory) { * return $cacheFactory('super-cache'); * }]); - * ``` - * - * Example test: - * - * ```js - * it('should behave like a cache', inject(function(superCache) { + * ``` + * + * Example test: + * + * ```js + * it('should behave like a cache', inject(function(superCache) { * superCache.put('key', 'value'); * superCache.put('another key', 'another value'); * @@ -5419,323 +5480,323 @@ function $CacheFactoryProvider() { * size: 0 * }); * })); - * ``` - */ - return caches[cacheId] = { - - /** - * @ngdoc method - * @name $cacheFactory.Cache#put - * @kind function - * - * @description - * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be - * retrieved later, and incrementing the size of the cache if the key was not already - * present in the cache. If behaving like an LRU cache, it will also remove stale - * entries from the set. - * - * It will not insert undefined values into the cache. - * - * @param {string} key the key under which the cached data is stored. - * @param {*} value the value to store alongside the key. If it is undefined, the key - * will not be stored. - * @returns {*} the value stored. - */ - put: function(key, value) { - if (capacity < Number.MAX_VALUE) { - var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); - - refresh(lruEntry); - } - - if (isUndefined(value)) return; - if (!(key in data)) size++; - data[key] = value; + * ``` + */ + return caches[cacheId] = { + + /** + * @ngdoc method + * @name $cacheFactory.Cache#put + * @kind function + * + * @description + * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be + * retrieved later, and incrementing the size of the cache if the key was not already + * present in the cache. If behaving like an LRU cache, it will also remove stale + * entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param {string} key the key under which the cached data is stored. + * @param {*} value the value to store alongside the key. If it is undefined, the key + * will not be stored. + * @returns {*} the value stored. + */ + put: function (key, value) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); + + refresh(lruEntry); + } + + if (isUndefined(value)) return; + if (!(key in data)) size++; + data[key] = value; + + if (size > capacity) { + this.remove(staleEnd.key); + } + + return value; + }, + + /** + * @ngdoc method + * @name $cacheFactory.Cache#get + * @kind function + * + * @description + * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the data to be retrieved + * @returns {*} the value stored. + */ + get: function (key) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; + + if (!lruEntry) return; + + refresh(lruEntry); + } + + return data[key]; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#remove + * @kind function + * + * @description + * Removes an entry from the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the entry to be removed + */ + remove: function (key) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; + + if (!lruEntry) return; + + if (lruEntry == freshEnd) freshEnd = lruEntry.p; + if (lruEntry == staleEnd) staleEnd = lruEntry.n; + link(lruEntry.n, lruEntry.p); + + delete lruHash[key]; + } + + delete data[key]; + size--; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#removeAll + * @kind function + * + * @description + * Clears the cache object of any entries. + */ + removeAll: function () { + data = {}; + size = 0; + lruHash = {}; + freshEnd = staleEnd = null; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#destroy + * @kind function + * + * @description + * Destroys the {@link $cacheFactory.Cache Cache} object entirely, + * removing it from the {@link $cacheFactory $cacheFactory} set. + */ + destroy: function () { + data = null; + stats = null; + lruHash = null; + delete caches[cacheId]; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#info + * @kind function + * + * @description + * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. + * + * @returns {object} an object with the following properties: + *
            + *
          • **id**: the id of the cache instance
          • + *
          • **size**: the number of entries kept in the cache instance
          • + *
          • **...**: any additional properties from the options object when creating the + * cache.
          • + *
          + */ + info: function () { + return extend({}, stats, {size: size}); + } + }; - if (size > capacity) { - this.remove(staleEnd.key); - } - return value; - }, + /** + * makes the `entry` the freshEnd of the LRU linked list + */ + function refresh(entry) { + if (entry != freshEnd) { + if (!staleEnd) { + staleEnd = entry; + } else if (staleEnd == entry) { + staleEnd = entry.n; + } + + link(entry.n, entry.p); + link(entry, freshEnd); + freshEnd = entry; + freshEnd.n = null; + } + } - /** - * @ngdoc method - * @name $cacheFactory.Cache#get - * @kind function - * - * @description - * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. - * - * @param {string} key the key of the data to be retrieved - * @returns {*} the value stored. - */ - get: function(key) { - if (capacity < Number.MAX_VALUE) { - var lruEntry = lruHash[key]; - if (!lruEntry) return; + /** + * bidirectionally links two entries of the LRU linked list + */ + function link(nextEntry, prevEntry) { + if (nextEntry != prevEntry) { + if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify + if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify + } + } + } - refresh(lruEntry); - } - return data[key]; - }, + /** + * @ngdoc method + * @name $cacheFactory#info + * + * @description + * Get information about all the caches that have been created + * + * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` + */ + cacheFactory.info = function () { + var info = {}; + forEach(caches, function (cache, cacheId) { + info[cacheId] = cache.info(); + }); + return info; + }; - /** - * @ngdoc method - * @name $cacheFactory.Cache#remove - * @kind function - * - * @description - * Removes an entry from the {@link $cacheFactory.Cache Cache} object. - * - * @param {string} key the key of the entry to be removed - */ - remove: function(key) { - if (capacity < Number.MAX_VALUE) { - var lruEntry = lruHash[key]; + /** + * @ngdoc method + * @name $cacheFactory#get + * + * @description + * Get access to a cache object by the `cacheId` used when it was created. + * + * @param {string} cacheId Name or id of a cache to access. + * @returns {object} Cache object identified by the cacheId or undefined if no such cache. + */ + cacheFactory.get = function (cacheId) { + return caches[cacheId]; + }; - if (!lruEntry) return; - if (lruEntry == freshEnd) freshEnd = lruEntry.p; - if (lruEntry == staleEnd) staleEnd = lruEntry.n; - link(lruEntry.n,lruEntry.p); + return cacheFactory; + }; + } - delete lruHash[key]; - } - - delete data[key]; - size--; - }, - - - /** - * @ngdoc method - * @name $cacheFactory.Cache#removeAll - * @kind function - * - * @description - * Clears the cache object of any entries. - */ - removeAll: function() { - data = {}; - size = 0; - lruHash = {}; - freshEnd = staleEnd = null; - }, - - - /** - * @ngdoc method - * @name $cacheFactory.Cache#destroy - * @kind function - * - * @description - * Destroys the {@link $cacheFactory.Cache Cache} object entirely, - * removing it from the {@link $cacheFactory $cacheFactory} set. - */ - destroy: function() { - data = null; - stats = null; - lruHash = null; - delete caches[cacheId]; - }, - - - /** - * @ngdoc method - * @name $cacheFactory.Cache#info - * @kind function - * - * @description - * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. - * - * @returns {object} an object with the following properties: - *
            - *
          • **id**: the id of the cache instance
          • - *
          • **size**: the number of entries kept in the cache instance
          • - *
          • **...**: any additional properties from the options object when creating the - * cache.
          • - *
          - */ - info: function() { - return extend({}, stats, {size: size}); - } - }; - - - /** - * makes the `entry` the freshEnd of the LRU linked list - */ - function refresh(entry) { - if (entry != freshEnd) { - if (!staleEnd) { - staleEnd = entry; - } else if (staleEnd == entry) { - staleEnd = entry.n; - } - - link(entry.n, entry.p); - link(entry, freshEnd); - freshEnd = entry; - freshEnd.n = null; - } - } - - - /** - * bidirectionally links two entries of the LRU linked list - */ - function link(nextEntry, prevEntry) { - if (nextEntry != prevEntry) { - if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify - if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify - } - } - } - - - /** - * @ngdoc method - * @name $cacheFactory#info - * - * @description - * Get information about all the caches that have been created - * - * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` - */ - cacheFactory.info = function() { - var info = {}; - forEach(caches, function(cache, cacheId) { - info[cacheId] = cache.info(); - }); - return info; - }; - - - /** - * @ngdoc method - * @name $cacheFactory#get - * - * @description - * Get access to a cache object by the `cacheId` used when it was created. - * - * @param {string} cacheId Name or id of a cache to access. - * @returns {object} Cache object identified by the cacheId or undefined if no such cache. - */ - cacheFactory.get = function(cacheId) { - return caches[cacheId]; - }; - - - return cacheFactory; - }; -} - -/** - * @ngdoc service - * @name $templateCache - * - * @description - * The first time a template is used, it is loaded in the template cache for quick retrieval. You - * can load templates directly into the cache in a `script` tag, or by consuming the - * `$templateCache` service directly. - * - * Adding via the `script` tag: - * - * ```html - * - * ``` - * - * **Note:** the `script` tag containing the template does not need to be included in the `head` of - * the document, but it must be below the `ng-app` definition. - * - * Adding via the $templateCache service: - * - * ```js - * var myApp = angular.module('myApp', []); - * myApp.run(function($templateCache) { + /** + * @ngdoc service + * @name $templateCache + * + * @description + * The first time a template is used, it is loaded in the template cache for quick retrieval. You + * can load templates directly into the cache in a `script` tag, or by consuming the + * `$templateCache` service directly. + * + * Adding via the `script` tag: + * + * ```html + * + * ``` + * + * **Note:** the `script` tag containing the template does not need to be included in the `head` of + * the document, but it must be below the `ng-app` definition. + * + * Adding via the $templateCache service: + * + * ```js + * var myApp = angular.module('myApp', []); + * myApp.run(function($templateCache) { * $templateCache.put('templateId.html', 'This is the content of the template'); * }); - * ``` - * - * To retrieve the template later, simply use it in your HTML: - * ```html - *
          - * ``` - * - * or get it via Javascript: - * ```js - * $templateCache.get('templateId.html') - * ``` - * - * See {@link ng.$cacheFactory $cacheFactory}. - * - */ -function $TemplateCacheProvider() { - this.$get = ['$cacheFactory', function($cacheFactory) { - return $cacheFactory('templates'); - }]; -} + * ``` + * + * To retrieve the template later, simply use it in your HTML: + * ```html + *
          + * ``` + * + * or get it via Javascript: + * ```js + * $templateCache.get('templateId.html') + * ``` + * + * See {@link ng.$cacheFactory $cacheFactory}. + * + */ + function $TemplateCacheProvider() { + this.$get = ['$cacheFactory', function ($cacheFactory) { + return $cacheFactory('templates'); + }]; + } -/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! - * - * DOM-related variables: - * - * - "node" - DOM Node - * - "element" - DOM Element or Node - * - "$node" or "$element" - jqLite-wrapped node or element - * - * - * Compiler related stuff: - * - * - "linkFn" - linking fn of a single directive - * - "nodeLinkFn" - function that aggregates all linking fns for a particular node - * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node - * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) - */ + /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! + * + * DOM-related variables: + * + * - "node" - DOM Node + * - "element" - DOM Element or Node + * - "$node" or "$element" - jqLite-wrapped node or element + * + * + * Compiler related stuff: + * + * - "linkFn" - linking fn of a single directive + * - "nodeLinkFn" - function that aggregates all linking fns for a particular node + * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node + * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) + */ -/** - * @ngdoc service - * @name $compile - * @kind function - * - * @description - * Compiles an HTML string or DOM into a template and produces a template function, which - * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. - * - * The compilation is a process of walking the DOM tree and matching DOM elements to - * {@link ng.$compileProvider#directive directives}. - * - *
          - * **Note:** This document is an in-depth reference of all directive options. - * For a gentle introduction to directives with examples of common use cases, - * see the {@link guide/directive directive guide}. - *
          - * - * ## Comprehensive Directive API - * - * There are many different options for a directive. - * - * The difference resides in the return value of the factory function. - * You can either return a "Directive Definition Object" (see below) that defines the directive properties, - * or just the `postLink` function (all other properties will have the default values). - * - *
          - * **Best Practice:** It's recommended to use the "directive definition object" form. - *
          - * - * Here's an example directive declared with a Directive Definition Object: - * - * ```js - * var myModule = angular.module(...); - * - * myModule.directive('directiveName', function factory(injectables) { + /** + * @ngdoc service + * @name $compile + * @kind function + * + * @description + * Compiles an HTML string or DOM into a template and produces a template function, which + * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. + * + * The compilation is a process of walking the DOM tree and matching DOM elements to + * {@link ng.$compileProvider#directive directives}. + * + *
          + * **Note:** This document is an in-depth reference of all directive options. + * For a gentle introduction to directives with examples of common use cases, + * see the {@link guide/directive directive guide}. + *
          + * + * ## Comprehensive Directive API + * + * There are many different options for a directive. + * + * The difference resides in the return value of the factory function. + * You can either return a "Directive Definition Object" (see below) that defines the directive properties, + * or just the `postLink` function (all other properties will have the default values). + * + *
          + * **Best Practice:** It's recommended to use the "directive definition object" form. + *
          + * + * Here's an example directive declared with a Directive Definition Object: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * priority: 0, * template: '
          ', // or // function(tElement, tAttrs) { ... }, @@ -5766,18 +5827,18 @@ function $TemplateCacheProvider() { * }; * return directiveDefinitionObject; * }); - * ``` - * - *
          - * **Note:** Any unspecified options will use the default value. You can see the default values below. - *
          - * - * Therefore the above can be simplified as: - * - * ```js - * var myModule = angular.module(...); - * - * myModule.directive('directiveName', function factory(injectables) { + * ``` + * + *
          + * **Note:** Any unspecified options will use the default value. You can see the default values below. + *
          + * + * Therefore the above can be simplified as: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * link: function postLink(scope, iElement, iAttrs) { ... } * }; @@ -5785,447 +5846,447 @@ function $TemplateCacheProvider() { * // or * // return function postLink(scope, iElement, iAttrs) { ... } * }); - * ``` - * - * - * - * ### Directive Definition Object - * - * The directive definition object provides instructions to the {@link ng.$compile + * ``` + * + * + * + * ### Directive Definition Object + * + * The directive definition object provides instructions to the {@link ng.$compile * compiler}. The attributes are: - * - * #### `multiElement` - * When this property is set to true, the HTML compiler will collect DOM nodes between - * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them - * together as the directive elements. It is recomended that this feature be used on directives - * which are not strictly behavioural (such as {@link ngClick}), and which - * do not manipulate or replace child nodes (such as {@link ngInclude}). - * - * #### `priority` - * When there are multiple directives defined on a single DOM element, sometimes it - * is necessary to specify the order in which the directives are applied. The `priority` is used - * to sort the directives before their `compile` functions get called. Priority is defined as a - * number. Directives with greater numerical `priority` are compiled first. Pre-link functions - * are also run in priority order, but post-link functions are run in reverse order. The order - * of directives with the same priority is undefined. The default priority is `0`. - * - * #### `terminal` - * If set to true then the current `priority` will be the last set of directives - * which will execute (any directives at the current priority will still execute - * as the order of execution on same `priority` is undefined). Note that expressions - * and other directives used in the directive's template will also be excluded from execution. - * - * #### `scope` - * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the - * same element request a new scope, only one new scope is created. The new scope rule does not - * apply for the root of the template since the root of the template always gets a new scope. - * - * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from - * normal scope in that it does not prototypically inherit from the parent scope. This is useful - * when creating reusable components, which should not accidentally read or modify data in the - * parent scope. - * - * The 'isolate' scope takes an object hash which defines a set of local scope properties - * derived from the parent scope. These local properties are useful for aliasing values for - * templates. Locals definition is a hash of local scope property to its source: - * - * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is - * always a string since DOM attributes are strings. If no `attr` name is specified then the - * attribute name is assumed to be the same as the local name. - * Given `` and widget definition - * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect - * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the - * `localName` property on the widget scope. The `name` is read from the parent scope (not - * component scope). - * - * * `=` or `=attr` - set up bi-directional binding between a local scope property and the - * parent scope property of name defined via the value of the `attr` attribute. If no `attr` - * name is specified then the attribute name is assumed to be the same as the local name. - * Given `` and widget definition of - * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the - * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected - * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent - * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You - * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. - * - * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. - * If no `attr` name is specified then the attribute name is assumed to be the same as the - * local name. Given `` and widget definition of - * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to - * a function wrapper for the `count = count + value` expression. Often it's desirable to - * pass data from the isolated scope via an expression to the parent scope, this can be - * done by passing a map of local variable names and values into the expression wrapper fn. - * For example, if the expression is `increment(amount)` then we can specify the amount value - * by calling the `localFn` as `localFn({amount: 22})`. - * - * - * #### `bindToController` - * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController` will - * allow a component to have its properties bound to the controller, rather than to scope. When the controller - * is instantiated, the initial values of the isolate scope bindings are already available. - * - * #### `controller` - * Controller constructor function. The controller is instantiated before the - * pre-linking phase and it is shared with other directives (see - * `require` attribute). This allows the directives to communicate with each other and augment - * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: - * - * * `$scope` - Current scope associated with the element - * * `$element` - Current element - * * `$attrs` - Current attributes object for the element - * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: - * `function([scope], cloneLinkingFn, futureParentElement)`. - * * `scope`: optional argument to override the scope. - * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content. - * * `futureParentElement`: - * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. - * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. - * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) - * and when the `cloneLinkinFn` is passed, - * as those elements need to created and cloned in a special way when they are defined outside their - * usual containers (e.g. like ``). - * * See also the `directive.templateNamespace` property. - * - * - * #### `require` - * Require another directive and inject its controller as the fourth argument to the linking function. The - * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the - * injected argument will be an array in corresponding order. If no such directive can be - * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: - * - * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. - * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. - * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. - * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. - * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass - * `null` to the `link` fn if not found. - * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass - * `null` to the `link` fn if not found. - * - * - * #### `controllerAs` - * Controller alias at the directive scope. An alias for the controller so it - * can be referenced at the directive template. The directive needs to define a scope for this - * configuration to be used. Useful in the case when directive is used as component. - * - * - * #### `restrict` - * String of subset of `EACM` which restricts the directive to a specific directive - * declaration style. If omitted, the defaults (elements and attributes) are used. - * - * * `E` - Element name (default): `` - * * `A` - Attribute (default): `
          ` - * * `C` - Class: `
          ` - * * `M` - Comment: `` - * - * - * #### `templateNamespace` - * String representing the document type used by the markup in the template. - * AngularJS needs this information as those elements need to be created and cloned - * in a special way when they are defined outside their usual containers like `` and ``. - * - * * `html` - All root nodes in the template are HTML. Root nodes may also be - * top-level elements such as `` or ``. - * * `svg` - The root nodes in the template are SVG elements (excluding ``). - * * `math` - The root nodes in the template are MathML elements (excluding ``). - * - * If no `templateNamespace` is specified, then the namespace is considered to be `html`. - * - * #### `template` - * HTML markup that may: - * * Replace the contents of the directive's element (default). - * * Replace the directive's element itself (if `replace` is true - DEPRECATED). - * * Wrap the contents of the directive's element (if `transclude` is true). - * - * Value may be: - * - * * A string. For example `
          {{delete_str}}
          `. - * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` - * function api below) and returns a string value. - * - * - * #### `templateUrl` - * This is similar to `template` but the template is loaded from the specified URL, asynchronously. - * - * Because template loading is asynchronous the compiler will suspend compilation of directives on that element - * for later when the template has been resolved. In the meantime it will continue to compile and link - * sibling and parent elements as though this element had not contained any directives. - * - * The compiler does not suspend the entire compilation to wait for templates to be loaded because this - * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the - * case when only one deeply nested directive has `templateUrl`. - * - * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} - * - * You can specify `templateUrl` as a string representing the URL or as a function which takes two - * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns - * a string value representing the url. In either case, the template URL is passed through {@link - * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. - * - * - * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0) - * specify what the template should replace. Defaults to `false`. - * - * * `true` - the template will replace the directive's element. - * * `false` - the template will replace the contents of the directive's element. - * - * The replacement process migrates all of the attributes / classes from the old element to the new - * one. See the {@link guide/directive#template-expanding-directive + * + * #### `multiElement` + * When this property is set to true, the HTML compiler will collect DOM nodes between + * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them + * together as the directive elements. It is recomended that this feature be used on directives + * which are not strictly behavioural (such as {@link ngClick}), and which + * do not manipulate or replace child nodes (such as {@link ngInclude}). + * + * #### `priority` + * When there are multiple directives defined on a single DOM element, sometimes it + * is necessary to specify the order in which the directives are applied. The `priority` is used + * to sort the directives before their `compile` functions get called. Priority is defined as a + * number. Directives with greater numerical `priority` are compiled first. Pre-link functions + * are also run in priority order, but post-link functions are run in reverse order. The order + * of directives with the same priority is undefined. The default priority is `0`. + * + * #### `terminal` + * If set to true then the current `priority` will be the last set of directives + * which will execute (any directives at the current priority will still execute + * as the order of execution on same `priority` is undefined). Note that expressions + * and other directives used in the directive's template will also be excluded from execution. + * + * #### `scope` + * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the + * same element request a new scope, only one new scope is created. The new scope rule does not + * apply for the root of the template since the root of the template always gets a new scope. + * + * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from + * normal scope in that it does not prototypically inherit from the parent scope. This is useful + * when creating reusable components, which should not accidentally read or modify data in the + * parent scope. + * + * The 'isolate' scope takes an object hash which defines a set of local scope properties + * derived from the parent scope. These local properties are useful for aliasing values for + * templates. Locals definition is a hash of local scope property to its source: + * + * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is + * always a string since DOM attributes are strings. If no `attr` name is specified then the + * attribute name is assumed to be the same as the local name. + * Given `` and widget definition + * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect + * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the + * `localName` property on the widget scope. The `name` is read from the parent scope (not + * component scope). + * + * * `=` or `=attr` - set up bi-directional binding between a local scope property and the + * parent scope property of name defined via the value of the `attr` attribute. If no `attr` + * name is specified then the attribute name is assumed to be the same as the local name. + * Given `` and widget definition of + * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected + * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent + * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You + * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. + * + * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. + * If no `attr` name is specified then the attribute name is assumed to be the same as the + * local name. Given `` and widget definition of + * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to + * a function wrapper for the `count = count + value` expression. Often it's desirable to + * pass data from the isolated scope via an expression to the parent scope, this can be + * done by passing a map of local variable names and values into the expression wrapper fn. + * For example, if the expression is `increment(amount)` then we can specify the amount value + * by calling the `localFn` as `localFn({amount: 22})`. + * + * + * #### `bindToController` + * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController` will + * allow a component to have its properties bound to the controller, rather than to scope. When the controller + * is instantiated, the initial values of the isolate scope bindings are already available. + * + * #### `controller` + * Controller constructor function. The controller is instantiated before the + * pre-linking phase and it is shared with other directives (see + * `require` attribute). This allows the directives to communicate with each other and augment + * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: + * + * * `$scope` - Current scope associated with the element + * * `$element` - Current element + * * `$attrs` - Current attributes object for the element + * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: + * `function([scope], cloneLinkingFn, futureParentElement)`. + * * `scope`: optional argument to override the scope. + * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content. + * * `futureParentElement`: + * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. + * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. + * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) + * and when the `cloneLinkinFn` is passed, + * as those elements need to created and cloned in a special way when they are defined outside their + * usual containers (e.g. like ``). + * * See also the `directive.templateNamespace` property. + * + * + * #### `require` + * Require another directive and inject its controller as the fourth argument to the linking function. The + * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the + * injected argument will be an array in corresponding order. If no such directive can be + * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: + * + * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. + * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. + * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. + * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. + * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass + * `null` to the `link` fn if not found. + * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass + * `null` to the `link` fn if not found. + * + * + * #### `controllerAs` + * Controller alias at the directive scope. An alias for the controller so it + * can be referenced at the directive template. The directive needs to define a scope for this + * configuration to be used. Useful in the case when directive is used as component. + * + * + * #### `restrict` + * String of subset of `EACM` which restricts the directive to a specific directive + * declaration style. If omitted, the defaults (elements and attributes) are used. + * + * * `E` - Element name (default): `` + * * `A` - Attribute (default): `
          ` + * * `C` - Class: `
          ` + * * `M` - Comment: `` + * + * + * #### `templateNamespace` + * String representing the document type used by the markup in the template. + * AngularJS needs this information as those elements need to be created and cloned + * in a special way when they are defined outside their usual containers like `` and ``. + * + * * `html` - All root nodes in the template are HTML. Root nodes may also be + * top-level elements such as `` or ``. + * * `svg` - The root nodes in the template are SVG elements (excluding ``). + * * `math` - The root nodes in the template are MathML elements (excluding ``). + * + * If no `templateNamespace` is specified, then the namespace is considered to be `html`. + * + * #### `template` + * HTML markup that may: + * * Replace the contents of the directive's element (default). + * * Replace the directive's element itself (if `replace` is true - DEPRECATED). + * * Wrap the contents of the directive's element (if `transclude` is true). + * + * Value may be: + * + * * A string. For example `
          {{delete_str}}
          `. + * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` + * function api below) and returns a string value. + * + * + * #### `templateUrl` + * This is similar to `template` but the template is loaded from the specified URL, asynchronously. + * + * Because template loading is asynchronous the compiler will suspend compilation of directives on that element + * for later when the template has been resolved. In the meantime it will continue to compile and link + * sibling and parent elements as though this element had not contained any directives. + * + * The compiler does not suspend the entire compilation to wait for templates to be loaded because this + * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the + * case when only one deeply nested directive has `templateUrl`. + * + * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} + * + * You can specify `templateUrl` as a string representing the URL or as a function which takes two + * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns + * a string value representing the url. In either case, the template URL is passed through {@link + * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. + * + * + * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0) + * specify what the template should replace. Defaults to `false`. + * + * * `true` - the template will replace the directive's element. + * * `false` - the template will replace the contents of the directive's element. + * + * The replacement process migrates all of the attributes / classes from the old element to the new + * one. See the {@link guide/directive#template-expanding-directive * Directives Guide} for an example. - * - * There are very few scenarios where element replacement is required for the application function, - * the main one being reusable custom components that are used within SVG contexts - * (because SVG doesn't work with custom elements in the DOM tree). - * - * #### `transclude` - * Extract the contents of the element where the directive appears and make it available to the directive. - * The contents are compiled and provided to the directive as a **transclusion function**. See the - * {@link $compile#transclusion Transclusion} section below. - * - * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the - * directive's element or the entire element: - * - * * `true` - transclude the content (i.e. the child nodes) of the directive's element. - * * `'element'` - transclude the whole of the directive's element including any directives on this - * element that defined at a lower priority than this directive. When used, the `template` - * property is ignored. - * - * - * #### `compile` - * - * ```js - * function compile(tElement, tAttrs, transclude) { ... } - * ``` - * - * The compile function deals with transforming the template DOM. Since most directives do not do - * template transformation, it is not used often. The compile function takes the following arguments: - * - * * `tElement` - template element - The element where the directive has been declared. It is - * safe to do template transformation on the element and child elements only. - * - * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared - * between all directive compile functions. - * - * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` - * - *
          - * **Note:** The template instance and the link instance may be different objects if the template has - * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that - * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration - * should be done in a linking function rather than in a compile function. - *
          - - *
          - * **Note:** The compile function cannot handle directives that recursively use themselves in their - * own templates or compile functions. Compiling these directives results in an infinite loop and a - * stack overflow errors. - * - * This can be avoided by manually using $compile in the postLink function to imperatively compile - * a directive's template instead of relying on automatic template compilation via `template` or - * `templateUrl` declaration or manual compilation inside the compile function. - *
          - * - *
          - * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it - * e.g. does not know about the right outer scope. Please use the transclude function that is passed - * to the link function instead. - *
          + * + * There are very few scenarios where element replacement is required for the application function, + * the main one being reusable custom components that are used within SVG contexts + * (because SVG doesn't work with custom elements in the DOM tree). + * + * #### `transclude` + * Extract the contents of the element where the directive appears and make it available to the directive. + * The contents are compiled and provided to the directive as a **transclusion function**. See the + * {@link $compile#transclusion Transclusion} section below. + * + * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the + * directive's element or the entire element: + * + * * `true` - transclude the content (i.e. the child nodes) of the directive's element. + * * `'element'` - transclude the whole of the directive's element including any directives on this + * element that defined at a lower priority than this directive. When used, the `template` + * property is ignored. + * + * + * #### `compile` + * + * ```js + * function compile(tElement, tAttrs, transclude) { ... } + * ``` + * + * The compile function deals with transforming the template DOM. Since most directives do not do + * template transformation, it is not used often. The compile function takes the following arguments: + * + * * `tElement` - template element - The element where the directive has been declared. It is + * safe to do template transformation on the element and child elements only. + * + * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared + * between all directive compile functions. + * + * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` + * + *
          + * **Note:** The template instance and the link instance may be different objects if the template has + * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that + * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration + * should be done in a linking function rather than in a compile function. + *
          + + *
          + * **Note:** The compile function cannot handle directives that recursively use themselves in their + * own templates or compile functions. Compiling these directives results in an infinite loop and a + * stack overflow errors. + * + * This can be avoided by manually using $compile in the postLink function to imperatively compile + * a directive's template instead of relying on automatic template compilation via `template` or + * `templateUrl` declaration or manual compilation inside the compile function. + *
          + * + *
          + * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it + * e.g. does not know about the right outer scope. Please use the transclude function that is passed + * to the link function instead. + *
          - * A compile function can have a return value which can be either a function or an object. - * - * * returning a (post-link) function - is equivalent to registering the linking function via the - * `link` property of the config object when the compile function is empty. - * - * * returning an object with function(s) registered via `pre` and `post` properties - allows you to - * control when a linking function should be called during the linking phase. See info about - * pre-linking and post-linking functions below. - * - * - * #### `link` - * This property is used only if the `compile` property is not defined. - * - * ```js - * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } - * ``` - * - * The link function is responsible for registering DOM listeners as well as updating the DOM. It is - * executed after the template has been cloned. This is where most of the directive logic will be - * put. - * - * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the - * directive for registering {@link ng.$rootScope.Scope#$watch watches}. - * - * * `iElement` - instance element - The element where the directive is to be used. It is safe to - * manipulate the children of the element only in `postLink` function since the children have - * already been linked. - * - * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared - * between all directive linking functions. - * - * * `controller` - a controller instance - A controller instance if at least one directive on the - * element defines a controller. The controller is shared among all the directives, which allows - * the directives to use the controllers as a communication channel. - * - * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. - * This is the same as the `$transclude` - * parameter of directive controllers, see there for details. - * `function([scope], cloneLinkingFn, futureParentElement)`. - * - * #### Pre-linking function - * - * Executed before the child elements are linked. Not safe to do DOM transformation since the - * compiler linking function will fail to locate the correct elements for linking. - * - * #### Post-linking function - * - * Executed after the child elements are linked. - * - * Note that child elements that contain `templateUrl` directives will not have been compiled - * and linked since they are waiting for their template to load asynchronously and their own - * compilation and linking has been suspended until that occurs. - * - * It is safe to do DOM transformation in the post-linking function on elements that are not waiting - * for their async templates to be resolved. - * - * - * ### Transclusion - * - * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and - * copying them to another part of the DOM, while maintaining their connection to the original AngularJS - * scope from where they were taken. - * - * Transclusion is used (often with {@link ngTransclude}) to insert the - * original contents of a directive's element into a specified place in the template of the directive. - * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded - * content has access to the properties on the scope from which it was taken, even if the directive - * has isolated scope. - * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. - * - * This makes it possible for the widget to have private state for its template, while the transcluded - * content has access to its originating scope. - * - *
          - * **Note:** When testing an element transclude directive you must not place the directive at the root of the - * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives + * A compile function can have a return value which can be either a function or an object. + * + * * returning a (post-link) function - is equivalent to registering the linking function via the + * `link` property of the config object when the compile function is empty. + * + * * returning an object with function(s) registered via `pre` and `post` properties - allows you to + * control when a linking function should be called during the linking phase. See info about + * pre-linking and post-linking functions below. + * + * + * #### `link` + * This property is used only if the `compile` property is not defined. + * + * ```js + * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } + * ``` + * + * The link function is responsible for registering DOM listeners as well as updating the DOM. It is + * executed after the template has been cloned. This is where most of the directive logic will be + * put. + * + * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the + * directive for registering {@link ng.$rootScope.Scope#$watch watches}. + * + * * `iElement` - instance element - The element where the directive is to be used. It is safe to + * manipulate the children of the element only in `postLink` function since the children have + * already been linked. + * + * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared + * between all directive linking functions. + * + * * `controller` - a controller instance - A controller instance if at least one directive on the + * element defines a controller. The controller is shared among all the directives, which allows + * the directives to use the controllers as a communication channel. + * + * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. + * This is the same as the `$transclude` + * parameter of directive controllers, see there for details. + * `function([scope], cloneLinkingFn, futureParentElement)`. + * + * #### Pre-linking function + * + * Executed before the child elements are linked. Not safe to do DOM transformation since the + * compiler linking function will fail to locate the correct elements for linking. + * + * #### Post-linking function + * + * Executed after the child elements are linked. + * + * Note that child elements that contain `templateUrl` directives will not have been compiled + * and linked since they are waiting for their template to load asynchronously and their own + * compilation and linking has been suspended until that occurs. + * + * It is safe to do DOM transformation in the post-linking function on elements that are not waiting + * for their async templates to be resolved. + * + * + * ### Transclusion + * + * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and + * copying them to another part of the DOM, while maintaining their connection to the original AngularJS + * scope from where they were taken. + * + * Transclusion is used (often with {@link ngTransclude}) to insert the + * original contents of a directive's element into a specified place in the template of the directive. + * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded + * content has access to the properties on the scope from which it was taken, even if the directive + * has isolated scope. + * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. + * + * This makes it possible for the widget to have private state for its template, while the transcluded + * content has access to its originating scope. + * + *
          + * **Note:** When testing an element transclude directive you must not place the directive at the root of the + * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives * Testing Transclusion Directives}. - *
          - * - * #### Transclusion Functions - * - * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion - * function** to the directive's `link` function and `controller`. This transclusion function is a special - * **linking function** that will return the compiled contents linked to a new transclusion scope. - * - *
          - * If you are just using {@link ngTransclude} then you don't need to worry about this function, since - * ngTransclude will deal with it for us. - *
          - * - * If you want to manually control the insertion and removal of the transcluded content in your directive - * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery - * object that contains the compiled DOM, which is linked to the correct transclusion scope. - * - * When you call a transclusion function you can pass in a **clone attach function**. This function accepts - * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded - * content and the `scope` is the newly created transclusion scope, to which the clone is bound. - * - *
          - * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function - * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. - *
          - * - * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone - * attach function**: - * - * ```js - * var transcludedContent, transclusionScope; - * - * $transclude(function(clone, scope) { + *
          + * + * #### Transclusion Functions + * + * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion + * function** to the directive's `link` function and `controller`. This transclusion function is a special + * **linking function** that will return the compiled contents linked to a new transclusion scope. + * + *
          + * If you are just using {@link ngTransclude} then you don't need to worry about this function, since + * ngTransclude will deal with it for us. + *
          + * + * If you want to manually control the insertion and removal of the transcluded content in your directive + * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery + * object that contains the compiled DOM, which is linked to the correct transclusion scope. + * + * When you call a transclusion function you can pass in a **clone attach function**. This function accepts + * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded + * content and the `scope` is the newly created transclusion scope, to which the clone is bound. + * + *
          + * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function + * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. + *
          + * + * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone + * attach function**: + * + * ```js + * var transcludedContent, transclusionScope; + * + * $transclude(function(clone, scope) { * element.append(clone); * transcludedContent = clone; * transclusionScope = scope; * }); - * ``` - * - * Later, if you want to remove the transcluded content from your DOM then you should also destroy the - * associated transclusion scope: - * - * ```js - * transcludedContent.remove(); - * transclusionScope.$destroy(); - * ``` - * - *
          - * **Best Practice**: if you intend to add and remove transcluded content manually in your directive - * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it), - * then you are also responsible for calling `$destroy` on the transclusion scope. - *
          - * - * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} - * automatically destroy their transluded clones as necessary so you do not need to worry about this if - * you are simply using {@link ngTransclude} to inject the transclusion into your directive. - * - * - * #### Transclusion Scopes - * - * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion - * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed - * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it - * was taken. - * - * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look - * like this: - * - * ```html - *
          - *
          - *
          - *
          - *
          - *
          - * ``` - * - * The `$parent` scope hierarchy will look like this: - * - * ``` - * - $rootScope - * - isolate - * - transclusion - * ``` - * - * but the scopes will inherit prototypically from different scopes to their `$parent`. - * - * ``` - * - $rootScope - * - transclusion - * - isolate - * ``` - * - * - * ### Attributes - * - * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the - * `link()` or `compile()` functions. It has a variety of uses. - * - * accessing *Normalized attribute names:* - * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. - * the attributes object allows for normalized access to - * the attributes. - * - * * *Directive inter-communication:* All directives share the same instance of the attributes - * object which allows the directives to use the attributes object as inter directive - * communication. - * - * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object - * allowing other directives to read the interpolated value. - * - * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes - * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also - * the only way to easily get the actual value because during the linking phase the interpolation - * hasn't been evaluated yet and so the value is at this time set to `undefined`. - * - * ```js - * function linkingFn(scope, elm, attrs, ctrl) { + * ``` + * + * Later, if you want to remove the transcluded content from your DOM then you should also destroy the + * associated transclusion scope: + * + * ```js + * transcludedContent.remove(); + * transclusionScope.$destroy(); + * ``` + * + *
          + * **Best Practice**: if you intend to add and remove transcluded content manually in your directive + * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it), + * then you are also responsible for calling `$destroy` on the transclusion scope. + *
          + * + * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} + * automatically destroy their transluded clones as necessary so you do not need to worry about this if + * you are simply using {@link ngTransclude} to inject the transclusion into your directive. + * + * + * #### Transclusion Scopes + * + * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion + * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed + * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it + * was taken. + * + * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look + * like this: + * + * ```html + *
          + *
          + *
          + *
          + *
          + *
          + * ``` + * + * The `$parent` scope hierarchy will look like this: + * + * ``` + * - $rootScope + * - isolate + * - transclusion + * ``` + * + * but the scopes will inherit prototypically from different scopes to their `$parent`. + * + * ``` + * - $rootScope + * - transclusion + * - isolate + * ``` + * + * + * ### Attributes + * + * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the + * `link()` or `compile()` functions. It has a variety of uses. + * + * accessing *Normalized attribute names:* + * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. + * the attributes object allows for normalized access to + * the attributes. + * + * * *Directive inter-communication:* All directives share the same instance of the attributes + * object which allows the directives to use the attributes object as inter directive + * communication. + * + * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object + * allowing other directives to read the interpolated value. + * + * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes + * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also + * the only way to easily get the actual value because during the linking phase the interpolation + * hasn't been evaluated yet and so the value is at this time set to `undefined`. + * + * ```js + * function linkingFn(scope, elm, attrs, ctrl) { * // get the attribute value * console.log(attrs.ngModel); * @@ -6237,19 +6298,19 @@ function $TemplateCacheProvider() { * console.log('ngModel has changed value to ' + value); * }); * } - * ``` - * - * ## Example - * - *
          - * **Note**: Typically directives are registered with `module.directive`. The example below is - * to illustrate how `$compile` works. - *
          - * - - - -
          -
          -
          -
          -
          -
          - + +
          +
          +
          +
          +
          +
          + it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); @@ -6296,2503 +6357,2506 @@ function $TemplateCacheProvider() { textarea.sendKeys('{{name}}!'); expect(output.getText()).toBe('Angular!'); }); - -
          + + - * - * - * @param {string|DOMElement} element Element or HTML string to compile into a template function. - * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. - * @param {number} maxPriority only apply directives lower than given priority (Only effects the - * root element(s), not their children) - * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template - * (a DOM element/tree) to a scope. Where: - * - * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. - * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the - * `template` and call the `cloneAttachFn` function allowing the caller to attach the - * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is - * called as:
          `cloneAttachFn(clonedElement, scope)` where: - * - * * `clonedElement` - is a clone of the original `element` passed into the compiler. - * * `scope` - is the current scope with which the linking function is working with. - * - * Calling the linking function returns the element of the template. It is either the original - * element passed in, or the clone of the element if the `cloneAttachFn` is provided. - * - * After linking the view is not updated until after a call to $digest which typically is done by - * Angular automatically. - * - * If you need access to the bound view, there are two ways to do it: - * - * - If you are not asking the linking function to clone the template, create the DOM element(s) - * before you send them to the compiler and keep this reference around. - * ```js - * var element = $compile('

          {{total}}

          ')(scope); - * ``` - * - * - if on the other hand, you need the element to be cloned, the view reference from the original - * example would not point to the clone, but rather to the original template that was cloned. In - * this case, you can access the clone via the cloneAttachFn: - * ```js - * var templateElement = angular.element('

          {{total}}

          '), - * scope = ....; - * - * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { + * + * + * @param {string|DOMElement} element Element or HTML string to compile into a template function. + * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. + * @param {number} maxPriority only apply directives lower than given priority (Only effects the + * root element(s), not their children) + * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template + * (a DOM element/tree) to a scope. Where: + * + * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. + * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the + * `template` and call the `cloneAttachFn` function allowing the caller to attach the + * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is + * called as:
          `cloneAttachFn(clonedElement, scope)` where: + * + * * `clonedElement` - is a clone of the original `element` passed into the compiler. + * * `scope` - is the current scope with which the linking function is working with. + * + * Calling the linking function returns the element of the template. It is either the original + * element passed in, or the clone of the element if the `cloneAttachFn` is provided. + * + * After linking the view is not updated until after a call to $digest which typically is done by + * Angular automatically. + * + * If you need access to the bound view, there are two ways to do it: + * + * - If you are not asking the linking function to clone the template, create the DOM element(s) + * before you send them to the compiler and keep this reference around. + * ```js + * var element = $compile('

          {{total}}

          ')(scope); + * ``` + * + * - if on the other hand, you need the element to be cloned, the view reference from the original + * example would not point to the clone, but rather to the original template that was cloned. In + * this case, you can access the clone via the cloneAttachFn: + * ```js + * var templateElement = angular.element('

          {{total}}

          '), + * scope = ....; + * + * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); - * - * //now we have reference to the cloned DOM via `clonedElement` - * ``` - * - * - * For information on how the compiler works, see the - * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. - */ + * + * //now we have reference to the cloned DOM via `clonedElement` + * ``` + * + * + * For information on how the compiler works, see the + * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. + */ -var $compileMinErr = minErr('$compile'); + var $compileMinErr = minErr('$compile'); -/** - * @ngdoc provider - * @name $compileProvider - * - * @description - */ -$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; -function $CompileProvider($provide, $$sanitizeUriProvider) { - var hasDirectives = {}, - Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/, - ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), - REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; - - // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes - // The assumption is that future DOM event attribute names will begin with - // 'on' and be composed of only English letters. - var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; - - function parseIsolateBindings(scope, directiveName) { - var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; - - var bindings = {}; - - forEach(scope, function(definition, scopeName) { - var match = definition.match(LOCAL_REGEXP); - - if (!match) { - throw $compileMinErr('iscp', - "Invalid isolate scope definition for directive '{0}'." + - " Definition: {... {1}: '{2}' ...}", - directiveName, scopeName, definition); - } + /** + * @ngdoc provider + * @name $compileProvider + * + * @description + */ + $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; + function $CompileProvider($provide, $$sanitizeUriProvider) { + var hasDirectives = {}, + Suffix = 'Directive', + COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/, + ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), + REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; + + // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes + // The assumption is that future DOM event attribute names will begin with + // 'on' and be composed of only English letters. + var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; + + function parseIsolateBindings(scope, directiveName) { + var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; + + var bindings = {}; + + forEach(scope, function (definition, scopeName) { + var match = definition.match(LOCAL_REGEXP); + + if (!match) { + throw $compileMinErr('iscp', + "Invalid isolate scope definition for directive '{0}'." + + " Definition: {... {1}: '{2}' ...}", + directiveName, scopeName, definition); + } - bindings[scopeName] = { - attrName: match[3] || scopeName, - mode: match[1], - optional: match[2] === '?' - }; - }); + bindings[scopeName] = { + attrName: match[3] || scopeName, + mode: match[1], + optional: match[2] === '?' + }; + }); - return bindings; - } + return bindings; + } - /** - * @ngdoc method - * @name $compileProvider#directive - * @kind function - * - * @description - * Register a new directive with the compiler. - * - * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which - * will match as ng-bind), or an object map of directives where the keys are the - * names and the values are the factories. - * @param {Function|Array} directiveFactory An injectable directive factory function. See - * {@link guide/directive} for more info. - * @returns {ng.$compileProvider} Self for chaining. - */ - this.directive = function registerDirective(name, directiveFactory) { - assertNotHasOwnProperty(name, 'directive'); - if (isString(name)) { - assertArg(directiveFactory, 'directiveFactory'); - if (!hasDirectives.hasOwnProperty(name)) { - hasDirectives[name] = []; - $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', - function($injector, $exceptionHandler) { - var directives = []; - forEach(hasDirectives[name], function(directiveFactory, index) { - try { - var directive = $injector.invoke(directiveFactory); - if (isFunction(directive)) { - directive = { compile: valueFn(directive) }; - } else if (!directive.compile && directive.link) { - directive.compile = valueFn(directive.link); - } - directive.priority = directive.priority || 0; - directive.index = index; - directive.name = directive.name || name; - directive.require = directive.require || (directive.controller && directive.name); - directive.restrict = directive.restrict || 'EA'; - if (isObject(directive.scope)) { - directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name); + /** + * @ngdoc method + * @name $compileProvider#directive + * @kind function + * + * @description + * Register a new directive with the compiler. + * + * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which + * will match as ng-bind), or an object map of directives where the keys are the + * names and the values are the factories. + * @param {Function|Array} directiveFactory An injectable directive factory function. See + * {@link guide/directive} for more info. + * @returns {ng.$compileProvider} Self for chaining. + */ + this.directive = function registerDirective(name, directiveFactory) { + assertNotHasOwnProperty(name, 'directive'); + if (isString(name)) { + assertArg(directiveFactory, 'directiveFactory'); + if (!hasDirectives.hasOwnProperty(name)) { + hasDirectives[name] = []; + $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', + function ($injector, $exceptionHandler) { + var directives = []; + forEach(hasDirectives[name], function (directiveFactory, index) { + try { + var directive = $injector.invoke(directiveFactory); + if (isFunction(directive)) { + directive = {compile: valueFn(directive)}; + } else if (!directive.compile && directive.link) { + directive.compile = valueFn(directive.link); + } + directive.priority = directive.priority || 0; + directive.index = index; + directive.name = directive.name || name; + directive.require = directive.require || (directive.controller && directive.name); + directive.restrict = directive.restrict || 'EA'; + if (isObject(directive.scope)) { + directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name); + } + directives.push(directive); + } catch (e) { + $exceptionHandler(e); + } + }); + return directives; + }]); } - directives.push(directive); - } catch (e) { - $exceptionHandler(e); - } - }); - return directives; - }]); - } - hasDirectives[name].push(directiveFactory); - } else { - forEach(name, reverseParams(registerDirective)); - } - return this; - }; + hasDirectives[name].push(directiveFactory); + } else { + forEach(name, reverseParams(registerDirective)); + } + return this; + }; - /** - * @ngdoc method - * @name $compileProvider#aHrefSanitizationWhitelist - * @kind function - * - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during a[href] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to a[href] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` - * regular expression. If a match is found, the original url is written into the dom. Otherwise, - * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.aHrefSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); - return this; - } else { - return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); - } - }; + /** + * @ngdoc method + * @name $compileProvider#aHrefSanitizationWhitelist + * @kind function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during a[href] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function (regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); + return this; + } else { + return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); + } + }; - /** - * @ngdoc method - * @name $compileProvider#imgSrcSanitizationWhitelist - * @kind function - * - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during img[src] sanitization. - * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. - * - * Any url about to be assigned to img[src] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` - * regular expression. If a match is found, the original url is written into the dom. Otherwise, - * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. - * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.imgSrcSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); - return this; - } else { - return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); - } - }; + /** + * @ngdoc method + * @name $compileProvider#imgSrcSanitizationWhitelist + * @kind function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.imgSrcSanitizationWhitelist = function (regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); + return this; + } else { + return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); + } + }; - /** - * @ngdoc method - * @name $compileProvider#debugInfoEnabled - * - * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the - * current debugInfoEnabled state - * @returns {*} current value if used as getter or itself (chaining) if used as setter - * - * @kind function - * - * @description - * Call this method to enable/disable various debug runtime information in the compiler such as adding - * binding information and a reference to the current scope on to DOM elements. - * If enabled, the compiler will add the following to DOM elements that have been bound to the scope - * * `ng-binding` CSS class - * * `$binding` data property containing an array of the binding expressions - * - * You may want to use this in production for a significant performance boost. See - * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. - * - * The default value is true. - */ - var debugInfoEnabled = true; - this.debugInfoEnabled = function(enabled) { - if(isDefined(enabled)) { - debugInfoEnabled = enabled; - return this; - } - return debugInfoEnabled; - }; + /** + * @ngdoc method + * @name $compileProvider#debugInfoEnabled + * + * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the + * current debugInfoEnabled state + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable/disable various debug runtime information in the compiler such as adding + * binding information and a reference to the current scope on to DOM elements. + * If enabled, the compiler will add the following to DOM elements that have been bound to the scope + * * `ng-binding` CSS class + * * `$binding` data property containing an array of the binding expressions + * + * You may want to use this in production for a significant performance boost. See + * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. + * + * The default value is true. + */ + var debugInfoEnabled = true; + this.debugInfoEnabled = function (enabled) { + if (isDefined(enabled)) { + debugInfoEnabled = enabled; + return this; + } + return debugInfoEnabled; + }; - this.$get = [ + this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', - function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, - $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { + function ($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, + $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { + + var Attributes = function (element, attributesToCopy) { + if (attributesToCopy) { + var keys = Object.keys(attributesToCopy); + var i, l, key; + + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + this[key] = attributesToCopy[key]; + } + } else { + this.$attr = {}; + } - var Attributes = function(element, attributesToCopy) { - if (attributesToCopy) { - var keys = Object.keys(attributesToCopy); - var i, l, key; + this.$$element = element; + }; - for (i = 0, l = keys.length; i < l; i++) { - key = keys[i]; - this[key] = attributesToCopy[key]; - } - } else { - this.$attr = {}; - } + Attributes.prototype = { + $normalize: directiveNormalize, + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$addClass + * @kind function + * + * @description + * Adds the CSS class value specified by the classVal parameter to the element. If animations + * are enabled then an animation will be triggered for the class addition. + * + * @param {string} classVal The className value that will be added to the element + */ + $addClass: function (classVal) { + if (classVal && classVal.length > 0) { + $animate.addClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$removeClass + * @kind function + * + * @description + * Removes the CSS class value specified by the classVal parameter from the element. If + * animations are enabled then an animation will be triggered for the class removal. + * + * @param {string} classVal The className value that will be removed from the element + */ + $removeClass: function (classVal) { + if (classVal && classVal.length > 0) { + $animate.removeClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$updateClass + * @kind function + * + * @description + * Adds and removes the appropriate CSS class values to the element based on the difference + * between the new and old CSS class values (specified as newClasses and oldClasses). + * + * @param {string} newClasses The current CSS className value + * @param {string} oldClasses The former CSS className value + */ + $updateClass: function (newClasses, oldClasses) { + var toAdd = tokenDifference(newClasses, oldClasses); + if (toAdd && toAdd.length) { + $animate.addClass(this.$$element, toAdd); + } + + var toRemove = tokenDifference(oldClasses, newClasses); + if (toRemove && toRemove.length) { + $animate.removeClass(this.$$element, toRemove); + } + }, + + /** + * Set a normalized attribute on the element in a way such that all directives + * can share the attribute. This function properly handles boolean attributes. + * @param {string} key Normalized key. (ie ngAttribute) + * @param {string|boolean} value The value to set. If `null` attribute will be deleted. + * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. + * Defaults to true. + * @param {string=} attrName Optional none normalized name. Defaults to key. + */ + $set: function (key, value, writeAttr, attrName) { + // TODO: decide whether or not to throw an error if "class" + //is set through this function since it may cause $updateClass to + //become unstable. + + var node = this.$$element[0], + booleanKey = getBooleanAttrName(node, key), + aliasedKey = getAliasedAttrName(node, key), + observer = key, + normalizedVal, + nodeName; + + if (booleanKey) { + this.$$element.prop(key, value); + attrName = booleanKey; + } else if (aliasedKey) { + this[aliasedKey] = value; + observer = aliasedKey; + } + + this[key] = value; + + // translate normalized key to actual key + if (attrName) { + this.$attr[key] = attrName; + } else { + attrName = this.$attr[key]; + if (!attrName) { + this.$attr[key] = attrName = snake_case(key, '-'); + } + } + + nodeName = nodeName_(this.$$element); + + if ((nodeName === 'a' && key === 'href') || + (nodeName === 'img' && key === 'src')) { + // sanitize a[href] and img[src] values + this[key] = value = $$sanitizeUri(value, key === 'src'); + } else if (nodeName === 'img' && key === 'srcset') { + // sanitize img[srcset] values + var result = ""; + + // first check if there are spaces because it's not the same pattern + var trimmedSrcset = trim(value); + // ( 999x ,| 999w ,| ,|, ) + var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; + var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; + + // split srcset into tuple of uri and descriptor except for the last item + var rawUris = trimmedSrcset.split(pattern); + + // for each tuples + var nbrUrisWith2parts = Math.floor(rawUris.length / 2); + for (var i = 0; i < nbrUrisWith2parts; i++) { + var innerIdx = i * 2; + // sanitize the uri + result += $$sanitizeUri(trim(rawUris[innerIdx]), true); + // add the descriptor + result += ( " " + trim(rawUris[innerIdx + 1])); + } + + // split the last item into uri and descriptor + var lastTuple = trim(rawUris[i * 2]).split(/\s/); + + // sanitize the last uri + result += $$sanitizeUri(trim(lastTuple[0]), true); + + // and add the last descriptor if any + if (lastTuple.length === 2) { + result += (" " + trim(lastTuple[1])); + } + this[key] = value = result; + } + + if (writeAttr !== false) { + if (value === null || value === undefined) { + this.$$element.removeAttr(attrName); + } else { + this.$$element.attr(attrName, value); + } + } + + // fire observers + var $$observers = this.$$observers; + $$observers && forEach($$observers[observer], function (fn) { + try { + fn(value); + } catch (e) { + $exceptionHandler(e); + } + }); + }, + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$observe + * @kind function + * + * @description + * Observes an interpolated attribute. + * + * The observer function will be invoked once during the next `$digest` following + * compilation. The observer is then invoked whenever the interpolated value + * changes. + * + * @param {string} key Normalized key. (ie ngAttribute) . + * @param {function(interpolatedValue)} fn Function that will be called whenever + the interpolated value of the attribute changes. + * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info. + * @returns {function()} Returns a deregistration function for this observer. + */ + $observe: function (key, fn) { + var attrs = this, + $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), + listeners = ($$observers[key] || ($$observers[key] = [])); + + listeners.push(fn); + $rootScope.$evalAsync(function () { + if (!listeners.$$inter) { + // no one registered attribute interpolation function, so lets call it manually + fn(attrs[key]); + } + }); + + return function () { + arrayRemove(listeners, fn); + }; + } + }; - this.$$element = element; - }; - Attributes.prototype = { - $normalize: directiveNormalize, + function safeAddClass($element, className) { + try { + $element.addClass(className); + } catch (e) { + // ignore, since it means that we are trying to set class on + // SVG element, where class name is read-only. + } + } - /** - * @ngdoc method - * @name $compile.directive.Attributes#$addClass - * @kind function - * - * @description - * Adds the CSS class value specified by the classVal parameter to the element. If animations - * are enabled then an animation will be triggered for the class addition. - * - * @param {string} classVal The className value that will be added to the element - */ - $addClass : function(classVal) { - if(classVal && classVal.length > 0) { - $animate.addClass(this.$$element, classVal); - } - }, + var startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') + ? identity + : function denormalizeTemplate(template) { + return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); + }, + NG_ATTR_BINDING = /^ngAttr[A-Z]/; - /** - * @ngdoc method - * @name $compile.directive.Attributes#$removeClass - * @kind function - * - * @description - * Removes the CSS class value specified by the classVal parameter from the element. If - * animations are enabled then an animation will be triggered for the class removal. - * - * @param {string} classVal The className value that will be removed from the element - */ - $removeClass : function(classVal) { - if(classVal && classVal.length > 0) { - $animate.removeClass(this.$$element, classVal); - } - }, + compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { + var bindings = $element.data('$binding') || []; - /** - * @ngdoc method - * @name $compile.directive.Attributes#$updateClass - * @kind function - * - * @description - * Adds and removes the appropriate CSS class values to the element based on the difference - * between the new and old CSS class values (specified as newClasses and oldClasses). - * - * @param {string} newClasses The current CSS className value - * @param {string} oldClasses The former CSS className value - */ - $updateClass : function(newClasses, oldClasses) { - var toAdd = tokenDifference(newClasses, oldClasses); - if (toAdd && toAdd.length) { - $animate.addClass(this.$$element, toAdd); - } + if (isArray(binding)) { + bindings = bindings.concat(binding); + } else { + bindings.push(binding); + } - var toRemove = tokenDifference(oldClasses, newClasses); - if (toRemove && toRemove.length) { - $animate.removeClass(this.$$element, toRemove); - } - }, - - /** - * Set a normalized attribute on the element in a way such that all directives - * can share the attribute. This function properly handles boolean attributes. - * @param {string} key Normalized key. (ie ngAttribute) - * @param {string|boolean} value The value to set. If `null` attribute will be deleted. - * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. - * Defaults to true. - * @param {string=} attrName Optional none normalized name. Defaults to key. - */ - $set: function(key, value, writeAttr, attrName) { - // TODO: decide whether or not to throw an error if "class" - //is set through this function since it may cause $updateClass to - //become unstable. - - var node = this.$$element[0], - booleanKey = getBooleanAttrName(node, key), - aliasedKey = getAliasedAttrName(node, key), - observer = key, - normalizedVal, - nodeName; - - if (booleanKey) { - this.$$element.prop(key, value); - attrName = booleanKey; - } else if(aliasedKey) { - this[aliasedKey] = value; - observer = aliasedKey; - } + $element.data('$binding', bindings); + } : noop; - this[key] = value; + compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { + safeAddClass($element, 'ng-binding'); + } : noop; - // translate normalized key to actual key - if (attrName) { - this.$attr[key] = attrName; - } else { - attrName = this.$attr[key]; - if (!attrName) { - this.$attr[key] = attrName = snake_case(key, '-'); - } - } + compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { + var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; + $element.data(dataName, scope); + } : noop; - nodeName = nodeName_(this.$$element); - - if ((nodeName === 'a' && key === 'href') || - (nodeName === 'img' && key === 'src')) { - // sanitize a[href] and img[src] values - this[key] = value = $$sanitizeUri(value, key === 'src'); - } else if (nodeName === 'img' && key === 'srcset') { - // sanitize img[srcset] values - var result = ""; - - // first check if there are spaces because it's not the same pattern - var trimmedSrcset = trim(value); - // ( 999x ,| 999w ,| ,|, ) - var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; - var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; - - // split srcset into tuple of uri and descriptor except for the last item - var rawUris = trimmedSrcset.split(pattern); - - // for each tuples - var nbrUrisWith2parts = Math.floor(rawUris.length / 2); - for (var i=0; i + forEach($compileNodes, function (node, index) { + if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */) { + $compileNodes[index] = jqLite(node).wrap('').parent()[0]; + } + }); + var compositeLinkFn = + compileNodes($compileNodes, transcludeFn, $compileNodes, + maxPriority, ignoreDirective, previousCompileContext); + compile.$$addScopeClass($compileNodes); + var namespace = null; + return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn, futureParentElement) { + assertArg(scope, 'scope'); + if (!namespace) { + namespace = detectNamespaceForChildElements(futureParentElement); + } + var $linkNode; + if (namespace !== 'html') { + // When using a directive with replace:true and templateUrl the $compileNodes + // (or a child element inside of them) + // might change, so we need to recreate the namespace adapted compileNodes + // for call to the link function. + // Note: This will already clone the nodes... + $linkNode = jqLite( + wrapTemplate(namespace, jqLite('
          ').append($compileNodes).html()) + ); + } else if (cloneConnectFn) { + // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart + // and sometimes changes the structure of the DOM. + $linkNode = JQLitePrototype.clone.call($compileNodes); + } else { + $linkNode = $compileNodes; + } + + if (transcludeControllers) { + for (var controllerName in transcludeControllers) { + $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); + } + } + + compile.$$addScopeInfo($linkNode, scope); + + if (cloneConnectFn) cloneConnectFn($linkNode, scope); + if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); + return $linkNode; + }; + } - if (writeAttr !== false) { - if (value === null || value === undefined) { - this.$$element.removeAttr(attrName); - } else { - this.$$element.attr(attrName, value); - } - } + function detectNamespaceForChildElements(parentElement) { + // TODO: Make this detect MathML as well... + var node = parentElement && parentElement[0]; + if (!node) { + return 'html'; + } else { + return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html'; + } + } - // fire observers - var $$observers = this.$$observers; - $$observers && forEach($$observers[observer], function(fn) { - try { - fn(value); - } catch (e) { - $exceptionHandler(e); - } - }); - }, + /** + * Compile function matches each node in nodeList against the directives. Once all directives + * for a particular node are collected their compile functions are executed. The compile + * functions return values - the linking functions - are combined into a composite linking + * function, which is the a linking function for the node. + * + * @param {NodeList} nodeList an array of nodes or NodeList to compile + * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the + * scope argument is auto-generated to the new child of the transcluded parent scope. + * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then + * the rootElement must be set the jqLite collection of the compile root. This is + * needed so that the jqLite collection items can be replaced with widgets. + * @param {number=} maxPriority Max directive priority. + * @returns {Function} A composite linking function of all of the matched directives or null. + */ + function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, + previousCompileContext) { + var linkFns = [], + attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; + + for (var i = 0; i < nodeList.length; i++) { + attrs = new Attributes(); + + // we must always refer to nodeList[i] since the nodes can be replaced underneath us. + directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, + ignoreDirective); + + nodeLinkFn = (directives.length) + ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, + null, [], [], previousCompileContext) + : null; + + if (nodeLinkFn && nodeLinkFn.scope) { + compile.$$addScopeClass(attrs.$$element); + } + + childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !(childNodes = nodeList[i].childNodes) || !childNodes.length) + ? null + : compileNodes(childNodes, + nodeLinkFn ? ( + (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) + && nodeLinkFn.transclude) : transcludeFn); + + if (nodeLinkFn || childLinkFn) { + linkFns.push(i, nodeLinkFn, childLinkFn); + linkFnFound = true; + nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; + } + + //use the previous context only for the first element in the virtual group + previousCompileContext = null; + } + // return a linking function if we have found anything, null otherwise + return linkFnFound ? compositeLinkFn : null; + + function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { + var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; + var stableNodeList; + + + if (nodeLinkFnFound) { + // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our + // offsets don't get screwed up + var nodeListLength = nodeList.length; + stableNodeList = new Array(nodeListLength); + + // create a sparse array by only copying the elements which have a linkFn + for (i = 0; i < linkFns.length; i += 3) { + idx = linkFns[i]; + stableNodeList[idx] = nodeList[idx]; + } + } else { + stableNodeList = nodeList; + } + + for (i = 0, ii = linkFns.length; i < ii;) { + node = stableNodeList[linkFns[i++]]; + nodeLinkFn = linkFns[i++]; + childLinkFn = linkFns[i++]; + + if (nodeLinkFn) { + if (nodeLinkFn.scope) { + childScope = scope.$new(); + compile.$$addScopeInfo(jqLite(node), childScope); + } else { + childScope = scope; + } + + if (nodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn( + scope, nodeLinkFn.transclude, parentBoundTranscludeFn, + nodeLinkFn.elementTranscludeOnThisElement); + + } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { + childBoundTranscludeFn = parentBoundTranscludeFn; + + } else if (!parentBoundTranscludeFn && transcludeFn) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); + + } else { + childBoundTranscludeFn = null; + } + + nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); + + } else if (childLinkFn) { + childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); + } + } + } + } - /** - * @ngdoc method - * @name $compile.directive.Attributes#$observe - * @kind function - * - * @description - * Observes an interpolated attribute. - * - * The observer function will be invoked once during the next `$digest` following - * compilation. The observer is then invoked whenever the interpolated value - * changes. - * - * @param {string} key Normalized key. (ie ngAttribute) . - * @param {function(interpolatedValue)} fn Function that will be called whenever - the interpolated value of the attribute changes. - * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info. - * @returns {function()} Returns a deregistration function for this observer. - */ - $observe: function(key, fn) { - var attrs = this, - $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), - listeners = ($$observers[key] || ($$observers[key] = [])); - - listeners.push(fn); - $rootScope.$evalAsync(function() { - if (!listeners.$$inter) { - // no one registered attribute interpolation function, so lets call it manually - fn(attrs[key]); - } - }); + function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) { - return function() { - arrayRemove(listeners, fn); - }; - } - }; + var boundTranscludeFn = function (transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { + if (!transcludedScope) { + transcludedScope = scope.$new(false, containingScope); + transcludedScope.$$transcluded = true; + } - function safeAddClass($element, className) { - try { - $element.addClass(className); - } catch(e) { - // ignore, since it means that we are trying to set class on - // SVG element, where class name is read-only. - } - } + return transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn, futureParentElement); + }; + return boundTranscludeFn; + } - var startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(), - denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') - ? identity - : function denormalizeTemplate(template) { - return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); - }, - NG_ATTR_BINDING = /^ngAttr[A-Z]/; + /** + * Looks for directives on the given node and adds them to the directive collection which is + * sorted. + * + * @param node Node to search. + * @param directives An array to which the directives are added to. This array is sorted before + * the function returns. + * @param attrs The shared attrs object which is used to populate the normalized attributes. + * @param {number=} maxPriority Max directive priority. + */ + function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { + var nodeType = node.nodeType, + attrsMap = attrs.$attr, + match, + className; + + switch (nodeType) { + case NODE_TYPE_ELEMENT: /* Element */ + // use the node name: + addDirective(directives, + directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective); + + // iterate over the attributes + for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, + j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { + var attrStartName = false; + var attrEndName = false; + + attr = nAttrs[j]; + name = attr.name; + value = trim(attr.value); + + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { + name = snake_case(ngAttrName.substr(6), '-'); + } + + var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); + if (directiveIsMultiElement(directiveNName)) { + if (ngAttrName === directiveNName + 'Start') { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } + } + + nName = directiveNormalize(name.toLowerCase()); + attrsMap[nName] = name; + if (isNgAttr || !attrs.hasOwnProperty(nName)) { + attrs[nName] = value; + if (getBooleanAttrName(node, nName)) { + attrs[nName] = true; // presence means true + } + } + addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, + attrEndName); + } + + // use class as directive + className = node.className; + if (isString(className) && className !== '') { + while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { + nName = directiveNormalize(match[2]); + if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[3]); + } + className = className.substr(match.index + match[0].length); + } + } + break; + case NODE_TYPE_TEXT: /* Text Node */ + addTextInterpolateDirective(directives, node.nodeValue); + break; + case NODE_TYPE_COMMENT: /* Comment */ + try { + match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); + if (match) { + nName = directiveNormalize(match[1]); + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[2]); + } + } + } catch (e) { + // turns out that under some circumstances IE9 throws errors when one attempts to read + // comment's node value. + // Just ignore it and continue. (Can't seem to reproduce in test case.) + } + break; + } - compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { - var bindings = $element.data('$binding') || []; + directives.sort(byPriority); + return directives; + } - if (isArray(binding)) { - bindings = bindings.concat(binding); - } else { - bindings.push(binding); - } + /** + * Given a node with an directive-start it collects all of the siblings until it finds + * directive-end. + * @param node + * @param attrStart + * @param attrEnd + * @returns {*} + */ + function groupScan(node, attrStart, attrEnd) { + var nodes = []; + var depth = 0; + if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { + var startNode = node; + do { + if (!node) { + throw $compileMinErr('uterdir', + "Unterminated attribute, found '{0}' but no matching '{1}' found.", + attrStart, attrEnd); + } + if (node.nodeType == NODE_TYPE_ELEMENT) { + if (node.hasAttribute(attrStart)) depth++; + if (node.hasAttribute(attrEnd)) depth--; + } + nodes.push(node); + node = node.nextSibling; + } while (depth > 0); + } else { + nodes.push(node); + } - $element.data('$binding', bindings); - } : noop; + return jqLite(nodes); + } - compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { - safeAddClass($element, 'ng-binding'); - } : noop; + /** + * Wrapper for linking function which converts normal linking function into a grouped + * linking function. + * @param linkFn + * @param attrStart + * @param attrEnd + * @returns {Function} + */ + function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { + return function (scope, element, attrs, controllers, transcludeFn) { + element = groupScan(element[0], attrStart, attrEnd); + return linkFn(scope, element, attrs, controllers, transcludeFn); + }; + } - compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { - var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; - $element.data(dataName, scope); - } : noop; + /** + * Once the directives have been collected, their compile functions are executed. This method + * is responsible for inlining directive templates as well as terminating the application + * of the directives if the terminal directive has been reached. + * + * @param {Array} directives Array of collected directives to execute their compile function. + * this needs to be pre-sorted by priority order. + * @param {Node} compileNode The raw DOM node to apply the compile functions to + * @param {Object} templateAttrs The shared attribute function + * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the + * scope argument is auto-generated to the new + * child of the transcluded parent scope. + * @param {JQLite} jqCollection If we are working on the root of the compile tree then this + * argument has the root jqLite array so that we can replace nodes + * on it. + * @param {Object=} originalReplaceDirective An optional directive that will be ignored when + * compiling the transclusion. + * @param {Array.} preLinkFns + * @param {Array.} postLinkFns + * @param {Object} previousCompileContext Context used for previous compilation of the current + * node + * @returns {Function} linkFn + */ + function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, + jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, + previousCompileContext) { + previousCompileContext = previousCompileContext || {}; + + var terminalPriority = -Number.MAX_VALUE, + newScopeDirective, + controllerDirectives = previousCompileContext.controllerDirectives, + controllers, + newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, + templateDirective = previousCompileContext.templateDirective, + nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, + hasTranscludeDirective = false, + hasTemplate = false, + hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, + $compileNode = templateAttrs.$$element = jqLite(compileNode), + directive, + directiveName, + $template, + replaceDirective = originalReplaceDirective, + childTranscludeFn = transcludeFn, + linkFn, + directiveValue; + + // executes all directives on the current element + for (var i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + var attrStart = directive.$$start; + var attrEnd = directive.$$end; + + // collect multiblock sections + if (attrStart) { + $compileNode = groupScan(compileNode, attrStart, attrEnd); + } + $template = undefined; + + if (terminalPriority > directive.priority) { + break; // prevent further processing of directives + } + + if (directiveValue = directive.scope) { + + // skip the check for directives with async templates, we'll check the derived sync + // directive when the template arrives + if (!directive.templateUrl) { + if (isObject(directiveValue)) { + // This directive is trying to add an isolated scope. + // Check that there is no scope of any kind already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, + directive, $compileNode); + newIsolateScopeDirective = directive; + } else { + // This directive is trying to add a child scope. + // Check that there is no isolated scope already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, + $compileNode); + } + } + + newScopeDirective = newScopeDirective || directive; + } + + directiveName = directive.name; + + if (!directive.templateUrl && directive.controller) { + directiveValue = directive.controller; + controllerDirectives = controllerDirectives || {}; + assertNoDuplicate("'" + directiveName + "' controller", + controllerDirectives[directiveName], directive, $compileNode); + controllerDirectives[directiveName] = directive; + } + + if (directiveValue = directive.transclude) { + hasTranscludeDirective = true; + + // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. + // This option should only be used by directives that know how to safely handle element transclusion, + // where the transcluded nodes are added or replaced after linking. + if (!directive.$$tlb) { + assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); + nonTlbTranscludeDirective = directive; + } + + if (directiveValue == 'element') { + hasElementTranscludeDirective = true; + terminalPriority = directive.priority; + $template = $compileNode; + $compileNode = templateAttrs.$$element = + jqLite(document.createComment(' ' + directiveName + ': ' + + templateAttrs[directiveName] + ' ')); + compileNode = $compileNode[0]; + replaceWith(jqCollection, sliceArgs($template), compileNode); + + childTranscludeFn = compile($template, transcludeFn, terminalPriority, + replaceDirective && replaceDirective.name, { + // Don't pass in: + // - controllerDirectives - otherwise we'll create duplicates controllers + // - newIsolateScopeDirective or templateDirective - combining templates with + // element transclusion doesn't make sense. + // + // We need only nonTlbTranscludeDirective so that we prevent putting transclusion + // on the same element more than once. + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); + } else { + $template = jqLite(jqLiteClone(compileNode)).contents(); + $compileNode.empty(); // clear contents + childTranscludeFn = compile($template, transcludeFn); + } + } + + if (directive.template) { + hasTemplate = true; + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + directiveValue = (isFunction(directive.template)) + ? directive.template($compileNode, templateAttrs) + : directive.template; + + directiveValue = denormalizeTemplate(directiveValue); + + if (directive.replace) { + replaceDirective = directive; + if (jqLiteIsTextNode(directiveValue)) { + $template = []; + } else { + $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); + } + compileNode = $template[0]; + + if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + directiveName, ''); + } + + replaceWith(jqCollection, $compileNode, compileNode); + + var newTemplateAttrs = {$attr: {}}; + + // combine directives from the original node and from the template: + // - take the array of directives for this element + // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) + // - collect directives from the template and sort them by priority + // - combine directives as: processed + template + unprocessed + var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); + var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); + + if (newIsolateScopeDirective) { + markDirectivesAsIsolate(templateDirectives); + } + directives = directives.concat(templateDirectives).concat(unprocessedDirectives); + mergeTemplateAttributes(templateAttrs, newTemplateAttrs); + + ii = directives.length; + } else { + $compileNode.html(directiveValue); + } + } + + if (directive.templateUrl) { + hasTemplate = true; + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + if (directive.replace) { + replaceDirective = directive; + } + + nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, + templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { + controllerDirectives: controllerDirectives, + newIsolateScopeDirective: newIsolateScopeDirective, + templateDirective: templateDirective, + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); + ii = directives.length; + } else if (directive.compile) { + try { + linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); + if (isFunction(linkFn)) { + addLinkFns(null, linkFn, attrStart, attrEnd); + } else if (linkFn) { + addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); + } + } catch (e) { + $exceptionHandler(e, startingTag($compileNode)); + } + } + + if (directive.terminal) { + nodeLinkFn.terminal = true; + terminalPriority = Math.max(terminalPriority, directive.priority); + } - compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { - safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); - } : noop; + } - return compile; + nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; + nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; + nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective; + nodeLinkFn.templateOnThisElement = hasTemplate; + nodeLinkFn.transclude = childTranscludeFn; + + previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; + + // might be normal or delayed nodeLinkFn depending on if templateUrl is present + return nodeLinkFn; + + //////////////////// + + function addLinkFns(pre, post, attrStart, attrEnd) { + if (pre) { + if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); + pre.require = directive.require; + pre.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + pre = cloneAndAnnotateFn(pre, {isolateScope: true}); + } + preLinkFns.push(pre); + } + if (post) { + if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); + post.require = directive.require; + post.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + post = cloneAndAnnotateFn(post, {isolateScope: true}); + } + postLinkFns.push(post); + } + } - //================================ - function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, - previousCompileContext) { - if (!($compileNodes instanceof jqLite)) { - // jquery always rewraps, whereas we need to preserve the original selector so that we can - // modify it. - $compileNodes = jqLite($compileNodes); - } - // We can not compile top level text elements since text nodes can be merged and we will - // not be able to attach scope data to them, so we will wrap them in - forEach($compileNodes, function(node, index){ - if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = jqLite(node).wrap('').parent()[0]; - } - }); - var compositeLinkFn = - compileNodes($compileNodes, transcludeFn, $compileNodes, - maxPriority, ignoreDirective, previousCompileContext); - compile.$$addScopeClass($compileNodes); - var namespace = null; - return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn, futureParentElement){ - assertArg(scope, 'scope'); - if (!namespace) { - namespace = detectNamespaceForChildElements(futureParentElement); - } - var $linkNode; - if (namespace !== 'html') { - // When using a directive with replace:true and templateUrl the $compileNodes - // (or a child element inside of them) - // might change, so we need to recreate the namespace adapted compileNodes - // for call to the link function. - // Note: This will already clone the nodes... - $linkNode = jqLite( - wrapTemplate(namespace, jqLite('
          ').append($compileNodes).html()) - ); - } else if (cloneConnectFn) { - // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart - // and sometimes changes the structure of the DOM. - $linkNode = JQLitePrototype.clone.call($compileNodes); - } else { - $linkNode = $compileNodes; - } + function getControllers(directiveName, require, $element, elementControllers) { + var value, retrievalMethod = 'data', optional = false; + var $searchElement = $element; + var match; + if (isString(require)) { + match = require.match(REQUIRE_PREFIX_REGEXP); + require = require.substring(match[0].length); + + if (match[3]) { + if (match[1]) match[3] = null; + else match[1] = match[3]; + } + if (match[1] === '^') { + retrievalMethod = 'inheritedData'; + } else if (match[1] === '^^') { + retrievalMethod = 'inheritedData'; + $searchElement = $element.parent(); + } + if (match[2] === '?') { + optional = true; + } + + value = null; + + if (elementControllers && retrievalMethod === 'data') { + if (value = elementControllers[require]) { + value = value.instance; + } + } + value = value || $searchElement[retrievalMethod]('$' + require + 'Controller'); + + if (!value && !optional) { + throw $compileMinErr('ctreq', + "Controller '{0}', required by directive '{1}', can't be found!", + require, directiveName); + } + return value; + } else if (isArray(require)) { + value = []; + forEach(require, function (require) { + value.push(getControllers(directiveName, require, $element, elementControllers)); + }); + } + return value; + } - if (transcludeControllers) { - for (var controllerName in transcludeControllers) { - $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); - } - } - compile.$$addScopeInfo($linkNode, scope); + function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { + var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element, + attrs; + + if (compileNode === linkNode) { + attrs = templateAttrs; + $element = templateAttrs.$$element; + } else { + $element = jqLite(linkNode); + attrs = new Attributes($element, templateAttrs); + } + + if (newIsolateScopeDirective) { + isolateScope = scope.$new(true); + } + + transcludeFn = boundTranscludeFn && controllersBoundTransclude; + if (controllerDirectives) { + // TODO: merge `controllers` and `elementControllers` into single object. + controllers = {}; + elementControllers = {}; + forEach(controllerDirectives, function (directive) { + var locals = { + $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, + $element: $element, + $attrs: attrs, + $transclude: transcludeFn + }, controllerInstance; + + controller = directive.controller; + if (controller == '@') { + controller = attrs[directive.name]; + } + + controllerInstance = $controller(controller, locals, true, directive.controllerAs); + + // For directives with element transclusion the element is a comment, + // but jQuery .data doesn't support attaching data to comment nodes as it's hard to + // clean up (http://bugs.jquery.com/ticket/8335). + // Instead, we save the controllers for the element in a local hash and attach to .data + // later, once we have the actual element. + elementControllers[directive.name] = controllerInstance; + if (!hasElementTranscludeDirective) { + $element.data('$' + directive.name + 'Controller', controllerInstance.instance); + } + + controllers[directive.name] = controllerInstance; + }); + } + + if (newIsolateScopeDirective) { + var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; + + compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || + templateDirective === newIsolateScopeDirective.$$originalDirective))); + compile.$$addScopeClass($element, true); + + var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name]; + var isolateBindingContext = isolateScope; + if (isolateScopeController && isolateScopeController.identifier && + newIsolateScopeDirective.bindToController === true) { + isolateBindingContext = isolateScopeController.instance; + } + + forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function (definition, scopeName) { + var attrName = definition.attrName, + optional = definition.optional, + mode = definition.mode, // @, =, or & + lastValue, + parentGet, parentSet, compare; + + switch (mode) { + + case '@': + attrs.$observe(attrName, function (value) { + isolateBindingContext[scopeName] = value; + }); + attrs.$$observers[attrName].$$scope = scope; + if (attrs[attrName]) { + // If the attribute has been provided then we trigger an interpolation to ensure + // the value is there for use in the link fn + isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope); + } + break; + + case '=': + if (optional && !attrs[attrName]) { + return; + } + parentGet = $parse(attrs[attrName]); + if (parentGet.literal) { + compare = equals; + } else { + compare = function (a, b) { + return a === b || (a !== a && b !== b); + }; + } + parentSet = parentGet.assign || function () { + // reset the change, or we will throw this exception on every $digest + lastValue = isolateBindingContext[scopeName] = parentGet(scope); + throw $compileMinErr('nonassign', + "Expression '{0}' used with directive '{1}' is non-assignable!", + attrs[attrName], newIsolateScopeDirective.name); + }; + lastValue = isolateBindingContext[scopeName] = parentGet(scope); + var parentValueWatch = function parentValueWatch(parentValue) { + if (!compare(parentValue, isolateBindingContext[scopeName])) { + // we are out of sync and need to copy + if (!compare(parentValue, lastValue)) { + // parent changed and it has precedence + isolateBindingContext[scopeName] = parentValue; + } else { + // if the parent can be assigned then do so + parentSet(scope, parentValue = isolateBindingContext[scopeName]); + } + } + return lastValue = parentValue; + }; + parentValueWatch.$stateful = true; + var unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); + isolateScope.$on('$destroy', unwatch); + break; + + case '&': + parentGet = $parse(attrs[attrName]); + isolateBindingContext[scopeName] = function (locals) { + return parentGet(scope, locals); + }; + break; + } + }); + } + if (controllers) { + forEach(controllers, function (controller) { + controller(); + }); + controllers = null; + } + + // PRELINKING + for (i = 0, ii = preLinkFns.length; i < ii; i++) { + linkFn = preLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); + } + + // RECURSION + // We only pass the isolate scope, if the isolate directive has a template, + // otherwise the child elements do not belong to the isolate directive. + var scopeToChild = scope; + if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { + scopeToChild = isolateScope; + } + childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + + // POSTLINKING + for (i = postLinkFns.length - 1; i >= 0; i--) { + linkFn = postLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); + } + + // This is the function that is injected as `$transclude`. + // Note: all arguments are optional! + function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) { + var transcludeControllers; + + // No scope passed in: + if (!isScope(scope)) { + futureParentElement = cloneAttachFn; + cloneAttachFn = scope; + scope = undefined; + } + + if (hasElementTranscludeDirective) { + transcludeControllers = elementControllers; + } + if (!futureParentElement) { + futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; + } + return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + } + } + } + + function markDirectivesAsIsolate(directives) { + // mark all directives as needing isolate scope. + for (var j = 0, jj = directives.length; j < jj; j++) { + directives[j] = inherit(directives[j], {$$isolateScope: true}); + } + } - if (cloneConnectFn) cloneConnectFn($linkNode, scope); - if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); - return $linkNode; - }; - } + /** + * looks up the directive and decorates it with exception handling and proper parameters. We + * call this the boundDirective. + * + * @param {string} name name of the directive to look up. + * @param {string} location The directive must be found in specific format. + * String containing any of theses characters: + * + * * `E`: element name + * * `A': attribute + * * `C`: class + * * `M`: comment + * @returns {boolean} true if directive was added. + */ + function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, + endAttrName) { + if (name === ignoreDirective) return null; + var match = null; + if (hasDirectives.hasOwnProperty(name)) { + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + try { + directive = directives[i]; + if ((maxPriority === undefined || maxPriority > directive.priority) && + directive.restrict.indexOf(location) != -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } + tDirectives.push(directive); + match = directive; + } + } catch (e) { + $exceptionHandler(e); + } + } + } + return match; + } - function detectNamespaceForChildElements(parentElement) { - // TODO: Make this detect MathML as well... - var node = parentElement && parentElement[0]; - if (!node) { - return 'html'; - } else { - return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg': 'html'; - } - } - /** - * Compile function matches each node in nodeList against the directives. Once all directives - * for a particular node are collected their compile functions are executed. The compile - * functions return values - the linking functions - are combined into a composite linking - * function, which is the a linking function for the node. - * - * @param {NodeList} nodeList an array of nodes or NodeList to compile - * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the - * scope argument is auto-generated to the new child of the transcluded parent scope. - * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then - * the rootElement must be set the jqLite collection of the compile root. This is - * needed so that the jqLite collection items can be replaced with widgets. - * @param {number=} maxPriority Max directive priority. - * @returns {Function} A composite linking function of all of the matched directives or null. - */ - function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, - previousCompileContext) { - var linkFns = [], - attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; + /** + * looks up the directive and returns true if it is a multi-element directive, + * and therefore requires DOM nodes between -start and -end markers to be grouped + * together. + * + * @param {string} name name of the directive to look up. + * @returns true if directive was registered as multi-element. + */ + function directiveIsMultiElement(name) { + if (hasDirectives.hasOwnProperty(name)) { + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + if (directive.multiElement) { + return true; + } + } + } + return false; + } - for (var i = 0; i < nodeList.length; i++) { - attrs = new Attributes(); + /** + * When the element is replaced with HTML template then the new attributes + * on the template need to be merged with the existing attributes in the DOM. + * The desired effect is to have both of the attributes present. + * + * @param {object} dst destination attributes (original DOM) + * @param {object} src source attributes (from the directive template) + */ + function mergeTemplateAttributes(dst, src) { + var srcAttr = src.$attr, + dstAttr = dst.$attr, + $element = dst.$$element; + + // reapply the old attributes to the new element + forEach(dst, function (value, key) { + if (key.charAt(0) != '$') { + if (src[key] && src[key] !== value) { + value += (key === 'style' ? ';' : ' ') + src[key]; + } + dst.$set(key, value, true, srcAttr[key]); + } + }); + + // copy the new attributes on the old attrs object + forEach(src, function (value, key) { + if (key == 'class') { + safeAddClass($element, value); + dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; + } else if (key == 'style') { + $element.attr('style', $element.attr('style') + ';' + value); + dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; + // `dst` will never contain hasOwnProperty as DOM parser won't let it. + // You will get an "InvalidCharacterError: DOM Exception 5" error if you + // have an attribute like "has-own-property" or "data-has-own-property", etc. + } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { + dst[key] = value; + dstAttr[key] = srcAttr[key]; + } + }); + } - // we must always refer to nodeList[i] since the nodes can be replaced underneath us. - directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, - ignoreDirective); - nodeLinkFn = (directives.length) - ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, - null, [], [], previousCompileContext) - : null; + function compileTemplateUrl(directives, $compileNode, tAttrs, + $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { + var linkQueue = [], + afterTemplateNodeLinkFn, + afterTemplateChildLinkFn, + beforeTemplateCompileNode = $compileNode[0], + origAsyncDirective = directives.shift(), + // The fact that we have to copy and patch the directive seems wrong! + derivedSyncDirective = extend({}, origAsyncDirective, { + templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective + }), + templateUrl = (isFunction(origAsyncDirective.templateUrl)) + ? origAsyncDirective.templateUrl($compileNode, tAttrs) + : origAsyncDirective.templateUrl, + templateNamespace = origAsyncDirective.templateNamespace; + + $compileNode.empty(); + + $templateRequest($sce.getTrustedResourceUrl(templateUrl)) + .then(function (content) { + var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; + + content = denormalizeTemplate(content); + + if (origAsyncDirective.replace) { + if (jqLiteIsTextNode(content)) { + $template = []; + } else { + $template = removeComments(wrapTemplate(templateNamespace, trim(content))); + } + compileNode = $template[0]; + + if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + origAsyncDirective.name, templateUrl); + } + + tempTemplateAttrs = {$attr: {}}; + replaceWith($rootElement, $compileNode, compileNode); + var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); + + if (isObject(origAsyncDirective.scope)) { + markDirectivesAsIsolate(templateDirectives); + } + directives = templateDirectives.concat(directives); + mergeTemplateAttributes(tAttrs, tempTemplateAttrs); + } else { + compileNode = beforeTemplateCompileNode; + $compileNode.html(content); + } + + directives.unshift(derivedSyncDirective); + + afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, + childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, + previousCompileContext); + forEach($rootElement, function (node, i) { + if (node == compileNode) { + $rootElement[i] = $compileNode[0]; + } + }); + afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); + + while (linkQueue.length) { + var scope = linkQueue.shift(), + beforeTemplateLinkNode = linkQueue.shift(), + linkRootElement = linkQueue.shift(), + boundTranscludeFn = linkQueue.shift(), + linkNode = $compileNode[0]; + + if (scope.$$destroyed) continue; + + if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { + var oldClasses = beforeTemplateLinkNode.className; + + if (!(previousCompileContext.hasElementTranscludeDirective && + origAsyncDirective.replace)) { + // it was cloned therefore we have to clone as well. + linkNode = jqLiteClone(compileNode); + } + replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); + + // Copy in CSS classes from original node + safeAddClass(jqLite(linkNode), oldClasses); + } + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } else { + childBoundTranscludeFn = boundTranscludeFn; + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, + childBoundTranscludeFn); + } + linkQueue = null; + }); + + return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { + var childBoundTranscludeFn = boundTranscludeFn; + if (scope.$$destroyed) return; + if (linkQueue) { + linkQueue.push(scope); + linkQueue.push(node); + linkQueue.push(rootElement); + linkQueue.push(childBoundTranscludeFn); + } else { + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); + } + }; + } - if (nodeLinkFn && nodeLinkFn.scope) { - compile.$$addScopeClass(attrs.$$element); - } - childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || - !(childNodes = nodeList[i].childNodes) || - !childNodes.length) - ? null - : compileNodes(childNodes, - nodeLinkFn ? ( - (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) - && nodeLinkFn.transclude) : transcludeFn); - - if (nodeLinkFn || childLinkFn) { - linkFns.push(i, nodeLinkFn, childLinkFn); - linkFnFound = true; - nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; - } + /** + * Sorting function for bound directives. + */ + function byPriority(a, b) { + var diff = b.priority - a.priority; + if (diff !== 0) return diff; + if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; + return a.index - b.index; + } - //use the previous context only for the first element in the virtual group - previousCompileContext = null; - } - // return a linking function if we have found anything, null otherwise - return linkFnFound ? compositeLinkFn : null; + function assertNoDuplicate(what, previousDirective, directive, element) { + if (previousDirective) { + throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', + previousDirective.name, directive.name, what, startingTag(element)); + } + } - function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { - var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; - var stableNodeList; + function addTextInterpolateDirective(directives, text) { + var interpolateFn = $interpolate(text, true); + if (interpolateFn) { + directives.push({ + priority: 0, + compile: function textInterpolateCompileFn(templateNode) { + var templateNodeParent = templateNode.parent(), + hasCompileParent = !!templateNodeParent.length; + + // When transcluding a template that has bindings in the root + // we don't have a parent and thus need to add the class during linking fn. + if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); + + return function textInterpolateLinkFn(scope, node) { + var parent = node.parent(); + if (!hasCompileParent) compile.$$addBindingClass(parent); + compile.$$addBindingInfo(parent, interpolateFn.expressions); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }; + } + }); + } + } - if (nodeLinkFnFound) { - // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our - // offsets don't get screwed up - var nodeListLength = nodeList.length; - stableNodeList = new Array(nodeListLength); - // create a sparse array by only copying the elements which have a linkFn - for (i = 0; i < linkFns.length; i+=3) { - idx = linkFns[i]; - stableNodeList[idx] = nodeList[idx]; - } - } else { - stableNodeList = nodeList; - } + function wrapTemplate(type, template) { + type = lowercase(type || 'html'); + switch (type) { + case 'svg': + case 'math': + var wrapper = document.createElement('div'); + wrapper.innerHTML = '<' + type + '>' + template + ''; + return wrapper.childNodes[0].childNodes; + default: + return template; + } + } - for(i = 0, ii = linkFns.length; i < ii;) { - node = stableNodeList[linkFns[i++]]; - nodeLinkFn = linkFns[i++]; - childLinkFn = linkFns[i++]; - if (nodeLinkFn) { - if (nodeLinkFn.scope) { - childScope = scope.$new(); - compile.$$addScopeInfo(jqLite(node), childScope); - } else { - childScope = scope; - } + function getTrustedContext(node, attrNormalizedName) { + if (attrNormalizedName == "srcdoc") { + return $sce.HTML; + } + var tag = nodeName_(node); + // maction[xlink:href] can source SVG. It's not limited to . + if (attrNormalizedName == "xlinkHref" || + (tag == "form" && attrNormalizedName == "action") || + (tag != "img" && (attrNormalizedName == "src" || + attrNormalizedName == "ngSrc"))) { + return $sce.RESOURCE_URL; + } + } - if ( nodeLinkFn.transcludeOnThisElement ) { - childBoundTranscludeFn = createBoundTranscludeFn( - scope, nodeLinkFn.transclude, parentBoundTranscludeFn, - nodeLinkFn.elementTranscludeOnThisElement); - } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { - childBoundTranscludeFn = parentBoundTranscludeFn; + function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) { + var interpolateFn = $interpolate(value, true); - } else if (!parentBoundTranscludeFn && transcludeFn) { - childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); + // no interpolation found -> ignore + if (!interpolateFn) return; - } else { - childBoundTranscludeFn = null; - } - nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); + if (name === "multiple" && nodeName_(node) === "select") { + throw $compileMinErr("selmulti", + "Binding to the 'multiple' attribute is not supported. Element: {0}", + startingTag(node)); + } - } else if (childLinkFn) { - childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); - } - } - } - } + directives.push({ + priority: 100, + compile: function () { + return { + pre: function attrInterpolatePreLinkFn(scope, element, attr) { + var $$observers = (attr.$$observers || (attr.$$observers = {})); + + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', + "Interpolations for HTML DOM event attributes are disallowed. Please use the " + + "ng- versions (such as ng-click instead of onclick) instead."); + } + + // If the attribute was removed, then we are done + if (!attr[name]) { + return; + } + + // we need to interpolate again, in case the attribute value has been updated + // (e.g. by another directive's compile function) + interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name), + ALL_OR_NOTHING_ATTRS[name] || allOrNothing); + + // if attribute was updated so that there is no interpolation going on we don't want to + // register any observers + if (!interpolateFn) return; + + // initialize attr object so that it's ready in case we need the value for isolate + // scope initialization, otherwise the value would not be available from isolate + // directive's linking fn during linking phase + attr[name] = interpolateFn(scope); + + ($$observers[name] || ($$observers[name] = [])).$$inter = true; + (attr.$$observers && attr.$$observers[name].$$scope || scope). + $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service. Be sure to + //skip animations when the first digest occurs (when + //both the new and the old values are the same) since + //the CSS classes are the non-interpolated values + if (name === 'class' && newValue != oldValue) { + attr.$updateClass(newValue, oldValue); + } else { + attr.$set(name, newValue); + } + }); + } + }; + } + }); + } - function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) { - var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { + /** + * This is a special jqLite.replaceWith, which can replace items which + * have no parents, provided that the containing jqLite collection is provided. + * + * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes + * in the root of the tree. + * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep + * the shell, but replace its DOM node reference. + * @param {Node} newNode The new DOM node. + */ + function replaceWith($rootElement, elementsToRemove, newNode) { + var firstElementToRemove = elementsToRemove[0], + removeCount = elementsToRemove.length, + parent = firstElementToRemove.parentNode, + i, ii; + + if ($rootElement) { + for (i = 0, ii = $rootElement.length; i < ii; i++) { + if ($rootElement[i] == firstElementToRemove) { + $rootElement[i++] = newNode; + for (var j = i, j2 = j + removeCount - 1, + jj = $rootElement.length; + j < jj; j++, j2++) { + if (j2 < jj) { + $rootElement[j] = $rootElement[j2]; + } else { + delete $rootElement[j]; + } + } + $rootElement.length -= removeCount - 1; + + // If the replaced element is also the jQuery .context then replace it + // .context is a deprecated jQuery api, so we should set it only when jQuery set it + // http://api.jquery.com/context/ + if ($rootElement.context === firstElementToRemove) { + $rootElement.context = newNode; + } + break; + } + } + } - if (!transcludedScope) { - transcludedScope = scope.$new(false, containingScope); - transcludedScope.$$transcluded = true; - } + if (parent) { + parent.replaceChild(newNode, firstElementToRemove); + } - return transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn, futureParentElement); - }; + // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it? + var fragment = document.createDocumentFragment(); + fragment.appendChild(firstElementToRemove); - return boundTranscludeFn; - } + // Copy over user data (that includes Angular's $scope etc.). Don't copy private + // data here because there's no public interface in jQuery to do that and copying over + // event listeners (which is the main use of private data) wouldn't work anyway. + jqLite(newNode).data(jqLite(firstElementToRemove).data()); - /** - * Looks for directives on the given node and adds them to the directive collection which is - * sorted. - * - * @param node Node to search. - * @param directives An array to which the directives are added to. This array is sorted before - * the function returns. - * @param attrs The shared attrs object which is used to populate the normalized attributes. - * @param {number=} maxPriority Max directive priority. - */ - function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { - var nodeType = node.nodeType, - attrsMap = attrs.$attr, - match, - className; - - switch(nodeType) { - case NODE_TYPE_ELEMENT: /* Element */ - // use the node name: - addDirective(directives, - directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective); - - // iterate over the attributes - for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, - j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { - var attrStartName = false; - var attrEndName = false; - - attr = nAttrs[j]; - name = attr.name; - value = trim(attr.value); - - // support ngAttr attribute binding - ngAttrName = directiveNormalize(name); - if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { - name = snake_case(ngAttrName.substr(6), '-'); - } - - var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); - if (directiveIsMultiElement(directiveNName)) { - if (ngAttrName === directiveNName + 'Start') { - attrStartName = name; - attrEndName = name.substr(0, name.length - 5) + 'end'; - name = name.substr(0, name.length - 6); - } - } + // Remove data of the replaced element. We cannot just call .remove() + // on the element it since that would deallocate scope that is needed + // for the new node. Instead, remove the data "manually". + if (!jQuery) { + delete jqLite.cache[firstElementToRemove[jqLite.expando]]; + } else { + // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after + // the replaced element. The cleanData version monkey-patched by Angular would cause + // the scope to be trashed and we do need the very same scope to work with the new + // element. However, we cannot just cache the non-patched version and use it here as + // that would break if another library patches the method after Angular does (one + // example is jQuery UI). Instead, set a flag indicating scope destroying should be + // skipped this one time. + skipDestroyOnNextJQueryCleanData = true; + jQuery.cleanData([firstElementToRemove]); + } + + for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { + var element = elementsToRemove[k]; + jqLite(element).remove(); // must do this way to clean up expando + fragment.appendChild(element); + delete elementsToRemove[k]; + } - nName = directiveNormalize(name.toLowerCase()); - attrsMap[nName] = name; - if (isNgAttr || !attrs.hasOwnProperty(nName)) { - attrs[nName] = value; - if (getBooleanAttrName(node, nName)) { - attrs[nName] = true; // presence means true + elementsToRemove[0] = newNode; + elementsToRemove.length = 1; } - } - addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); - addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, - attrEndName); - } - // use class as directive - className = node.className; - if (isString(className) && className !== '') { - while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { - nName = directiveNormalize(match[2]); - if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[3]); - } - className = className.substr(match.index + match[0].length); - } - } - break; - case NODE_TYPE_TEXT: /* Text Node */ - addTextInterpolateDirective(directives, node.nodeValue); - break; - case NODE_TYPE_COMMENT: /* Comment */ - try { - match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); - if (match) { - nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[2]); - } - } - } catch (e) { - // turns out that under some circumstances IE9 throws errors when one attempts to read - // comment's node value. - // Just ignore it and continue. (Can't seem to reproduce in test case.) - } - break; - } - directives.sort(byPriority); - return directives; - } + function cloneAndAnnotateFn(fn, annotation) { + return extend(function () { + return fn.apply(null, arguments); + }, fn, annotation); + } - /** - * Given a node with an directive-start it collects all of the siblings until it finds - * directive-end. - * @param node - * @param attrStart - * @param attrEnd - * @returns {*} - */ - function groupScan(node, attrStart, attrEnd) { - var nodes = []; - var depth = 0; - if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { - var startNode = node; - do { - if (!node) { - throw $compileMinErr('uterdir', - "Unterminated attribute, found '{0}' but no matching '{1}' found.", - attrStart, attrEnd); - } - if (node.nodeType == NODE_TYPE_ELEMENT) { - if (node.hasAttribute(attrStart)) depth++; - if (node.hasAttribute(attrEnd)) depth--; - } - nodes.push(node); - node = node.nextSibling; - } while (depth > 0); - } else { - nodes.push(node); - } - return jqLite(nodes); + function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { + try { + linkFn(scope, $element, attrs, controllers, transcludeFn); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + }]; } + var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; + /** - * Wrapper for linking function which converts normal linking function into a grouped - * linking function. - * @param linkFn - * @param attrStart - * @param attrEnd - * @returns {Function} + * Converts all accepted directives format into proper directive name. + * All of these will become 'myDirective': + * my:Directive + * my-directive + * x-my-directive + * data-my:directive + * + * Also there is special case for Moz prefix starting with upper case letter. + * @param name Name to normalize */ - function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { - return function(scope, element, attrs, controllers, transcludeFn) { - element = groupScan(element[0], attrStart, attrEnd); - return linkFn(scope, element, attrs, controllers, transcludeFn); - }; + function directiveNormalize(name) { + return camelCase(name.replace(PREFIX_REGEXP, '')); } /** - * Once the directives have been collected, their compile functions are executed. This method - * is responsible for inlining directive templates as well as terminating the application - * of the directives if the terminal directive has been reached. - * - * @param {Array} directives Array of collected directives to execute their compile function. - * this needs to be pre-sorted by priority order. - * @param {Node} compileNode The raw DOM node to apply the compile functions to - * @param {Object} templateAttrs The shared attribute function - * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the - * scope argument is auto-generated to the new - * child of the transcluded parent scope. - * @param {JQLite} jqCollection If we are working on the root of the compile tree then this - * argument has the root jqLite array so that we can replace nodes - * on it. - * @param {Object=} originalReplaceDirective An optional directive that will be ignored when - * compiling the transclusion. - * @param {Array.} preLinkFns - * @param {Array.} postLinkFns - * @param {Object} previousCompileContext Context used for previous compilation of the current - * node - * @returns {Function} linkFn + * @ngdoc type + * @name $compile.directive.Attributes + * + * @description + * A shared object between directive compile / linking functions which contains normalized DOM + * element attributes. The values reflect current binding state `{{ }}`. The normalization is + * needed since all of these are treated as equivalent in Angular: + * + * ``` + * + * ``` */ - function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, - jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, - previousCompileContext) { - previousCompileContext = previousCompileContext || {}; - - var terminalPriority = -Number.MAX_VALUE, - newScopeDirective, - controllerDirectives = previousCompileContext.controllerDirectives, - controllers, - newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, - templateDirective = previousCompileContext.templateDirective, - nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, - hasTranscludeDirective = false, - hasTemplate = false, - hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, - $compileNode = templateAttrs.$$element = jqLite(compileNode), - directive, - directiveName, - $template, - replaceDirective = originalReplaceDirective, - childTranscludeFn = transcludeFn, - linkFn, - directiveValue; - - // executes all directives on the current element - for(var i = 0, ii = directives.length; i < ii; i++) { - directive = directives[i]; - var attrStart = directive.$$start; - var attrEnd = directive.$$end; - - // collect multiblock sections - if (attrStart) { - $compileNode = groupScan(compileNode, attrStart, attrEnd); - } - $template = undefined; - - if (terminalPriority > directive.priority) { - break; // prevent further processing of directives - } - - if (directiveValue = directive.scope) { - - // skip the check for directives with async templates, we'll check the derived sync - // directive when the template arrives - if (!directive.templateUrl) { - if (isObject(directiveValue)) { - // This directive is trying to add an isolated scope. - // Check that there is no scope of any kind already - assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, - directive, $compileNode); - newIsolateScopeDirective = directive; - } else { - // This directive is trying to add a child scope. - // Check that there is no isolated scope already - assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, - $compileNode); - } - } - - newScopeDirective = newScopeDirective || directive; - } - directiveName = directive.name; - - if (!directive.templateUrl && directive.controller) { - directiveValue = directive.controller; - controllerDirectives = controllerDirectives || {}; - assertNoDuplicate("'" + directiveName + "' controller", - controllerDirectives[directiveName], directive, $compileNode); - controllerDirectives[directiveName] = directive; - } + /** + * @ngdoc property + * @name $compile.directive.Attributes#$attr + * + * @description + * A map of DOM element attribute names to the normalized name. This is + * needed to do reverse lookup from normalized name back to actual name. + */ - if (directiveValue = directive.transclude) { - hasTranscludeDirective = true; - // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. - // This option should only be used by directives that know how to safely handle element transclusion, - // where the transcluded nodes are added or replaced after linking. - if (!directive.$$tlb) { - assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); - nonTlbTranscludeDirective = directive; - } + /** + * @ngdoc method + * @name $compile.directive.Attributes#$set + * @kind function + * + * @description + * Set DOM element attribute value. + * + * + * @param {string} name Normalized element attribute name of the property to modify. The name is + * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} + * property to the original name. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. + */ - if (directiveValue == 'element') { - hasElementTranscludeDirective = true; - terminalPriority = directive.priority; - $template = $compileNode; - $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + - templateAttrs[directiveName] + ' ')); - compileNode = $compileNode[0]; - replaceWith(jqCollection, sliceArgs($template), compileNode); - - childTranscludeFn = compile($template, transcludeFn, terminalPriority, - replaceDirective && replaceDirective.name, { - // Don't pass in: - // - controllerDirectives - otherwise we'll create duplicates controllers - // - newIsolateScopeDirective or templateDirective - combining templates with - // element transclusion doesn't make sense. - // - // We need only nonTlbTranscludeDirective so that we prevent putting transclusion - // on the same element more than once. - nonTlbTranscludeDirective: nonTlbTranscludeDirective - }); - } else { - $template = jqLite(jqLiteClone(compileNode)).contents(); - $compileNode.empty(); // clear contents - childTranscludeFn = compile($template, transcludeFn); - } - } - if (directive.template) { - hasTemplate = true; - assertNoDuplicate('template', templateDirective, directive, $compileNode); - templateDirective = directive; + /** + * Closure compiler type information + */ - directiveValue = (isFunction(directive.template)) - ? directive.template($compileNode, templateAttrs) - : directive.template; + function nodesetLinkingFn(/* angular.Scope */ scope, + /* NodeList */ nodeList, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn) { + } - directiveValue = denormalizeTemplate(directiveValue); + function directiveLinkingFn(/* nodesetLinkingFn */ nodesetLinkingFn, + /* angular.Scope */ scope, + /* Node */ node, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn) { + } - if (directive.replace) { - replaceDirective = directive; - if (jqLiteIsTextNode(directiveValue)) { - $template = []; - } else { - $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); - } - compileNode = $template[0]; + function tokenDifference(str1, str2) { + var values = '', + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); - if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { - throw $compileMinErr('tplrt', - "Template for directive '{0}' must have exactly one root element. {1}", - directiveName, ''); + outer: + for (var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for (var j = 0; j < tokens2.length; j++) { + if (token == tokens2[j]) continue outer; + } + values += (values.length > 0 ? ' ' : '') + token; } + return values; + } - replaceWith(jqCollection, $compileNode, compileNode); - - var newTemplateAttrs = {$attr: {}}; + function removeComments(jqNodes) { + jqNodes = jqLite(jqNodes); + var i = jqNodes.length; - // combine directives from the original node and from the template: - // - take the array of directives for this element - // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) - // - collect directives from the template and sort them by priority - // - combine directives as: processed + template + unprocessed - var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); - var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); + if (i <= 1) { + return jqNodes; + } - if (newIsolateScopeDirective) { - markDirectivesAsIsolate(templateDirectives); + while (i--) { + var node = jqNodes[i]; + if (node.nodeType === NODE_TYPE_COMMENT) { + splice.call(jqNodes, i, 1); } - directives = directives.concat(templateDirectives).concat(unprocessedDirectives); - mergeTemplateAttributes(templateAttrs, newTemplateAttrs); - - ii = directives.length; - } else { - $compileNode.html(directiveValue); - } } + return jqNodes; + } - if (directive.templateUrl) { - hasTemplate = true; - assertNoDuplicate('template', templateDirective, directive, $compileNode); - templateDirective = directive; + /** + * @ngdoc provider + * @name $controllerProvider + * @description + * The {@link ng.$controller $controller service} is used by Angular to create new + * controllers. + * + * This provider allows controller registration via the + * {@link ng.$controllerProvider#register register} method. + */ + function $ControllerProvider() { + var controllers = {}, + globals = false, + CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; - if (directive.replace) { - replaceDirective = directive; - } - nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, - templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { - controllerDirectives: controllerDirectives, - newIsolateScopeDirective: newIsolateScopeDirective, - templateDirective: templateDirective, - nonTlbTranscludeDirective: nonTlbTranscludeDirective - }); - ii = directives.length; - } else if (directive.compile) { - try { - linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); - if (isFunction(linkFn)) { - addLinkFns(null, linkFn, attrStart, attrEnd); - } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); - } - } catch (e) { - $exceptionHandler(e, startingTag($compileNode)); - } - } + /** + * @ngdoc method + * @name $controllerProvider#register + * @param {string|Object} name Controller name, or an object map of controllers where the keys are + * the names and the values are the constructors. + * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI + * annotations in the array notation). + */ + this.register = function (name, constructor) { + assertNotHasOwnProperty(name, 'controller'); + if (isObject(name)) { + extend(controllers, name); + } else { + controllers[name] = constructor; + } + }; - if (directive.terminal) { - nodeLinkFn.terminal = true; - terminalPriority = Math.max(terminalPriority, directive.priority); - } + /** + * @ngdoc method + * @name $controllerProvider#allowGlobals + * @description If called, allows `$controller` to find controller constructors on `window` + */ + this.allowGlobals = function () { + globals = true; + }; - } - nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; - nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; - nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective; - nodeLinkFn.templateOnThisElement = hasTemplate; - nodeLinkFn.transclude = childTranscludeFn; + this.$get = ['$injector', '$window', function ($injector, $window) { + + /** + * @ngdoc service + * @name $controller + * @requires $injector + * + * @param {Function|string} constructor If called with a function then it's considered to be the + * controller constructor function. Otherwise it's considered to be a string which is used + * to retrieve the controller constructor using the following steps: + * + * * check if a controller with given name is registered via `$controllerProvider` + * * check if evaluating the string on the current scope returns a constructor + * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global + * `window` object (not recommended) + * + * @param {Object} locals Injection locals for Controller. + * @return {Object} Instance of given controller. + * + * @description + * `$controller` service is responsible for instantiating controllers. + * + * It's just a simple call to {@link auto.$injector $injector}, but extracted into + * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). + */ + return function (expression, locals, later, ident) { + // PRIVATE API: + // param `later` --- indicates that the controller's constructor is invoked at a later time. + // If true, $controller will allocate the object with the correct + // prototype chain, but will not invoke the controller until a returned + // callback is invoked. + // param `ident` --- An optional label which overrides the label parsed from the controller + // expression, if any. + var instance, match, constructor, identifier; + later = later === true; + if (ident && isString(ident)) { + identifier = ident; + } - previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; + if (isString(expression)) { + match = expression.match(CNTRL_REG), + constructor = match[1], + identifier = identifier || match[3]; + expression = controllers.hasOwnProperty(constructor) + ? controllers[constructor] + : getter(locals.$scope, constructor, true) || + (globals ? getter($window, constructor, true) : undefined); - // might be normal or delayed nodeLinkFn depending on if templateUrl is present - return nodeLinkFn; + assertArgFn(expression, constructor, true); + } - //////////////////// + if (later) { + // Instantiate controller later: + // This machinery is used to create an instance of the object before calling the + // controller's constructor itself. + // + // This allows properties to be added to the controller before the constructor is + // invoked. Primarily, this is used for isolate scope bindings in $compile. + // + // This feature is not intended for use by applications, and is thus not documented + // publicly. + var Constructor = function () { + }; + Constructor.prototype = (isArray(expression) ? + expression[expression.length - 1] : expression).prototype; + instance = new Constructor(); + + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); + } - function addLinkFns(pre, post, attrStart, attrEnd) { - if (pre) { - if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); - pre.require = directive.require; - pre.directiveName = directiveName; - if (newIsolateScopeDirective === directive || directive.$$isolateScope) { - pre = cloneAndAnnotateFn(pre, {isolateScope: true}); - } - preLinkFns.push(pre); - } - if (post) { - if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); - post.require = directive.require; - post.directiveName = directiveName; - if (newIsolateScopeDirective === directive || directive.$$isolateScope) { - post = cloneAndAnnotateFn(post, {isolateScope: true}); - } - postLinkFns.push(post); - } - } + return extend(function () { + $injector.invoke(expression, instance, locals, constructor); + return instance; + }, { + instance: instance, + identifier: identifier + }); + } + instance = $injector.instantiate(expression, locals, constructor); - function getControllers(directiveName, require, $element, elementControllers) { - var value, retrievalMethod = 'data', optional = false; - var $searchElement = $element; - var match; - if (isString(require)) { - match = require.match(REQUIRE_PREFIX_REGEXP); - require = require.substring(match[0].length); + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); + } - if (match[3]) { - if (match[1]) match[3] = null; - else match[1] = match[3]; - } - if (match[1] === '^') { - retrievalMethod = 'inheritedData'; - } else if (match[1] === '^^') { - retrievalMethod = 'inheritedData'; - $searchElement = $element.parent(); - } - if (match[2] === '?') { - optional = true; - } + return instance; + }; - value = null; + function addIdentifier(locals, identifier, instance, name) { + if (!(locals && isObject(locals.$scope))) { + throw minErr('$controller')('noscp', + "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", + name, identifier); + } - if (elementControllers && retrievalMethod === 'data') { - if (value = elementControllers[require]) { - value = value.instance; + locals.$scope[identifier] = instance; } - } - value = value || $searchElement[retrievalMethod]('$' + require + 'Controller'); - - if (!value && !optional) { - throw $compileMinErr('ctreq', - "Controller '{0}', required by directive '{1}', can't be found!", - require, directiveName); - } - return value; - } else if (isArray(require)) { - value = []; - forEach(require, function(require) { - value.push(getControllers(directiveName, require, $element, elementControllers)); - }); - } - return value; - } - - - function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element, - attrs; - - if (compileNode === linkNode) { - attrs = templateAttrs; - $element = templateAttrs.$$element; - } else { - $element = jqLite(linkNode); - attrs = new Attributes($element, templateAttrs); - } - - if (newIsolateScopeDirective) { - isolateScope = scope.$new(true); - } - - transcludeFn = boundTranscludeFn && controllersBoundTransclude; - if (controllerDirectives) { - // TODO: merge `controllers` and `elementControllers` into single object. - controllers = {}; - elementControllers = {}; - forEach(controllerDirectives, function(directive) { - var locals = { - $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, - $element: $element, - $attrs: attrs, - $transclude: transcludeFn - }, controllerInstance; - - controller = directive.controller; - if (controller == '@') { - controller = attrs[directive.name]; - } - - controllerInstance = $controller(controller, locals, true, directive.controllerAs); - - // For directives with element transclusion the element is a comment, - // but jQuery .data doesn't support attaching data to comment nodes as it's hard to - // clean up (http://bugs.jquery.com/ticket/8335). - // Instead, we save the controllers for the element in a local hash and attach to .data - // later, once we have the actual element. - elementControllers[directive.name] = controllerInstance; - if (!hasElementTranscludeDirective) { - $element.data('$' + directive.name + 'Controller', controllerInstance.instance); - } - - controllers[directive.name] = controllerInstance; - }); - } - - if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; - - compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || - templateDirective === newIsolateScopeDirective.$$originalDirective))); - compile.$$addScopeClass($element, true); - - var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name]; - var isolateBindingContext = isolateScope; - if (isolateScopeController && isolateScopeController.identifier && - newIsolateScopeDirective.bindToController === true) { - isolateBindingContext = isolateScopeController.instance; - } - - forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) { - var attrName = definition.attrName, - optional = definition.optional, - mode = definition.mode, // @, =, or & - lastValue, - parentGet, parentSet, compare; - - switch (mode) { - - case '@': - attrs.$observe(attrName, function(value) { - isolateBindingContext[scopeName] = value; - }); - attrs.$$observers[attrName].$$scope = scope; - if( attrs[attrName] ) { - // If the attribute has been provided then we trigger an interpolation to ensure - // the value is there for use in the link fn - isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope); - } - break; - - case '=': - if (optional && !attrs[attrName]) { - return; - } - parentGet = $parse(attrs[attrName]); - if (parentGet.literal) { - compare = equals; - } else { - compare = function(a,b) { return a === b || (a !== a && b !== b); }; - } - parentSet = parentGet.assign || function() { - // reset the change, or we will throw this exception on every $digest - lastValue = isolateBindingContext[scopeName] = parentGet(scope); - throw $compileMinErr('nonassign', - "Expression '{0}' used with directive '{1}' is non-assignable!", - attrs[attrName], newIsolateScopeDirective.name); - }; - lastValue = isolateBindingContext[scopeName] = parentGet(scope); - var parentValueWatch = function parentValueWatch(parentValue) { - if (!compare(parentValue, isolateBindingContext[scopeName])) { - // we are out of sync and need to copy - if (!compare(parentValue, lastValue)) { - // parent changed and it has precedence - isolateBindingContext[scopeName] = parentValue; - } else { - // if the parent can be assigned then do so - parentSet(scope, parentValue = isolateBindingContext[scopeName]); - } - } - return lastValue = parentValue; - }; - parentValueWatch.$stateful = true; - var unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); - isolateScope.$on('$destroy', unwatch); - break; - - case '&': - parentGet = $parse(attrs[attrName]); - isolateBindingContext[scopeName] = function(locals) { - return parentGet(scope, locals); - }; - break; - } - }); - } - if (controllers) { - forEach(controllers, function(controller) { - controller(); - }); - controllers = null; - } - - // PRELINKING - for(i = 0, ii = preLinkFns.length; i < ii; i++) { - linkFn = preLinkFns[i]; - invokeLinkFn(linkFn, - linkFn.isolateScope ? isolateScope : scope, - $element, - attrs, - linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), - transcludeFn - ); - } - - // RECURSION - // We only pass the isolate scope, if the isolate directive has a template, - // otherwise the child elements do not belong to the isolate directive. - var scopeToChild = scope; - if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { - scopeToChild = isolateScope; - } - childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); - - // POSTLINKING - for(i = postLinkFns.length - 1; i >= 0; i--) { - linkFn = postLinkFns[i]; - invokeLinkFn(linkFn, - linkFn.isolateScope ? isolateScope : scope, - $element, - attrs, - linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), - transcludeFn - ); - } - - // This is the function that is injected as `$transclude`. - // Note: all arguments are optional! - function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) { - var transcludeControllers; - - // No scope passed in: - if (!isScope(scope)) { - futureParentElement = cloneAttachFn; - cloneAttachFn = scope; - scope = undefined; - } - - if (hasElementTranscludeDirective) { - transcludeControllers = elementControllers; - } - if (!futureParentElement) { - futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; - } - return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); - } - } - } - - function markDirectivesAsIsolate(directives) { - // mark all directives as needing isolate scope. - for (var j = 0, jj = directives.length; j < jj; j++) { - directives[j] = inherit(directives[j], {$$isolateScope: true}); - } - } - - /** - * looks up the directive and decorates it with exception handling and proper parameters. We - * call this the boundDirective. - * - * @param {string} name name of the directive to look up. - * @param {string} location The directive must be found in specific format. - * String containing any of theses characters: - * - * * `E`: element name - * * `A': attribute - * * `C`: class - * * `M`: comment - * @returns {boolean} true if directive was added. - */ - function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, - endAttrName) { - if (name === ignoreDirective) return null; - var match = null; - if (hasDirectives.hasOwnProperty(name)) { - for(var directive, directives = $injector.get(name + Suffix), - i = 0, ii = directives.length; i directive.priority) && - directive.restrict.indexOf(location) != -1) { - if (startAttrName) { - directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); - } - tDirectives.push(directive); - match = directive; - } - } catch(e) { $exceptionHandler(e); } - } - } - return match; - } + }]; + } + /** + * @ngdoc service + * @name $document + * @requires $window + * + * @description + * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. + * + * @example + + +
          +

          $document title:

          +

          window.document title:

          +
          +
          + + angular.module('documentExample', []) + .controller('ExampleController', ['$scope', '$document', function($scope, $document) { + $scope.title = $document[0].title; + $scope.windowTitle = angular.element(window.document)[0].title; + }]); + +
          + */ + function $DocumentProvider() { + this.$get = ['$window', function (window) { + return jqLite(window.document); + }]; + } /** - * looks up the directive and returns true if it is a multi-element directive, - * and therefore requires DOM nodes between -start and -end markers to be grouped - * together. + * @ngdoc service + * @name $exceptionHandler + * @requires ng.$log + * + * @description + * Any uncaught exception in angular expressions is delegated to this service. + * The default implementation simply delegates to `$log.error` which logs it into + * the browser console. + * + * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by + * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. + * + * ## Example: + * + * ```js + * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { + * return function (exception, cause) { + * exception.message += ' (caused by "' + cause + '")'; + * throw exception; + * }; + * }); + * ``` + * + * This example will override the normal action of `$exceptionHandler`, to make angular + * exceptions fail hard when they happen, instead of just logging to the console. + * + *
          + * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` + * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} + * (unless executed during a digest). + * + * If you wish, you can manually delegate exceptions, e.g. + * `try { ... } catch(e) { $exceptionHandler(e); }` + * + * @param {Error} exception Exception associated with the error. + * @param {string=} cause optional information about the context in which + * the error was thrown. * - * @param {string} name name of the directive to look up. - * @returns true if directive was registered as multi-element. */ - function directiveIsMultiElement(name) { - if (hasDirectives.hasOwnProperty(name)) { - for(var directive, directives = $injector.get(name + Suffix), - i = 0, ii = directives.length; i'+template+''; - return wrapper.childNodes[0].childNodes; - default: - return template; - } - } - + function headersGetter(headers) { + var headersObj = isObject(headers) ? headers : undefined; - function getTrustedContext(node, attrNormalizedName) { - if (attrNormalizedName == "srcdoc") { - return $sce.HTML; - } - var tag = nodeName_(node); - // maction[xlink:href] can source SVG. It's not limited to . - if (attrNormalizedName == "xlinkHref" || - (tag == "form" && attrNormalizedName == "action") || - (tag != "img" && (attrNormalizedName == "src" || - attrNormalizedName == "ngSrc"))) { - return $sce.RESOURCE_URL; - } - } - - - function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) { - var interpolateFn = $interpolate(value, true); - - // no interpolation found -> ignore - if (!interpolateFn) return; - - - if (name === "multiple" && nodeName_(node) === "select") { - throw $compileMinErr("selmulti", - "Binding to the 'multiple' attribute is not supported. Element: {0}", - startingTag(node)); - } - - directives.push({ - priority: 100, - compile: function() { - return { - pre: function attrInterpolatePreLinkFn(scope, element, attr) { - var $$observers = (attr.$$observers || (attr.$$observers = {})); - - if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { - throw $compileMinErr('nodomevents', - "Interpolations for HTML DOM event attributes are disallowed. Please use the " + - "ng- versions (such as ng-click instead of onclick) instead."); - } + return function (name) { + if (!headersObj) headersObj = parseHeaders(headers); - // If the attribute was removed, then we are done - if (!attr[name]) { - return; - } + if (name) { + return headersObj[lowercase(name)] || null; + } - // we need to interpolate again, in case the attribute value has been updated - // (e.g. by another directive's compile function) - interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name), - ALL_OR_NOTHING_ATTRS[name] || allOrNothing); - - // if attribute was updated so that there is no interpolation going on we don't want to - // register any observers - if (!interpolateFn) return; - - // initialize attr object so that it's ready in case we need the value for isolate - // scope initialization, otherwise the value would not be available from isolate - // directive's linking fn during linking phase - attr[name] = interpolateFn(scope); - - ($$observers[name] || ($$observers[name] = [])).$$inter = true; - (attr.$$observers && attr.$$observers[name].$$scope || scope). - $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { - //special case for class attribute addition + removal - //so that class changes can tap into the animation - //hooks provided by the $animate service. Be sure to - //skip animations when the first digest occurs (when - //both the new and the old values are the same) since - //the CSS classes are the non-interpolated values - if(name === 'class' && newValue != oldValue) { - attr.$updateClass(newValue, oldValue); - } else { - attr.$set(name, newValue); - } - }); - } - }; - } - }); + return headersObj; + }; } /** - * This is a special jqLite.replaceWith, which can replace items which - * have no parents, provided that the containing jqLite collection is provided. - * - * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes - * in the root of the tree. - * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep - * the shell, but replace its DOM node reference. - * @param {Node} newNode The new DOM node. + * Chain all given functions + * + * This function is used for both request and response transforming + * + * @param {*} data Data to transform. + * @param {function(string=)} headers Http headers getter fn. + * @param {(Function|Array.)} fns Function or an array of functions. + * @returns {*} Transformed data. */ - function replaceWith($rootElement, elementsToRemove, newNode) { - var firstElementToRemove = elementsToRemove[0], - removeCount = elementsToRemove.length, - parent = firstElementToRemove.parentNode, - i, ii; - - if ($rootElement) { - for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == firstElementToRemove) { - $rootElement[i++] = newNode; - for (var j = i, j2 = j + removeCount - 1, - jj = $rootElement.length; - j < jj; j++, j2++) { - if (j2 < jj) { - $rootElement[j] = $rootElement[j2]; - } else { - delete $rootElement[j]; - } - } - $rootElement.length -= removeCount - 1; - - // If the replaced element is also the jQuery .context then replace it - // .context is a deprecated jQuery api, so we should set it only when jQuery set it - // http://api.jquery.com/context/ - if ($rootElement.context === firstElementToRemove) { - $rootElement.context = newNode; - } - break; - } - } - } - - if (parent) { - parent.replaceChild(newNode, firstElementToRemove); - } - - // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it? - var fragment = document.createDocumentFragment(); - fragment.appendChild(firstElementToRemove); - - // Copy over user data (that includes Angular's $scope etc.). Don't copy private - // data here because there's no public interface in jQuery to do that and copying over - // event listeners (which is the main use of private data) wouldn't work anyway. - jqLite(newNode).data(jqLite(firstElementToRemove).data()); - - // Remove data of the replaced element. We cannot just call .remove() - // on the element it since that would deallocate scope that is needed - // for the new node. Instead, remove the data "manually". - if (!jQuery) { - delete jqLite.cache[firstElementToRemove[jqLite.expando]]; - } else { - // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after - // the replaced element. The cleanData version monkey-patched by Angular would cause - // the scope to be trashed and we do need the very same scope to work with the new - // element. However, we cannot just cache the non-patched version and use it here as - // that would break if another library patches the method after Angular does (one - // example is jQuery UI). Instead, set a flag indicating scope destroying should be - // skipped this one time. - skipDestroyOnNextJQueryCleanData = true; - jQuery.cleanData([firstElementToRemove]); - } - - for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { - var element = elementsToRemove[k]; - jqLite(element).remove(); // must do this way to clean up expando - fragment.appendChild(element); - delete elementsToRemove[k]; - } - - elementsToRemove[0] = newNode; - elementsToRemove.length = 1; - } + function transformData(data, headers, fns) { + if (isFunction(fns)) + return fns(data, headers); + forEach(fns, function (fn) { + data = fn(data, headers); + }); - function cloneAndAnnotateFn(fn, annotation) { - return extend(function() { return fn.apply(null, arguments); }, fn, annotation); + return data; } - function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { - try { - linkFn(scope, $element, attrs, controllers, transcludeFn); - } catch(e) { - $exceptionHandler(e, startingTag($element)); - } + function isSuccess(status) { + return 200 <= status && status < 300; } - }]; -} - -var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; -/** - * Converts all accepted directives format into proper directive name. - * All of these will become 'myDirective': - * my:Directive - * my-directive - * x-my-directive - * data-my:directive - * - * Also there is special case for Moz prefix starting with upper case letter. - * @param name Name to normalize - */ -function directiveNormalize(name) { - return camelCase(name.replace(PREFIX_REGEXP, '')); -} - -/** - * @ngdoc type - * @name $compile.directive.Attributes - * - * @description - * A shared object between directive compile / linking functions which contains normalized DOM - * element attributes. The values reflect current binding state `{{ }}`. The normalization is - * needed since all of these are treated as equivalent in Angular: - * - * ``` - * - * ``` - */ - -/** - * @ngdoc property - * @name $compile.directive.Attributes#$attr - * - * @description - * A map of DOM element attribute names to the normalized name. This is - * needed to do reverse lookup from normalized name back to actual name. - */ -/** - * @ngdoc method - * @name $compile.directive.Attributes#$set - * @kind function - * - * @description - * Set DOM element attribute value. - * - * - * @param {string} name Normalized element attribute name of the property to modify. The name is - * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} - * property to the original name. - * @param {string} value Value to set the attribute to. The value can be an interpolated string. - */ + /** + * @ngdoc provider + * @name $httpProvider + * @description + * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. + * */ + function $HttpProvider() { + var JSON_START = /^\s*(\[|\{[^\{])/, + JSON_END = /[\}\]]\s*$/, + PROTECTION_PREFIX = /^\)\]\}',?\n/, + APPLICATION_JSON = 'application/json', + CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; + /** + * @ngdoc property + * @name $httpProvider#defaults + * @description + * + * Object containing default values for all {@link ng.$http $http} requests. + * + * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. + * Defaults value is `'XSRF-TOKEN'`. + * + * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the + * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. + * + * - **`defaults.headers`** - {Object} - Default headers for all $http requests. + * Refer to {@link ng.$http#setting-http-headers $http} for documentation on + * setting default headers. + * - **`defaults.headers.common`** + * - **`defaults.headers.post`** + * - **`defaults.headers.put`** + * - **`defaults.headers.patch`** + **/ + var defaults = this.defaults = { + // transform incoming response data + transformResponse: [function defaultHttpResponseTransform(data, headers) { + if (isString(data)) { + // strip json vulnerability protection prefix + data = data.replace(PROTECTION_PREFIX, ''); + var contentType = headers('Content-Type'); + if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0) || + (JSON_START.test(data) && JSON_END.test(data))) { + data = fromJson(data); + } + } + return data; + }], + + // transform outgoing request data + transformRequest: [function (d) { + return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; + }], + + // default headers + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + }, + post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) + }, + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN' + }; -/** - * Closure compiler type information - */ + var useApplyAsync = false; + /** + * @ngdoc method + * @name $httpProvider#useApplyAsync + * @description + * + * Configure $http service to combine processing of multiple http responses received at around + * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in + * significant performance improvement for bigger applications that make many HTTP requests + * concurrently (common during application bootstrap). + * + * Defaults to false. If no value is specifed, returns the current configured value. + * + * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred + * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window + * to load and share the same digest cycle. + * + * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. + * otherwise, returns the current configured value. + **/ + this.useApplyAsync = function (value) { + if (isDefined(value)) { + useApplyAsync = !!value; + return this; + } + return useApplyAsync; + }; -function nodesetLinkingFn( - /* angular.Scope */ scope, - /* NodeList */ nodeList, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn -){} - -function directiveLinkingFn( - /* nodesetLinkingFn */ nodesetLinkingFn, - /* angular.Scope */ scope, - /* Node */ node, - /* Element */ rootElement, - /* function(Function) */ boundTranscludeFn -){} - -function tokenDifference(str1, str2) { - var values = '', - tokens1 = str1.split(/\s+/), - tokens2 = str2.split(/\s+/); - - outer: - for(var i = 0; i < tokens1.length; i++) { - var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; - } - values += (values.length > 0 ? ' ' : '') + token; - } - return values; -} - -function removeComments(jqNodes) { - jqNodes = jqLite(jqNodes); - var i = jqNodes.length; - - if (i <= 1) { - return jqNodes; - } - - while (i--) { - var node = jqNodes[i]; - if (node.nodeType === NODE_TYPE_COMMENT) { - splice.call(jqNodes, i, 1); - } - } - return jqNodes; -} + /** + * Are ordered by request, i.e. they are applied in the same order as the + * array, on request, but reverse order, on response. + */ + var interceptorFactories = this.interceptors = []; -/** - * @ngdoc provider - * @name $controllerProvider - * @description - * The {@link ng.$controller $controller service} is used by Angular to create new - * controllers. - * - * This provider allows controller registration via the - * {@link ng.$controllerProvider#register register} method. - */ -function $ControllerProvider() { - var controllers = {}, - globals = false, - CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; - - - /** - * @ngdoc method - * @name $controllerProvider#register - * @param {string|Object} name Controller name, or an object map of controllers where the keys are - * the names and the values are the constructors. - * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI - * annotations in the array notation). - */ - this.register = function(name, constructor) { - assertNotHasOwnProperty(name, 'controller'); - if (isObject(name)) { - extend(controllers, name); - } else { - controllers[name] = constructor; - } - }; + this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', + function ($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { - /** - * @ngdoc method - * @name $controllerProvider#allowGlobals - * @description If called, allows `$controller` to find controller constructors on `window` - */ - this.allowGlobals = function() { - globals = true; - }; + var defaultCache = $cacheFactory('$http'); + /** + * Interceptors stored in reverse order. Inner interceptors before outer interceptors. + * The reversal is needed so that we can build up the interception chain around the + * server request. + */ + var reversedInterceptors = []; - this.$get = ['$injector', '$window', function($injector, $window) { + forEach(interceptorFactories, function (interceptorFactory) { + reversedInterceptors.unshift(isString(interceptorFactory) + ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); + }); - /** - * @ngdoc service - * @name $controller - * @requires $injector + /** + * @ngdoc service + * @kind function + * @name $http + * @requires ng.$httpBackend + * @requires $cacheFactory + * @requires $rootScope + * @requires $q + * @requires $injector + * + * @description + * The `$http` service is a core Angular service that facilitates communication with the remote + * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) + * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). + * + * For unit testing applications that use `$http` service, see + * {@link ngMock.$httpBackend $httpBackend mock}. + * + * For a higher level of abstraction, please check out the {@link ngResource.$resource + * $resource} service. + * + * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by + * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage + * it is important to familiarize yourself with these APIs and the guarantees they provide. + * + * + * ## General usage + * The `$http` service is a function which takes a single argument — a configuration object — + * that is used to generate an HTTP request and returns a {@link ng.$q promise} + * with two $http specific methods: `success` and `error`. + * + * ```js + * // Simple GET request example : + * $http.get('/someUrl'). + * success(function(data, status, headers, config) { + * // this callback will be called asynchronously + * // when the response is available + * }). + * error(function(data, status, headers, config) { + * // called asynchronously if an error occurs + * // or server returns response with an error status. + * }); + * ``` + * + * ```js + * // Simple POST request example (passing data) : + * $http.post('/someUrl', {msg:'hello word!'}). + * success(function(data, status, headers, config) { + * // this callback will be called asynchronously + * // when the response is available + * }). + * error(function(data, status, headers, config) { + * // called asynchronously if an error occurs + * // or server returns response with an error status. + * }); + * ``` + * + * + * Since the returned value of calling the $http function is a `promise`, you can also use + * the `then` method to register callbacks, and these callbacks will receive a single argument – + * an object representing the response. See the API signature and type info below for more + * details. + * + * A response status code between 200 and 299 is considered a success status and + * will result in the success callback being called. Note that if the response is a redirect, + * XMLHttpRequest will transparently follow it, meaning that the error callback will not be + * called for such responses. + * + * ## Writing Unit Tests that use $http + * When unit testing (using {@link ngMock ngMock}), it is necessary to call + * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending + * request using trained responses. + * + * ``` + * $httpBackend.expectGET(...); + * $http.get(...); + * $httpBackend.flush(); + * ``` + * + * ## Shortcut methods + * + * Shortcut methods are also available. All shortcut methods require passing in the URL, and + * request data must be passed in for POST/PUT requests. + * + * ```js + * $http.get('/someUrl').success(successCallback); + * $http.post('/someUrl', data).success(successCallback); + * ``` + * + * Complete list of shortcut methods: + * + * - {@link ng.$http#get $http.get} + * - {@link ng.$http#head $http.head} + * - {@link ng.$http#post $http.post} + * - {@link ng.$http#put $http.put} + * - {@link ng.$http#delete $http.delete} + * - {@link ng.$http#jsonp $http.jsonp} + * - {@link ng.$http#patch $http.patch} + * + * + * ## Setting HTTP Headers + * + * The $http service will automatically add certain HTTP headers to all requests. These defaults + * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration + * object, which currently contains this default configuration: + * + * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): + * - `Accept: application/json, text/plain, * / *` + * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) + * - `Content-Type: application/json` + * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) + * - `Content-Type: application/json` + * + * To add or overwrite these defaults, simply add or remove a property from these configuration + * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object + * with the lowercased HTTP method name as the key, e.g. + * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. + * + * The defaults can also be set at runtime via the `$http.defaults` object in the same + * fashion. For example: + * + * ``` + * module.run(function($http) { + * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' + * }); + * ``` + * + * In addition, you can supply a `headers` property in the config object passed when + * calling `$http(config)`, which overrides the defaults without changing them globally. + * + * + * ## Transforming Requests and Responses + * + * Both requests and responses can be transformed using transformation functions: `transformRequest` + * and `transformResponse`. These properties can be a single function that returns + * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions, + * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * - * @param {Function|string} constructor If called with a function then it's considered to be the - * controller constructor function. Otherwise it's considered to be a string which is used - * to retrieve the controller constructor using the following steps: + * ### Default Transformations * - * * check if a controller with given name is registered via `$controllerProvider` - * * check if evaluating the string on the current scope returns a constructor - * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global - * `window` object (not recommended) + * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and + * `defaults.transformResponse` properties. If a request does not provide its own transformations + * then these will be applied. * - * @param {Object} locals Injection locals for Controller. - * @return {Object} Instance of given controller. + * You can augment or replace the default transformations by modifying these properties by adding to or + * replacing the array. * - * @description - * `$controller` service is responsible for instantiating controllers. - * - * It's just a simple call to {@link auto.$injector $injector}, but extracted into - * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). - */ - return function(expression, locals, later, ident) { - // PRIVATE API: - // param `later` --- indicates that the controller's constructor is invoked at a later time. - // If true, $controller will allocate the object with the correct - // prototype chain, but will not invoke the controller until a returned - // callback is invoked. - // param `ident` --- An optional label which overrides the label parsed from the controller - // expression, if any. - var instance, match, constructor, identifier; - later = later === true; - if (ident && isString(ident)) { - identifier = ident; - } - - if(isString(expression)) { - match = expression.match(CNTRL_REG), - constructor = match[1], - identifier = identifier || match[3]; - expression = controllers.hasOwnProperty(constructor) - ? controllers[constructor] - : getter(locals.$scope, constructor, true) || - (globals ? getter($window, constructor, true) : undefined); - - assertArgFn(expression, constructor, true); - } - - if (later) { - // Instantiate controller later: - // This machinery is used to create an instance of the object before calling the - // controller's constructor itself. - // - // This allows properties to be added to the controller before the constructor is - // invoked. Primarily, this is used for isolate scope bindings in $compile. - // - // This feature is not intended for use by applications, and is thus not documented - // publicly. - var Constructor = function() {}; - Constructor.prototype = (isArray(expression) ? - expression[expression.length - 1] : expression).prototype; - instance = new Constructor(); - - if (identifier) { - addIdentifier(locals, identifier, instance, constructor || expression.name); - } - - return extend(function() { - $injector.invoke(expression, instance, locals, constructor); - return instance; - }, { - instance: instance, - identifier: identifier - }); - } - - instance = $injector.instantiate(expression, locals, constructor); - - if (identifier) { - addIdentifier(locals, identifier, instance, constructor || expression.name); - } - - return instance; - }; - - function addIdentifier(locals, identifier, instance, name) { - if (!(locals && isObject(locals.$scope))) { - throw minErr('$controller')('noscp', - "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", - name, identifier); - } - - locals.$scope[identifier] = instance; - } - }]; -} - -/** - * @ngdoc service - * @name $document - * @requires $window - * - * @description - * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. - * - * @example - - -
          -

          $document title:

          -

          window.document title:

          -
          -
          - - angular.module('documentExample', []) - .controller('ExampleController', ['$scope', '$document', function($scope, $document) { - $scope.title = $document[0].title; - $scope.windowTitle = angular.element(window.document)[0].title; - }]); - -
          - */ -function $DocumentProvider(){ - this.$get = ['$window', function(window){ - return jqLite(window.document); - }]; -} - -/** - * @ngdoc service - * @name $exceptionHandler - * @requires ng.$log - * - * @description - * Any uncaught exception in angular expressions is delegated to this service. - * The default implementation simply delegates to `$log.error` which logs it into - * the browser console. - * - * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by - * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. - * - * ## Example: - * - * ```js - * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { - * return function (exception, cause) { - * exception.message += ' (caused by "' + cause + '")'; - * throw exception; - * }; - * }); - * ``` - * - * This example will override the normal action of `$exceptionHandler`, to make angular - * exceptions fail hard when they happen, instead of just logging to the console. - * - *
          - * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` - * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} - * (unless executed during a digest). - * - * If you wish, you can manually delegate exceptions, e.g. - * `try { ... } catch(e) { $exceptionHandler(e); }` - * - * @param {Error} exception Exception associated with the error. - * @param {string=} cause optional information about the context in which - * the error was thrown. - * - */ -function $ExceptionHandlerProvider() { - this.$get = ['$log', function($log) { - return function(exception, cause) { - $log.error.apply($log, arguments); - }; - }]; -} - -/** - * Parse headers into key value object - * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object - */ -function parseHeaders(headers) { - var parsed = {}, key, val, i; - - if (!headers) return parsed; - - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); - - if (key) { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - }); - - return parsed; -} - - -/** - * Returns a function that provides access to parsed headers. - * - * Headers are lazy parsed when first requested. - * @see parseHeaders - * - * @param {(string|Object)} headers Headers to provide access to. - * @returns {function(string=)} Returns a getter function which if called with: - * - * - if called with single an argument returns a single header value or null - * - if called with no arguments returns an object containing all headers. - */ -function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; - - return function(name) { - if (!headersObj) headersObj = parseHeaders(headers); - - if (name) { - return headersObj[lowercase(name)] || null; - } - - return headersObj; - }; -} - - -/** - * Chain all given functions - * - * This function is used for both request and response transforming - * - * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. - * @param {(Function|Array.)} fns Function or an array of functions. - * @returns {*} Transformed data. - */ -function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); - - forEach(fns, function(fn) { - data = fn(data, headers); - }); - - return data; -} - - -function isSuccess(status) { - return 200 <= status && status < 300; -} - - -/** - * @ngdoc provider - * @name $httpProvider - * @description - * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. - * */ -function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/, - APPLICATION_JSON = 'application/json', - CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; - - /** - * @ngdoc property - * @name $httpProvider#defaults - * @description - * - * Object containing default values for all {@link ng.$http $http} requests. - * - * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. - * Defaults value is `'XSRF-TOKEN'`. - * - * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the - * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. - * - * - **`defaults.headers`** - {Object} - Default headers for all $http requests. - * Refer to {@link ng.$http#setting-http-headers $http} for documentation on - * setting default headers. - * - **`defaults.headers.common`** - * - **`defaults.headers.post`** - * - **`defaults.headers.put`** - * - **`defaults.headers.patch`** - **/ - var defaults = this.defaults = { - // transform incoming response data - transformResponse: [function defaultHttpResponseTransform(data, headers) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - var contentType = headers('Content-Type'); - if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0) || - (JSON_START.test(data) && JSON_END.test(data))) { - data = fromJson(data); - } - } - return data; - }], - - // transform outgoing request data - transformRequest: [function(d) { - return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; - }], - - // default headers - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - }, - post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), - put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), - patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) - }, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' - }; - - var useApplyAsync = false; - /** - * @ngdoc method - * @name $httpProvider#useApplyAsync - * @description - * - * Configure $http service to combine processing of multiple http responses received at around - * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in - * significant performance improvement for bigger applications that make many HTTP requests - * concurrently (common during application bootstrap). - * - * Defaults to false. If no value is specifed, returns the current configured value. - * - * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred - * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window - * to load and share the same digest cycle. - * - * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. - * otherwise, returns the current configured value. - **/ - this.useApplyAsync = function(value) { - if (isDefined(value)) { - useApplyAsync = !!value; - return this; - } - return useApplyAsync; - }; - - /** - * Are ordered by request, i.e. they are applied in the same order as the - * array, on request, but reverse order, on response. - */ - var interceptorFactories = this.interceptors = []; - - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { - - var defaultCache = $cacheFactory('$http'); - - /** - * Interceptors stored in reverse order. Inner interceptors before outer interceptors. - * The reversal is needed so that we can build up the interception chain around the - * server request. - */ - var reversedInterceptors = []; - - forEach(interceptorFactories, function(interceptorFactory) { - reversedInterceptors.unshift(isString(interceptorFactory) - ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); - }); - - /** - * @ngdoc service - * @kind function - * @name $http - * @requires ng.$httpBackend - * @requires $cacheFactory - * @requires $rootScope - * @requires $q - * @requires $injector - * - * @description - * The `$http` service is a core Angular service that facilitates communication with the remote - * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) - * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). - * - * For unit testing applications that use `$http` service, see - * {@link ngMock.$httpBackend $httpBackend mock}. - * - * For a higher level of abstraction, please check out the {@link ngResource.$resource - * $resource} service. - * - * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by - * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage - * it is important to familiarize yourself with these APIs and the guarantees they provide. - * - * - * ## General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. - * - * ```js - * // Simple GET request example : - * $http.get('/someUrl'). - * success(function(data, status, headers, config) { - * // this callback will be called asynchronously - * // when the response is available - * }). - * error(function(data, status, headers, config) { - * // called asynchronously if an error occurs - * // or server returns response with an error status. - * }); - * ``` - * - * ```js - * // Simple POST request example (passing data) : - * $http.post('/someUrl', {msg:'hello word!'}). - * success(function(data, status, headers, config) { - * // this callback will be called asynchronously - * // when the response is available - * }). - * error(function(data, status, headers, config) { - * // called asynchronously if an error occurs - * // or server returns response with an error status. - * }); - * ``` - * - * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. - * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. - * - * ## Writing Unit Tests that use $http - * When unit testing (using {@link ngMock ngMock}), it is necessary to call - * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending - * request using trained responses. - * - * ``` - * $httpBackend.expectGET(...); - * $http.get(...); - * $httpBackend.flush(); - * ``` - * - * ## Shortcut methods - * - * Shortcut methods are also available. All shortcut methods require passing in the URL, and - * request data must be passed in for POST/PUT requests. - * - * ```js - * $http.get('/someUrl').success(successCallback); - * $http.post('/someUrl', data).success(successCallback); - * ``` - * - * Complete list of shortcut methods: - * - * - {@link ng.$http#get $http.get} - * - {@link ng.$http#head $http.head} - * - {@link ng.$http#post $http.post} - * - {@link ng.$http#put $http.put} - * - {@link ng.$http#delete $http.delete} - * - {@link ng.$http#jsonp $http.jsonp} - * - {@link ng.$http#patch $http.patch} - * - * - * ## Setting HTTP Headers - * - * The $http service will automatically add certain HTTP headers to all requests. These defaults - * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration - * object, which currently contains this default configuration: - * - * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` - * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) - * - `Content-Type: application/json` - * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) - * - `Content-Type: application/json` - * - * To add or overwrite these defaults, simply add or remove a property from these configuration - * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object - * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. - * - * The defaults can also be set at runtime via the `$http.defaults` object in the same - * fashion. For example: - * - * ``` - * module.run(function($http) { - * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' - * }); - * ``` - * - * In addition, you can supply a `headers` property in the config object passed when - * calling `$http(config)`, which overrides the defaults without changing them globally. - * - * - * ## Transforming Requests and Responses - * - * Both requests and responses can be transformed using transformation functions: `transformRequest` - * and `transformResponse`. These properties can be a single function that returns - * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions, - * which allows you to `push` or `unshift` a new transformation function into the transformation chain. - * - * ### Default Transformations - * - * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and - * `defaults.transformResponse` properties. If a request does not provide its own transformations - * then these will be applied. - * - * You can augment or replace the default transformations by modifying these properties by adding to or - * replacing the array. - * - * Angular provides the following default transformations: + * Angular provides the following default transformations: * * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): * @@ -8963,129 +9027,129 @@ function $HttpProvider() { * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. - * - * For example if your server needs to return: - * ```js - * ['one','two'] - * ``` - * - * which is vulnerable to attack, your server can return: - * ```js - * )]}', - * ['one','two'] - * ``` - * - * Angular will strip the prefix, before processing the JSON. - * - * - * ### Cross Site Request Forgery (XSRF) Protection - * - * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only - * JavaScript that runs on your domain could read the cookie, your server can be assured that - * the XHR came from JavaScript running on your domain. The header will not be set for - * cross-domain requests. - * - * To take advantage of this, your server needs to set a token in a JavaScript readable session - * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the - * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure - * that only JavaScript running on your domain could have sent the request. The token must be - * unique for each user and must be verifiable by the server (to prevent the JavaScript from - * making up its own tokens). We recommend that the token is a digest of your site's - * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) - * for added security. - * - * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName - * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, - * or the per-request config object. - * - * - * @param {object} config Object describing the request to be made and how it should be - * processed. The object has following properties: - * - * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned - * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be - * JSONified. - * - **data** – `{string|Object}` – Data to be sent as the request message data. - * - **headers** – `{Object}` – Map of strings or functions which return strings representing - * HTTP headers to send to the server. If the return value of a function is null, the - * header will not be sent. - * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. - * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. - * - **transformRequest** – - * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * request body and headers and returns its transformed (typically serialized) version. - * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} - * - **transformResponse** – - * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} - * that should abort the request when resolved. - * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the - * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) - * for more information. - * - **responseType** - `{string}` - see - * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). - * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: - * - * - **data** – `{string|Object}` – The response body transformed with the transform - * functions. - * - **status** – `{number}` – HTTP status code of the response. - * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. - * - **statusText** – `{string}` – HTTP status text of the response. - * - * @property {Array.} pendingRequests Array of config objects for currently pending - * requests. This is primarily meant to be used for debugging purposes. - * - * - * @example - - -
          - - -
          - - - -
          http status code: {{status}}
          -
          http response data: {{data}}
          -
          -
          - - angular.module('httpExample', []) - .controller('FetchController', ['$scope', '$http', '$templateCache', - function($scope, $http, $templateCache) { + * Angular will automatically strip the prefix before processing it as JSON. + * + * For example if your server needs to return: + * ```js + * ['one','two'] + * ``` + * + * which is vulnerable to attack, your server can return: + * ```js + * )]}', + * ['one','two'] + * ``` + * + * Angular will strip the prefix, before processing the JSON. + * + * + * ### Cross Site Request Forgery (XSRF) Protection + * + * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which + * an unauthorized site can gain your user's private data. Angular provides a mechanism + * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie + * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only + * JavaScript that runs on your domain could read the cookie, your server can be assured that + * the XHR came from JavaScript running on your domain. The header will not be set for + * cross-domain requests. + * + * To take advantage of this, your server needs to set a token in a JavaScript readable session + * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the + * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure + * that only JavaScript running on your domain could have sent the request. The token must be + * unique for each user and must be verifiable by the server (to prevent the JavaScript from + * making up its own tokens). We recommend that the token is a digest of your site's + * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) + * for added security. + * + * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName + * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, + * or the per-request config object. + * + * + * @param {object} config Object describing the request to be made and how it should be + * processed. The object has following properties: + * + * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) + * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. + * - **params** – `{Object.}` – Map of strings or objects which will be turned + * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be + * JSONified. + * - **data** – `{string|Object}` – Data to be sent as the request message data. + * - **headers** – `{Object}` – Map of strings or functions which return strings representing + * HTTP headers to send to the server. If the return value of a function is null, the + * header will not be sent. + * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. + * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. + * - **transformRequest** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} + * - **transformResponse** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} + * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} + * that should abort the request when resolved. + * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) + * for more information. + * - **responseType** - `{string}` - see + * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * + * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the + * standard `then` method and two http specific methods: `success` and `error`. The `then` + * method takes two arguments a success and an error callback which will be called with a + * response object. The `success` and `error` methods take a single argument - a function that + * will be called when the request succeeds or fails respectively. The arguments passed into + * these functions are destructured representation of the response object passed into the + * `then` method. The response object has these properties: + * + * - **data** – `{string|Object}` – The response body transformed with the transform + * functions. + * - **status** – `{number}` – HTTP status code of the response. + * - **headers** – `{function([headerName])}` – Header getter function. + * - **config** – `{Object}` – The configuration object that was used to generate the request. + * - **statusText** – `{string}` – HTTP status text of the response. + * + * @property {Array.} pendingRequests Array of config objects for currently pending + * requests. This is primarily meant to be used for debugging purposes. + * + * + * @example + + +
          + + +
          + + + +
          http status code: {{status}}
          +
          http response data: {{data}}
          +
          +
          + + angular.module('httpExample', []) + .controller('FetchController', ['$scope', '$http', '$templateCache', + function($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; @@ -9109,1007 +9173,1007 @@ function $HttpProvider() { $scope.url = url; }; }]); - - - Hello, $http! - - - var status = element(by.binding('status')); - var data = element(by.binding('data')); - var fetchBtn = element(by.id('fetchbtn')); - var sampleGetBtn = element(by.id('samplegetbtn')); - var sampleJsonpBtn = element(by.id('samplejsonpbtn')); - var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); - - it('should make an xhr GET request', function() { + + + Hello, $http! + + + var status = element(by.binding('status')); + var data = element(by.binding('data')); + var fetchBtn = element(by.id('fetchbtn')); + var sampleGetBtn = element(by.id('samplegetbtn')); + var sampleJsonpBtn = element(by.id('samplejsonpbtn')); + var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); + + it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); -// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 -// it('should make a JSONP request to angularjs.org', function() { + // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 + // it('should make a JSONP request to angularjs.org', function() { // sampleJsonpBtn.click(); // fetchBtn.click(); // expect(status.getText()).toMatch('200'); // expect(data.getText()).toMatch(/Super Hero!/); // }); - it('should make JSONP request to invalid URL and invoke the error handler', - function() { + it('should make JSONP request to invalid URL and invoke the error handler', + function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); - -
          - */ - function $http(requestConfig) { - var config = { - method: 'get', - transformRequest: defaults.transformRequest, - transformResponse: defaults.transformResponse - }; - var headers = mergeHeaders(requestConfig); - - extend(config, requestConfig); - config.headers = headers; - config.method = uppercase(config.method); - - var serverRequest = function(config) { - headers = config.headers; - var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); - - // strip content-type if data is undefined - if (isUndefined(reqData)) { - forEach(headers, function(value, header) { - if (lowercase(header) === 'content-type') { - delete headers[header]; - } - }); - } + + + */ + function $http(requestConfig) { + var config = { + method: 'get', + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse + }; + var headers = mergeHeaders(requestConfig); + + extend(config, requestConfig); + config.headers = headers; + config.method = uppercase(config.method); + + var serverRequest = function (config) { + headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); + + // strip content-type if data is undefined + if (isUndefined(reqData)) { + forEach(headers, function (value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; + } + }); + } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData, headers).then(transformResponse, transformResponse); + }; + + var chain = [serverRequest, undefined]; + var promise = $q.when(config); + + // apply interceptors + forEach(reversedInterceptors, function (interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift(interceptor.request, interceptor.requestError); + } + if (interceptor.response || interceptor.responseError) { + chain.push(interceptor.response, interceptor.responseError); + } + }); + + while (chain.length) { + var thenFn = chain.shift(); + var rejectFn = chain.shift(); + + promise = promise.then(thenFn, rejectFn); + } - if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { - config.withCredentials = defaults.withCredentials; - } + promise.success = function (fn) { + promise.then(function (response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + promise.error = function (fn) { + promise.then(null, function (response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + return promise; + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response); + if (!response.data) { + resp.data = response.data; + } else { + resp.data = transformData(response.data, response.headers, config.transformResponse); + } + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); + } - // send request - return sendReq(config, reqData, headers).then(transformResponse, transformResponse); - }; + function mergeHeaders(config) { + var defHeaders = defaults.headers, + reqHeaders = extend({}, config.headers), + defHeaderName, lowercaseDefHeaderName, reqHeaderName; + + defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); + + // using for-in instead of forEach to avoid unecessary iteration after header has been found + defaultHeadersIteration: + for (defHeaderName in defHeaders) { + lowercaseDefHeaderName = lowercase(defHeaderName); + + for (reqHeaderName in reqHeaders) { + if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { + continue defaultHeadersIteration; + } + } + + reqHeaders[defHeaderName] = defHeaders[defHeaderName]; + } + + // execute if header value is a function for merged headers + execHeaders(reqHeaders); + return reqHeaders; + + function execHeaders(headers) { + var headerContent; + + forEach(headers, function (headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(); + if (headerContent != null) { + headers[header] = headerContent; + } else { + delete headers[header]; + } + } + }); + } + } + } - var chain = [serverRequest, undefined]; - var promise = $q.when(config); + $http.pendingRequests = []; + + /** + * @ngdoc method + * @name $http#get + * + * @description + * Shortcut method to perform `GET` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#delete + * + * @description + * Shortcut method to perform `DELETE` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#head + * + * @description + * Shortcut method to perform `HEAD` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#jsonp + * + * @description + * Shortcut method to perform `JSONP` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request. + * The name of the callback should be the string `JSON_CALLBACK`. + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethods('get', 'delete', 'head', 'jsonp'); + + /** + * @ngdoc method + * @name $http#post + * + * @description + * Shortcut method to perform `POST` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#put + * + * @description + * Shortcut method to perform `PUT` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#patch + * + * @description + * Shortcut method to perform `PATCH` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethodsWithData('post', 'put', 'patch'); + + /** + * @ngdoc property + * @name $http#defaults + * + * @description + * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of + * default headers, withCredentials as well as request and response transformations. + * + * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. + */ + $http.defaults = defaults; + + + return $http; + + + function createShortMethods(names) { + forEach(arguments, function (name) { + $http[name] = function (url, config) { + return $http(extend(config || {}, { + method: name, + url: url + })); + }; + }); + } - // apply interceptors - forEach(reversedInterceptors, function(interceptor) { - if (interceptor.request || interceptor.requestError) { - chain.unshift(interceptor.request, interceptor.requestError); - } - if (interceptor.response || interceptor.responseError) { - chain.push(interceptor.response, interceptor.responseError); - } - }); - while(chain.length) { - var thenFn = chain.shift(); - var rejectFn = chain.shift(); + function createShortMethodsWithData(name) { + forEach(arguments, function (name) { + $http[name] = function (url, data, config) { + return $http(extend(config || {}, { + method: name, + url: url, + data: data + })); + }; + }); + } - promise = promise.then(thenFn, rejectFn); - } - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; + /** + * Makes the request. + * + * !!! ACCESSES CLOSURE VARS: + * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests + */ + function sendReq(config, reqData, reqHeaders) { + var deferred = $q.defer(), + promise = deferred.promise, + cache, + cachedResp, + url = buildUrl(config.url, config.params); + + $http.pendingRequests.push(config); + promise.then(removePendingReq, removePendingReq); + + + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { + cache = isObject(config.cache) ? config.cache + : isObject(defaults.cache) ? defaults.cache + : defaultCache; + } - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; + if (cache) { + cachedResp = cache.get(url); + if (isDefined(cachedResp)) { + if (isPromiseLike(cachedResp)) { + // cached request has already been sent, but there is no response yet + cachedResp.then(removePendingReq, removePendingReq); + return cachedResp; + } else { + // serving from cache + if (isArray(cachedResp)) { + resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); + } else { + resolvePromise(cachedResp, 200, {}, 'OK'); + } + } + } else { + // put the promise for the non-transformed response into cache as a placeholder + cache.put(url, promise); + } + } - return promise; - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response); - if (!response.data) { - resp.data = response.data; - } else { - resp.data = transformData(response.data, response.headers, config.transformResponse); - } - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); - } + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend + if (isUndefined(cachedResp)) { + var xsrfValue = urlIsSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } - function mergeHeaders(config) { - var defHeaders = defaults.headers, - reqHeaders = extend({}, config.headers), - defHeaderName, lowercaseDefHeaderName, reqHeaderName; + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, + config.withCredentials, config.responseType); + } - defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); + return promise; + + + /** + * Callback registered to $httpBackend(): + * - caches the response if desired + * - resolves the raw $http promise + * - calls $apply + */ + function done(status, response, headersString, statusText) { + if (cache) { + if (isSuccess(status)) { + cache.put(url, [status, response, parseHeaders(headersString), statusText]); + } else { + // remove promise from the cache + cache.remove(url); + } + } + + function resolveHttpPromise() { + resolvePromise(response, status, headersString, statusText); + } + + if (useApplyAsync) { + $rootScope.$applyAsync(resolveHttpPromise); + } else { + resolveHttpPromise(); + if (!$rootScope.$$phase) $rootScope.$apply(); + } + } - // using for-in instead of forEach to avoid unecessary iteration after header has been found - defaultHeadersIteration: - for (defHeaderName in defHeaders) { - lowercaseDefHeaderName = lowercase(defHeaderName); - for (reqHeaderName in reqHeaders) { - if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { - continue defaultHeadersIteration; - } - } + /** + * Resolves the raw $http promise. + */ + function resolvePromise(response, status, headers, statusText) { + // normalize internal statuses to 0 + status = Math.max(status, 0); + + (isSuccess(status) ? deferred.resolve : deferred.reject)({ + data: response, + status: status, + headers: headersGetter(headers), + config: config, + statusText: statusText + }); + } - reqHeaders[defHeaderName] = defHeaders[defHeaderName]; - } - // execute if header value is a function for merged headers - execHeaders(reqHeaders); - return reqHeaders; + function removePendingReq() { + var idx = $http.pendingRequests.indexOf(config); + if (idx !== -1) $http.pendingRequests.splice(idx, 1); + } + } - function execHeaders(headers) { - var headerContent; - forEach(headers, function(headerFn, header) { - if (isFunction(headerFn)) { - headerContent = headerFn(); - if (headerContent != null) { - headers[header] = headerContent; - } else { - delete headers[header]; - } - } - }); - } - } + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function (value, key) { + if (value === null || isUndefined(value)) return; + if (!isArray(value)) value = [value]; + + forEach(value, function (v) { + if (isObject(v)) { + if (isDate(v)) { + v = v.toISOString(); + } else { + v = toJson(v); + } + } + parts.push(encodeUriQuery(key) + '=' + + encodeUriQuery(v)); + }); + }); + if (parts.length > 0) { + url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } + return url; + } + }]; } - $http.pendingRequests = []; + function createXhr() { + return new window.XMLHttpRequest(); + } /** - * @ngdoc method - * @name $http#get + * @ngdoc service + * @name $httpBackend + * @requires $window + * @requires $document * * @description - * Shortcut method to perform `GET` request. + * HTTP backend used by the {@link ng.$http service} that delegates to + * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name $http#delete + * You should never need to use this service directly, instead use the higher-level abstractions: + * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * - * @description - * Shortcut method to perform `DELETE` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * During testing this implementation is swapped with {@link ngMock.$httpBackend mock + * $httpBackend} which can be trained with responses. */ + function $HttpBackendProvider() { + this.$get = ['$browser', '$window', '$document', function ($browser, $window, $document) { + return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); + }]; + } + + function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { + // TODO(vojta): fix the signature + return function (method, url, post, callback, headers, timeout, withCredentials, responseType) { + $browser.$$incOutstandingRequestCount(); + url = url || $browser.url(); + + if (lowercase(method) == 'jsonp') { + var callbackId = '_' + (callbacks.counter++).toString(36); + callbacks[callbackId] = function (data) { + callbacks[callbackId].data = data; + callbacks[callbackId].called = true; + }; - /** - * @ngdoc method - * @name $http#head - * - * @description - * Shortcut method to perform `HEAD` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + callbackId, function (status, text) { + completeRequest(callback, status, callbacks[callbackId].data, "", text); + callbacks[callbackId] = noop; + }); + } else { - /** - * @ngdoc method - * @name $http#jsonp - * - * @description - * Shortcut method to perform `JSONP` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request. - * The name of the callback should be the string `JSON_CALLBACK`. - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - createShortMethods('get', 'delete', 'head', 'jsonp'); + var xhr = createXhr(); - /** - * @ngdoc method - * @name $http#post - * - * @description - * Shortcut method to perform `POST` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ + xhr.open(method, url, true); + forEach(headers, function (value, key) { + if (isDefined(value)) { + xhr.setRequestHeader(key, value); + } + }); - /** - * @ngdoc method - * @name $http#put - * - * @description - * Shortcut method to perform `PUT` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - - /** - * @ngdoc method - * @name $http#patch - * - * @description - * Shortcut method to perform `PATCH` request. - * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object - */ - createShortMethodsWithData('post', 'put', 'patch'); - - /** - * @ngdoc property - * @name $http#defaults - * - * @description - * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of - * default headers, withCredentials as well as request and response transformations. - * - * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. - */ - $http.defaults = defaults; + xhr.onload = function requestLoaded() { + var statusText = xhr.statusText || ''; + // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) + var response = ('response' in xhr) ? xhr.response : xhr.responseText; - return $http; + // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) + var status = xhr.status === 1223 ? 204 : xhr.status; + // fix status code when it is 0 (0 status is undocumented). + // Occurs when accessing file resources or on Android 4.1 stock browser + // while retrieving files from application cache. + if (status === 0) { + status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; + } - function createShortMethods(names) { - forEach(arguments, function(name) { - $http[name] = function(url, config) { - return $http(extend(config || {}, { - method: name, - url: url - })); - }; - }); - } + completeRequest(callback, + status, + response, + xhr.getAllResponseHeaders(), + statusText); + }; + var requestError = function () { + // The response is always empty + // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error + completeRequest(callback, -1, null, null, ''); + }; - function createShortMethodsWithData(name) { - forEach(arguments, function(name) { - $http[name] = function(url, data, config) { - return $http(extend(config || {}, { - method: name, - url: url, - data: data - })); - }; - }); - } + xhr.onerror = requestError; + xhr.onabort = requestError; + if (withCredentials) { + xhr.withCredentials = true; + } - /** - * Makes the request. - * - * !!! ACCESSES CLOSURE VARS: - * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests - */ - function sendReq(config, reqData, reqHeaders) { - var deferred = $q.defer(), - promise = deferred.promise, - cache, - cachedResp, - url = buildUrl(config.url, config.params); - - $http.pendingRequests.push(config); - promise.then(removePendingReq, removePendingReq); - - - if ((config.cache || defaults.cache) && config.cache !== false && - (config.method === 'GET' || config.method === 'JSONP')) { - cache = isObject(config.cache) ? config.cache - : isObject(defaults.cache) ? defaults.cache - : defaultCache; - } + if (responseType) { + try { + xhr.responseType = responseType; + } catch (e) { + // WebKit added support for the json responseType value on 09/03/2013 + // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are + // known to throw when setting the value "json" as the response type. Other older + // browsers implementing the responseType + // + // The json response type can be ignored if not supported, because JSON payloads are + // parsed on the client-side regardless. + if (responseType !== 'json') { + throw e; + } + } + } - if (cache) { - cachedResp = cache.get(url); - if (isDefined(cachedResp)) { - if (isPromiseLike(cachedResp)) { - // cached request has already been sent, but there is no response yet - cachedResp.then(removePendingReq, removePendingReq); - return cachedResp; - } else { - // serving from cache - if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); - } else { - resolvePromise(cachedResp, 200, {}, 'OK'); + xhr.send(post || null); } - } - } else { - // put the promise for the non-transformed response into cache as a placeholder - cache.put(url, promise); - } - } - - - // if we won't have the response in cache, set the xsrf headers and - // send the request to the backend - if (isUndefined(cachedResp)) { - var xsrfValue = urlIsSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] - : undefined; - if (xsrfValue) { - reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; - } - - $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, - config.withCredentials, config.responseType); - } - - return promise; - - - /** - * Callback registered to $httpBackend(): - * - caches the response if desired - * - resolves the raw $http promise - * - calls $apply - */ - function done(status, response, headersString, statusText) { - if (cache) { - if (isSuccess(status)) { - cache.put(url, [status, response, parseHeaders(headersString), statusText]); - } else { - // remove promise from the cache - cache.remove(url); - } - } - - function resolveHttpPromise() { - resolvePromise(response, status, headersString, statusText); - } - - if (useApplyAsync) { - $rootScope.$applyAsync(resolveHttpPromise); - } else { - resolveHttpPromise(); - if (!$rootScope.$$phase) $rootScope.$apply(); - } - } - - /** - * Resolves the raw $http promise. - */ - function resolvePromise(response, status, headers, statusText) { - // normalize internal statuses to 0 - status = Math.max(status, 0); - - (isSuccess(status) ? deferred.resolve : deferred.reject)({ - data: response, - status: status, - headers: headersGetter(headers), - config: config, - statusText : statusText - }); - } - - - function removePendingReq() { - var idx = $http.pendingRequests.indexOf(config); - if (idx !== -1) $http.pendingRequests.splice(idx, 1); - } - } - - - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value === null || isUndefined(value)) return; - if (!isArray(value)) value = [value]; - - forEach(value, function(v) { - if (isObject(v)) { - if (isDate(v)){ - v = v.toISOString(); - } else { - v = toJson(v); + if (timeout > 0) { + var timeoutId = $browserDefer(timeoutRequest, timeout); + } else if (isPromiseLike(timeout)) { + timeout.then(timeoutRequest); } - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); - }); - if(parts.length > 0) { - url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); - } - return url; - } - }]; -} - -function createXhr() { - return new window.XMLHttpRequest(); -} - -/** - * @ngdoc service - * @name $httpBackend - * @requires $window - * @requires $document - * - * @description - * HTTP backend used by the {@link ng.$http service} that delegates to - * XMLHttpRequest object or JSONP and deals with browser incompatibilities. - * - * You should never need to use this service directly, instead use the higher-level abstractions: - * {@link ng.$http $http} or {@link ngResource.$resource $resource}. - * - * During testing this implementation is swapped with {@link ngMock.$httpBackend mock - * $httpBackend} which can be trained with responses. - */ -function $HttpBackendProvider() { - this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { - return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); - }]; -} - -function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { - // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { - $browser.$$incOutstandingRequestCount(); - url = url || $browser.url(); - - if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - callbacks[callbackId].called = true; - }; - - var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - callbackId, function(status, text) { - completeRequest(callback, status, callbacks[callbackId].data, "", text); - callbacks[callbackId] = noop; - }); - } else { - - var xhr = createXhr(); - - xhr.open(method, url, true); - forEach(headers, function(value, key) { - if (isDefined(value)) { - xhr.setRequestHeader(key, value); - } - }); - xhr.onload = function requestLoaded() { - var statusText = xhr.statusText || ''; - // responseText is the old-school way of retrieving response (supported by IE8 & 9) - // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) - var response = ('response' in xhr) ? xhr.response : xhr.responseText; - - // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) - var status = xhr.status === 1223 ? 204 : xhr.status; - - // fix status code when it is 0 (0 status is undocumented). - // Occurs when accessing file resources or on Android 4.1 stock browser - // while retrieving files from application cache. - if (status === 0) { - status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; - } + function timeoutRequest() { + jsonpDone && jsonpDone(); + xhr && xhr.abort(); + } - completeRequest(callback, - status, - response, - xhr.getAllResponseHeaders(), - statusText); - }; + function completeRequest(callback, status, response, headersString, statusText) { + // cancel timeout and subsequent timeout promise resolution + timeoutId && $browserDefer.cancel(timeoutId); + jsonpDone = xhr = null; - var requestError = function () { - // The response is always empty - // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error - completeRequest(callback, -1, null, null, ''); - }; + callback(status, response, headersString, statusText); + $browser.$$completeOutstandingRequest(noop); + } + }; - xhr.onerror = requestError; - xhr.onabort = requestError; + function jsonpReq(url, callbackId, done) { + // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + // - fetches local scripts via XHR and evals them + // - adds and immediately removes script elements from the document + var script = rawDocument.createElement('script'), callback = null; + script.type = "text/javascript"; + script.src = url; + script.async = true; + + callback = function (event) { + removeEventListenerFn(script, "load", callback); + removeEventListenerFn(script, "error", callback); + rawDocument.body.removeChild(script); + script = null; + var status = -1; + var text = "unknown"; + + if (event) { + if (event.type === "load" && !callbacks[callbackId].called) { + event = {type: "error"}; + } + text = event.type; + status = event.type === "error" ? 404 : 200; + } - if (withCredentials) { - xhr.withCredentials = true; - } + if (done) { + done(status, text); + } + }; - if (responseType) { - try { - xhr.responseType = responseType; - } catch (e) { - // WebKit added support for the json responseType value on 09/03/2013 - // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are - // known to throw when setting the value "json" as the response type. Other older - // browsers implementing the responseType - // - // The json response type can be ignored if not supported, because JSON payloads are - // parsed on the client-side regardless. - if (responseType !== 'json') { - throw e; - } + addEventListenerFn(script, "load", callback); + addEventListenerFn(script, "error", callback); + rawDocument.body.appendChild(script); + return callback; } - } - - xhr.send(post || null); - } - - if (timeout > 0) { - var timeoutId = $browserDefer(timeoutRequest, timeout); - } else if (isPromiseLike(timeout)) { - timeout.then(timeoutRequest); - } - - - function timeoutRequest() { - jsonpDone && jsonpDone(); - xhr && xhr.abort(); - } - - function completeRequest(callback, status, response, headersString, statusText) { - // cancel timeout and subsequent timeout promise resolution - timeoutId && $browserDefer.cancel(timeoutId); - jsonpDone = xhr = null; - - callback(status, response, headersString, statusText); - $browser.$$completeOutstandingRequest(noop); } - }; - - function jsonpReq(url, callbackId, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: - // - fetches local scripts via XHR and evals them - // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), callback = null; - script.type = "text/javascript"; - script.src = url; - script.async = true; - - callback = function(event) { - removeEventListenerFn(script, "load", callback); - removeEventListenerFn(script, "error", callback); - rawDocument.body.removeChild(script); - script = null; - var status = -1; - var text = "unknown"; - - if (event) { - if (event.type === "load" && !callbacks[callbackId].called) { - event = { type: "error" }; - } - text = event.type; - status = event.type === "error" ? 404 : 200; - } - - if (done) { - done(status, text); - } - }; - - addEventListenerFn(script, "load", callback); - addEventListenerFn(script, "error", callback); - rawDocument.body.appendChild(script); - return callback; - } -} -var $interpolateMinErr = minErr('$interpolate'); + var $interpolateMinErr = minErr('$interpolate'); -/** - * @ngdoc provider - * @name $interpolateProvider - * - * @description - * - * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. - * - * @example - - - -
          - //demo.label// -
          -
          - - it('should interpolate binding with custom symbols', function() { + +
          + //demo.label// +
          +
          + + it('should interpolate binding with custom symbols', function() { expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); }); - -
          - */ -function $InterpolateProvider() { - var startSymbol = '{{'; - var endSymbol = '}}'; - - /** - * @ngdoc method - * @name $interpolateProvider#startSymbol - * @description - * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. - * - * @param {string=} value new value to set the starting symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.startSymbol = function(value){ - if (value) { - startSymbol = value; - return this; - } else { - return startSymbol; - } - }; - - /** - * @ngdoc method - * @name $interpolateProvider#endSymbol - * @description - * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. - * - * @param {string=} value new value to set the ending symbol to. - * @returns {string|self} Returns the symbol when used as getter and self if used as setter. - */ - this.endSymbol = function(value){ - if (value) { - endSymbol = value; - return this; - } else { - return endSymbol; - } - }; - - - this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { - var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length, - escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), - escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); - - function escape(ch) { - return '\\\\\\' + ch; - } - - /** - * @ngdoc service - * @name $interpolate - * @kind function - * - * @requires $parse - * @requires $sce - * - * @description - * - * Compiles a string with markup into an interpolation function. This service is used by the - * HTML {@link ng.$compile $compile} service for data binding. See - * {@link ng.$interpolateProvider $interpolateProvider} for configuring the - * interpolation markup. - * - * - * ```js - * var $interpolate = ...; // injected - * var exp = $interpolate('Hello {{name | uppercase}}!'); - * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); - * ``` - * - * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is - * `true`, the interpolation function will return `undefined` unless all embedded expressions - * evaluate to a value other than `undefined`. - * - * ```js - * var $interpolate = ...; // injected - * var context = {greeting: 'Hello', name: undefined }; - * - * // default "forgiving" mode - * var exp = $interpolate('{{greeting}} {{name}}!'); - * expect(exp(context)).toEqual('Hello !'); - * - * // "allOrNothing" mode - * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); - * expect(exp(context)).toBeUndefined(); - * context.name = 'Angular'; - * expect(exp(context)).toEqual('Hello Angular!'); - * ``` - * - * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. - * - * ####Escaped Interpolation - * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers - * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). - * It will be rendered as a regular start/end marker, and will not be interpreted as an expression - * or binding. - * - * This enables web-servers to prevent script injection attacks and defacing attacks, to some - * degree, while also enabling code examples to work without relying on the - * {@link ng.directive:ngNonBindable ngNonBindable} directive. - * - * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, - * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all - * interpolation start/end markers with their escaped counterparts.** - * - * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered - * output when the $interpolate service processes the text. So, for HTML elements interpolated - * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter - * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, - * this is typically useful only when user-data is used in rendering a template from the server, or - * when otherwise untrusted data is used by a directive. - * - * - * - *
          - *

          {{apptitle}}: \{\{ username = "defaced value"; \}\} - *

          - *

          {{username}} attempts to inject code which will deface the - * application, but fails to accomplish their task, because the server has correctly - * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) - * characters.

          - *

          Instead, the result of the attempted script injection is visible, and can be removed - * from the database by an administrator.

          - *
          - *
          - *
          - * - * @param {string} text The text with markup to interpolate. - * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have - * embedded expression in order to return an interpolation function. Strings with no - * embedded expression will return null for the interpolation function. - * @param {string=} trustedContext when provided, the returned function passes the interpolated - * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, - * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that - * provides Strict Contextual Escaping for details. - * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined - * unless all embedded expressions evaluate to a value other than `undefined`. - * @returns {function(context)} an interpolation function which is used to compute the - * interpolated string. The function has these parameters: - * - * - `context`: evaluation context for all expressions embedded in the interpolated text + + */ - function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { - allOrNothing = !!allOrNothing; - var startIndex, - endIndex, - index = 0, - expressions = [], - parseFns = [], - textLength = text.length, - exp, - concat = [], - expressionPositions = []; - - while(index < textLength) { - if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { - if (index !== startIndex) { - concat.push(unescapeText(text.substring(index, startIndex))); - } - exp = text.substring(startIndex + startSymbolLength, endIndex); - expressions.push(exp); - parseFns.push($parse(exp, parseStringifyInterceptor)); - index = endIndex + endSymbolLength; - expressionPositions.push(concat.length); - concat.push(''); - } else { - // we did not find an interpolation, so we have to add the remainder to the separators array - if (index !== textLength) { - concat.push(unescapeText(text.substring(index))); - } - break; - } - } - - // Concatenating expressions makes it hard to reason about whether some combination of - // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a - // single expression be used for iframe[src], object[src], etc., we ensure that the value - // that's used is assigned or constructed by some JS code somewhere that is more testable or - // make it obvious that you bound the value to some user controlled value. This helps reduce - // the load when auditing for XSS issues. - if (trustedContext && concat.length > 1) { - throw $interpolateMinErr('noconcat', - "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + - "interpolations that concatenate multiple expressions when a trusted value is " + - "required. See http://docs.angularjs.org/api/ng.$sce", text); - } + function $InterpolateProvider() { + var startSymbol = '{{'; + var endSymbol = '}}'; - if (!mustHaveExpression || expressions.length) { - var compute = function(values) { - for(var i = 0, ii = expressions.length; i < ii; i++) { - if (allOrNothing && isUndefined(values[i])) return; - concat[expressionPositions[i]] = values[i]; - } - return concat.join(''); + /** + * @ngdoc method + * @name $interpolateProvider#startSymbol + * @description + * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. + * + * @param {string=} value new value to set the starting symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.startSymbol = function (value) { + if (value) { + startSymbol = value; + return this; + } else { + return startSymbol; + } }; - var getValue = function (value) { - return trustedContext ? - $sce.getTrusted(trustedContext, value) : - $sce.valueOf(value); + /** + * @ngdoc method + * @name $interpolateProvider#endSymbol + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * @param {string=} value new value to set the ending symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.endSymbol = function (value) { + if (value) { + endSymbol = value; + return this; + } else { + return endSymbol; + } }; - var stringify = function (value) { - if (value == null) { // null || undefined - return ''; - } - switch (typeof value) { - case 'string': - break; - case 'number': - value = '' + value; - break; - default: - value = toJson(value); - } - - return value; - }; - return extend(function interpolationFn(context) { - var i = 0; - var ii = expressions.length; - var values = new Array(ii); + this.$get = ['$parse', '$exceptionHandler', '$sce', function ($parse, $exceptionHandler, $sce) { + var startSymbolLength = startSymbol.length, + endSymbolLength = endSymbol.length, + escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), + escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); - try { - for (; i < ii; i++) { - values[i] = parseFns[i](context); - } + function escape(ch) { + return '\\\\\\' + ch; + } - return compute(values); - } catch(err) { - var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, - err.toString()); - $exceptionHandler(newErr); - } - - }, { - // all of these properties are undocumented for now - exp: text, //just for compatibility with regular watchers created via $watch - expressions: expressions, - $$watchDelegate: function (scope, listener, objectEquality) { - var lastValue; - return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { - var currValue = compute(values); - if (isFunction(listener)) { - listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); - } - lastValue = currValue; - }, objectEquality); - } - }); - } + /** + * @ngdoc service + * @name $interpolate + * @kind function + * + * @requires $parse + * @requires $sce + * + * @description + * + * Compiles a string with markup into an interpolation function. This service is used by the + * HTML {@link ng.$compile $compile} service for data binding. See + * {@link ng.$interpolateProvider $interpolateProvider} for configuring the + * interpolation markup. + * + * + * ```js + * var $interpolate = ...; // injected + * var exp = $interpolate('Hello {{name | uppercase}}!'); + * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); + * ``` + * + * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is + * `true`, the interpolation function will return `undefined` unless all embedded expressions + * evaluate to a value other than `undefined`. + * + * ```js + * var $interpolate = ...; // injected + * var context = {greeting: 'Hello', name: undefined }; + * + * // default "forgiving" mode + * var exp = $interpolate('{{greeting}} {{name}}!'); + * expect(exp(context)).toEqual('Hello !'); + * + * // "allOrNothing" mode + * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); + * expect(exp(context)).toBeUndefined(); + * context.name = 'Angular'; + * expect(exp(context)).toEqual('Hello Angular!'); + * ``` + * + * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. + * + * ####Escaped Interpolation + * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers + * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). + * It will be rendered as a regular start/end marker, and will not be interpreted as an expression + * or binding. + * + * This enables web-servers to prevent script injection attacks and defacing attacks, to some + * degree, while also enabling code examples to work without relying on the + * {@link ng.directive:ngNonBindable ngNonBindable} directive. + * + * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, + * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all + * interpolation start/end markers with their escaped counterparts.** + * + * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered + * output when the $interpolate service processes the text. So, for HTML elements interpolated + * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter + * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, + * this is typically useful only when user-data is used in rendering a template from the server, or + * when otherwise untrusted data is used by a directive. + * + * + * + *
          + *

          {{apptitle}}: \{\{ username = "defaced value"; \}\} + *

          + *

          {{username}} attempts to inject code which will deface the + * application, but fails to accomplish their task, because the server has correctly + * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) + * characters.

          + *

          Instead, the result of the attempted script injection is visible, and can be removed + * from the database by an administrator.

          + *
          + *
          + *
          + * + * @param {string} text The text with markup to interpolate. + * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have + * embedded expression in order to return an interpolation function. Strings with no + * embedded expression will return null for the interpolation function. + * @param {string=} trustedContext when provided, the returned function passes the interpolated + * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, + * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that + * provides Strict Contextual Escaping for details. + * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined + * unless all embedded expressions evaluate to a value other than `undefined`. + * @returns {function(context)} an interpolation function which is used to compute the + * interpolated string. The function has these parameters: + * + * - `context`: evaluation context for all expressions embedded in the interpolated text + */ + function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { + allOrNothing = !!allOrNothing; + var startIndex, + endIndex, + index = 0, + expressions = [], + parseFns = [], + textLength = text.length, + exp, + concat = [], + expressionPositions = []; + + while (index < textLength) { + if (((startIndex = text.indexOf(startSymbol, index)) != -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) { + if (index !== startIndex) { + concat.push(unescapeText(text.substring(index, startIndex))); + } + exp = text.substring(startIndex + startSymbolLength, endIndex); + expressions.push(exp); + parseFns.push($parse(exp, parseStringifyInterceptor)); + index = endIndex + endSymbolLength; + expressionPositions.push(concat.length); + concat.push(''); + } else { + // we did not find an interpolation, so we have to add the remainder to the separators array + if (index !== textLength) { + concat.push(unescapeText(text.substring(index))); + } + break; + } + } - function unescapeText(text) { - return text.replace(escapedStartRegexp, startSymbol). - replace(escapedEndRegexp, endSymbol); - } + // Concatenating expressions makes it hard to reason about whether some combination of + // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a + // single expression be used for iframe[src], object[src], etc., we ensure that the value + // that's used is assigned or constructed by some JS code somewhere that is more testable or + // make it obvious that you bound the value to some user controlled value. This helps reduce + // the load when auditing for XSS issues. + if (trustedContext && concat.length > 1) { + throw $interpolateMinErr('noconcat', + "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + + "interpolations that concatenate multiple expressions when a trusted value is " + + "required. See http://docs.angularjs.org/api/ng.$sce", text); + } - function parseStringifyInterceptor(value) { - try { - return stringify(getValue(value)); - } catch(err) { - var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, - err.toString()); - $exceptionHandler(newErr); - } - } - } + if (!mustHaveExpression || expressions.length) { + var compute = function (values) { + for (var i = 0, ii = expressions.length; i < ii; i++) { + if (allOrNothing && isUndefined(values[i])) return; + concat[expressionPositions[i]] = values[i]; + } + return concat.join(''); + }; + + var getValue = function (value) { + return trustedContext ? + $sce.getTrusted(trustedContext, value) : + $sce.valueOf(value); + }; + + var stringify = function (value) { + if (value == null) { // null || undefined + return ''; + } + switch (typeof value) { + case 'string': + break; + case 'number': + value = '' + value; + break; + default: + value = toJson(value); + } + + return value; + }; + + return extend(function interpolationFn(context) { + var i = 0; + var ii = expressions.length; + var values = new Array(ii); + + try { + for (; i < ii; i++) { + values[i] = parseFns[i](context); + } + + return compute(values); + } catch (err) { + var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, + err.toString()); + $exceptionHandler(newErr); + } + + }, { + // all of these properties are undocumented for now + exp: text, //just for compatibility with regular watchers created via $watch + expressions: expressions, + $$watchDelegate: function (scope, listener, objectEquality) { + var lastValue; + return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { + var currValue = compute(values); + if (isFunction(listener)) { + listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); + } + lastValue = currValue; + }, objectEquality); + } + }); + } + function unescapeText(text) { + return text.replace(escapedStartRegexp, startSymbol). + replace(escapedEndRegexp, endSymbol); + } - /** - * @ngdoc method - * @name $interpolate#startSymbol - * @description - * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. - * - * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change - * the symbol. - * - * @returns {string} start symbol. - */ - $interpolate.startSymbol = function() { - return startSymbol; - }; + function parseStringifyInterceptor(value) { + try { + return stringify(getValue(value)); + } catch (err) { + var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, + err.toString()); + $exceptionHandler(newErr); + } + } + } - /** - * @ngdoc method - * @name $interpolate#endSymbol - * @description - * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + /** + * @ngdoc method + * @name $interpolate#startSymbol + * @description + * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * - * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change + * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change * the symbol. * - * @returns {string} end symbol. - */ - $interpolate.endSymbol = function() { - return endSymbol; - }; - - return $interpolate; - }]; -} + * @returns {string} start symbol. + */ + $interpolate.startSymbol = function () { + return startSymbol; + }; -function $IntervalProvider() { - this.$get = ['$rootScope', '$window', '$q', '$$q', - function($rootScope, $window, $q, $$q) { - var intervals = {}; + /** + * @ngdoc method + * @name $interpolate#endSymbol + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change + * the symbol. + * + * @returns {string} end symbol. + */ + $interpolate.endSymbol = function () { + return endSymbol; + }; - /** - * @ngdoc service - * @name $interval - * - * @description - * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` - * milliseconds. - * - * The return value of registering an interval function is a promise. This promise will be - * notified upon each tick of the interval, and will be resolved after `count` iterations, or - * run indefinitely if `count` is not defined. The value of the notification will be the - * number of iterations that have run. - * To cancel an interval, call `$interval.cancel(promise)`. - * - * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to - * move forward by `millis` milliseconds and trigger any functions scheduled to run in that - * time. - * - *
          - * **Note**: Intervals created by this service must be explicitly destroyed when you are finished - * with them. In particular they are not automatically destroyed when a controller's scope or a - * directive's element are destroyed. - * You should take this into consideration and make sure to always cancel the interval at the - * appropriate moment. See the example below for more details on how and when to do this. - *
          - * - * @param {function()} fn A function that should be called repeatedly. - * @param {number} delay Number of milliseconds between each function call. - * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat - * indefinitely. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {promise} A promise which will be notified on each iteration. - * - * @example - * - * - * - * - *
          - *
          - * Date format:
          - * Current time is: - *
          - * Blood 1 : {{blood_1}} - * Blood 2 : {{blood_2}} - * - * - * - *
          - *
          - * - *
          - *
          - */ - function interval(fn, delay, count, invokeApply) { - var setInterval = $window.setInterval, - clearInterval = $window.clearInterval, - iteration = 0, - skipApply = (isDefined(invokeApply) && !invokeApply), - deferred = (skipApply ? $$q : $q).defer(), - promise = deferred.promise; - - count = isDefined(count) ? count : 0; - - promise.then(null, null, fn); - - promise.$$intervalId = setInterval(function tick() { - deferred.notify(iteration++); - - if (count > 0 && iteration >= count) { - deferred.resolve(iteration); - clearInterval(promise.$$intervalId); - delete intervals[promise.$$intervalId]; - } - - if (!skipApply) $rootScope.$apply(); + * + * + *
          + *
          + * Date format:
          + * Current time is: + *
          + * Blood 1 : {{blood_1}} + * Blood 2 : {{blood_2}} + * + * + * + *
          + *
          + * + * + * + */ + function interval(fn, delay, count, invokeApply) { + var setInterval = $window.setInterval, + clearInterval = $window.clearInterval, + iteration = 0, + skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise; + + count = isDefined(count) ? count : 0; + + promise.then(null, null, fn); + + promise.$$intervalId = setInterval(function tick() { + deferred.notify(iteration++); + + if (count > 0 && iteration >= count) { + deferred.resolve(iteration); + clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + } + + if (!skipApply) $rootScope.$apply(); + + }, delay); + + intervals[promise.$$intervalId] = deferred; + + return promise; + } - }, delay); - intervals[promise.$$intervalId] = deferred; + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {promise} promise returned by the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully canceled. + */ + interval.cancel = function (promise) { + if (promise && promise.$$intervalId in intervals) { + intervals[promise.$$intervalId].reject('canceled'); + $window.clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + return true; + } + return false; + }; - return promise; + return interval; + }]; } + /** + * @ngdoc service + * @name $locale + * + * @description + * $locale service provides localization rules for various Angular components. As of right now the + * only public api is: + * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + */ + function $LocaleProvider() { + this.$get = function () { + return { + id: 'en-us', + + NUMBER_FORMATS: { + DECIMAL_SEP: '.', + GROUP_SEP: ',', + PATTERNS: [ + { // Decimal Pattern + minInt: 1, + minFrac: 0, + maxFrac: 3, + posPre: '', + posSuf: '', + negPre: '-', + negSuf: '', + gSize: 3, + lgSize: 3 + }, { //Currency Pattern + minInt: 1, + minFrac: 2, + maxFrac: 2, + posPre: '\u00A4', + posSuf: '', + negPre: '(\u00A4', + negSuf: ')', + gSize: 3, + lgSize: 3 + } + ], + CURRENCY_SYM: '$' + }, + + DATETIME_FORMATS: { + MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' + .split(','), + SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), + AMPMS: ['AM', 'PM'], + medium: 'MMM d, y h:mm:ss a', + short: 'M/d/yy h:mm a', + fullDate: 'EEEE, MMMM d, y', + longDate: 'MMMM d, y', + mediumDate: 'MMM d, y', + shortDate: 'M/d/yy', + mediumTime: 'h:mm:ss a', + shortTime: 'h:mm a' + }, + + pluralCat: function (num) { + if (num === 1) { + return 'one'; + } + return 'other'; + } + }; + }; + } - /** - * @ngdoc method - * @name $interval#cancel - * - * @description - * Cancels a task associated with the `promise`. - * - * @param {promise} promise returned by the `$interval` function. - * @returns {boolean} Returns `true` if the task was successfully canceled. - */ - interval.cancel = function(promise) { - if (promise && promise.$$intervalId in intervals) { - intervals[promise.$$intervalId].reject('canceled'); - $window.clearInterval(promise.$$intervalId); - delete intervals[promise.$$intervalId]; - return true; - } - return false; - }; - - return interval; - }]; -} - -/** - * @ngdoc service - * @name $locale - * - * @description - * $locale service provides localization rules for various Angular components. As of right now the - * only public api is: - * - * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) - */ -function $LocaleProvider(){ - this.$get = function() { - return { - id: 'en-us', - - NUMBER_FORMATS: { - DECIMAL_SEP: '.', - GROUP_SEP: ',', - PATTERNS: [ - { // Decimal Pattern - minInt: 1, - minFrac: 0, - maxFrac: 3, - posPre: '', - posSuf: '', - negPre: '-', - negSuf: '', - gSize: 3, - lgSize: 3 - },{ //Currency Pattern - minInt: 1, - minFrac: 2, - maxFrac: 2, - posPre: '\u00A4', - posSuf: '', - negPre: '(\u00A4', - negSuf: ')', - gSize: 3, - lgSize: 3 - } - ], - CURRENCY_SYM: '$' - }, - - DATETIME_FORMATS: { - MONTH: - 'January,February,March,April,May,June,July,August,September,October,November,December' - .split(','), - SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), - DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), - SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), - AMPMS: ['AM','PM'], - medium: 'MMM d, y h:mm:ss a', - short: 'M/d/yy h:mm a', - fullDate: 'EEEE, MMMM d, y', - longDate: 'MMMM d, y', - mediumDate: 'MMM d, y', - shortDate: 'M/d/yy', - mediumTime: 'h:mm:ss a', - shortTime: 'h:mm a' - }, - - pluralCat: function(num) { - if (num === 1) { - return 'one'; - } - return 'other'; - } - }; - }; -} - -var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, - DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; -var $locationMinErr = minErr('$location'); - - -/** - * Encode path using encodeUriSegment, ignoring forward slashes - * - * @param {string} path Path to encode - * @returns {string} - */ -function encodePath(path) { - var segments = path.split('/'), - i = segments.length; - - while (i--) { - segments[i] = encodeUriSegment(segments[i]); - } - - return segments.join('/'); -} - -function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { - var parsedUrl = urlResolve(absoluteUrl, appBase); - - locationObj.$$protocol = parsedUrl.protocol; - locationObj.$$host = parsedUrl.hostname; - locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; -} - - -function parseAppUrl(relativeUrl, locationObj, appBase) { - var prefixed = (relativeUrl.charAt(0) !== '/'); - if (prefixed) { - relativeUrl = '/' + relativeUrl; - } - var match = urlResolve(relativeUrl, appBase); - locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? - match.pathname.substring(1) : match.pathname); - locationObj.$$search = parseKeyValue(match.search); - locationObj.$$hash = decodeURIComponent(match.hash); - - // make sure path starts with '/'; - if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { - locationObj.$$path = '/' + locationObj.$$path; - } -} - - -/** - * - * @param {string} begin - * @param {string} whole - * @returns {string} returns text from whole after begin or undefined if it does not begin with - * expected string. - */ -function beginsWith(begin, whole) { - if (whole.indexOf(begin) === 0) { - return whole.substr(begin.length); - } -} - - -function stripHash(url) { - var index = url.indexOf('#'); - return index == -1 ? url : url.substr(0, index); -} - + var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, + DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; + var $locationMinErr = minErr('$location'); -function stripFile(url) { - return url.substr(0, stripHash(url).lastIndexOf('/') + 1); -} -/* return the server only (scheme://host:port) */ -function serverBase(url) { - return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); -} + /** + * Encode path using encodeUriSegment, ignoring forward slashes + * + * @param {string} path Path to encode + * @returns {string} + */ + function encodePath(path) { + var segments = path.split('/'), + i = segments.length; + while (i--) { + segments[i] = encodeUriSegment(segments[i]); + } -/** - * LocationHtml5Url represents an url - * This object is exposed as $location service when HTML5 mode is enabled and supported - * - * @constructor - * @param {string} appBase application base URL - * @param {string} basePrefix url path prefix - */ -function LocationHtml5Url(appBase, basePrefix) { - this.$$html5 = true; - basePrefix = basePrefix || ''; - var appBaseNoFile = stripFile(appBase); - parseAbsoluteUrl(appBase, this, appBase); - - - /** - * Parse given html5 (regular) url string into properties - * @param {string} newAbsoluteUrl HTML5 url - * @private - */ - this.$$parse = function(url) { - var pathUrl = beginsWith(appBaseNoFile, url); - if (!isString(pathUrl)) { - throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, - appBaseNoFile); + return segments.join('/'); } - parseAppUrl(pathUrl, this, appBase); + function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { + var parsedUrl = urlResolve(absoluteUrl, appBase); - if (!this.$$path) { - this.$$path = '/'; + locationObj.$$protocol = parsedUrl.protocol; + locationObj.$$host = parsedUrl.hostname; + locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } - this.$$compose(); - }; - - /** - * Compose url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' - }; - - this.$$parseLinkUrl = function(url, relHref) { - if (relHref && relHref[0] === '#') { - // special case for links to hash fragments: - // keep the old url and only replace the hash fragment - this.hash(relHref.slice(1)); - return true; - } - var appUrl, prevAppUrl; - var rewrittenUrl; - - if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { - prevAppUrl = appUrl; - if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { - rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); - } else { - rewrittenUrl = appBase + prevAppUrl; - } - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { - rewrittenUrl = appBaseNoFile + appUrl; - } else if (appBaseNoFile == url + '/') { - rewrittenUrl = appBaseNoFile; - } - if (rewrittenUrl) { - this.$$parse(rewrittenUrl); - } - return !!rewrittenUrl; - }; -} - -/** - * LocationHashbangUrl represents url - * This object is exposed as $location service when developer doesn't opt into html5 mode. - * It also serves as the base class for html5 mode fallback on legacy browsers. - * - * @constructor - * @param {string} appBase application base URL - * @param {string} hashPrefix hashbang prefix - */ -function LocationHashbangUrl(appBase, hashPrefix) { - var appBaseNoFile = stripFile(appBase); - - parseAbsoluteUrl(appBase, this, appBase); - - - /** - * Parse given hashbang url into properties - * @param {string} url Hashbang url - * @private - */ - this.$$parse = function(url) { - var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); - var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' - ? beginsWith(hashPrefix, withoutBaseUrl) - : (this.$$html5) - ? withoutBaseUrl - : ''; - - if (!isString(withoutHashUrl)) { - throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, - hashPrefix); + function parseAppUrl(relativeUrl, locationObj, appBase) { + var prefixed = (relativeUrl.charAt(0) !== '/'); + if (prefixed) { + relativeUrl = '/' + relativeUrl; + } + var match = urlResolve(relativeUrl, appBase); + locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? + match.pathname.substring(1) : match.pathname); + locationObj.$$search = parseKeyValue(match.search); + locationObj.$$hash = decodeURIComponent(match.hash); + + // make sure path starts with '/'; + if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { + locationObj.$$path = '/' + locationObj.$$path; + } } - parseAppUrl(withoutHashUrl, this, appBase); - this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); - this.$$compose(); - - /* - * In Windows, on an anchor node on documents loaded from - * the filesystem, the browser will return a pathname - * prefixed with the drive name ('/C:/path') when a - * pathname without a drive is set: - * * a.setAttribute('href', '/foo') - * * a.pathname === '/C:/foo' //true - * - * Inside of Angular, we're always using pathnames that - * do not include drive names for routing. + /** + * + * @param {string} begin + * @param {string} whole + * @returns {string} returns text from whole after begin or undefined if it does not begin with + * expected string. */ - function removeWindowsDriveName (path, url, base) { - /* - Matches paths for file protocol on windows, - such as /C:/foo/bar, and captures only /foo/bar. - */ - var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; - - var firstPathSegmentMatch; - - //Get the relative path from the input URL. - if (url.indexOf(base) === 0) { - url = url.replace(base, ''); - } - - // The input URL intentionally contains a first path segment that ends with a colon. - if (windowsFilePathExp.exec(url)) { - return path; - } - - firstPathSegmentMatch = windowsFilePathExp.exec(path); - return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; - } - }; - - /** - * Compose hashbang url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); - }; - - this.$$parseLinkUrl = function(url, relHref) { - if(stripHash(appBase) == stripHash(url)) { - this.$$parse(url); - return true; + function beginsWith(begin, whole) { + if (whole.indexOf(begin) === 0) { + return whole.substr(begin.length); + } } - return false; - }; -} -/** - * LocationHashbangUrl represents url - * This object is exposed as $location service when html5 history api is enabled but the browser - * does not support it. - * - * @constructor - * @param {string} appBase application base URL - * @param {string} hashPrefix hashbang prefix - */ -function LocationHashbangInHtml5Url(appBase, hashPrefix) { - this.$$html5 = true; - LocationHashbangUrl.apply(this, arguments); - - var appBaseNoFile = stripFile(appBase); - - this.$$parseLinkUrl = function(url, relHref) { - if (relHref && relHref[0] === '#') { - // special case for links to hash fragments: - // keep the old url and only replace the hash fragment - this.hash(relHref.slice(1)); - return true; + function stripHash(url) { + var index = url.indexOf('#'); + return index == -1 ? url : url.substr(0, index); } - var rewrittenUrl; - var appUrl; - if ( appBase == stripHash(url) ) { - rewrittenUrl = url; - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { - rewrittenUrl = appBase + hashPrefix + appUrl; - } else if ( appBaseNoFile === url + '/') { - rewrittenUrl = appBaseNoFile; - } - if (rewrittenUrl) { - this.$$parse(rewrittenUrl); + function stripFile(url) { + return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } - return !!rewrittenUrl; - }; - - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' - this.$$absUrl = appBase + hashPrefix + this.$$url; - }; - -} + /* return the server only (scheme://host:port) */ + function serverBase(url) { + return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); + } -var locationPrototype = { - /** - * Are we in html5 mode? - * @private - */ - $$html5: false, + /** + * LocationHtml5Url represents an url + * This object is exposed as $location service when HTML5 mode is enabled and supported + * + * @constructor + * @param {string} appBase application base URL + * @param {string} basePrefix url path prefix + */ + function LocationHtml5Url(appBase, basePrefix) { + this.$$html5 = true; + basePrefix = basePrefix || ''; + var appBaseNoFile = stripFile(appBase); + parseAbsoluteUrl(appBase, this, appBase); - /** - * Has any change been replacing? - * @private - */ - $$replace: false, - /** - * @ngdoc method - * @name $location#absUrl - * - * @description - * This method is getter only. - * - * Return full url representation with all segments encoded according to rules specified in - * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). - * - * @return {string} full url - */ - absUrl: locationGetter('$$absUrl'), + /** + * Parse given html5 (regular) url string into properties + * @param {string} newAbsoluteUrl HTML5 url + * @private + */ + this.$$parse = function (url) { + var pathUrl = beginsWith(appBaseNoFile, url); + if (!isString(pathUrl)) { + throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, + appBaseNoFile); + } - /** - * @ngdoc method - * @name $location#url - * - * @description - * This method is getter / setter. - * - * Return url (e.g. `/path?a=b#hash`) when called without any parameter. - * - * Change path, search and hash, when called with parameter and return `$location`. - * - * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) - * @return {string} url - */ - url: function(url) { - if (isUndefined(url)) - return this.$$url; - - var match = PATH_MATCH.exec(url); - if (match[1]) this.path(decodeURIComponent(match[1])); - if (match[2] || match[1]) this.search(match[3] || ''); - this.hash(match[5] || ''); - - return this; - }, - - /** - * @ngdoc method - * @name $location#protocol - * - * @description - * This method is getter only. - * - * Return protocol of current url. - * - * @return {string} protocol of current url - */ - protocol: locationGetter('$$protocol'), + parseAppUrl(pathUrl, this, appBase); - /** - * @ngdoc method - * @name $location#host - * - * @description - * This method is getter only. - * - * Return host of current url. - * - * @return {string} host of current url. - */ - host: locationGetter('$$host'), + if (!this.$$path) { + this.$$path = '/'; + } - /** - * @ngdoc method - * @name $location#port - * - * @description - * This method is getter only. - * - * Return port of current url. - * - * @return {Number} port - */ - port: locationGetter('$$port'), + this.$$compose(); + }; - /** - * @ngdoc method - * @name $location#path - * - * @description - * This method is getter / setter. - * - * Return path of current url when called without any parameter. - * - * Change path when called with parameter and return `$location`. - * - * Note: Path should always begin with forward slash (/), this method will add the forward slash - * if it is missing. - * - * @param {(string|number)=} path New path - * @return {string} path - */ - path: locationGetterSetter('$$path', function(path) { - path = path !== null ? path.toString() : ''; - return path.charAt(0) == '/' ? path : '/' + path; - }), - - /** - * @ngdoc method - * @name $location#search - * - * @description - * This method is getter / setter. - * - * Return search part (as object) of current url when called without any parameter. - * - * Change search part when called with parameter and return `$location`. - * - * - * ```js - * // given url http://example.com/#/some/path?foo=bar&baz=xoxo - * var searchObject = $location.search(); - * // => {foo: 'bar', baz: 'xoxo'} - * - * - * // set foo to 'yipee' - * $location.search('foo', 'yipee'); - * // => $location - * ``` - * - * @param {string|Object.|Object.>} search New search params - string or - * hash object. - * - * When called with a single argument the method acts as a setter, setting the `search` component - * of `$location` to the specified value. - * - * If the argument is a hash object containing an array of values, these values will be encoded - * as duplicate search parameters in the url. - * - * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` - * will override only a single search property. - * - * If `paramValue` is an array, it will override the property of the `search` component of - * `$location` specified via the first argument. - * - * If `paramValue` is `null`, the property specified via the first argument will be deleted. - * - * If `paramValue` is `true`, the property specified via the first argument will be added with no - * value nor trailing equal sign. - * - * @return {Object} If called with no arguments returns the parsed `search` object. If called with - * one or more arguments returns `$location` object itself. - */ - search: function(search, paramValue) { - switch (arguments.length) { - case 0: - return this.$$search; - case 1: - if (isString(search) || isNumber(search)) { - search = search.toString(); - this.$$search = parseKeyValue(search); - } else if (isObject(search)) { - search = copy(search, {}); - // remove object undefined or null properties - forEach(search, function(value, key) { - if (value == null) delete search[key]; - }); + /** + * Compose url and update `absUrl` property + * @private + */ + this.$$compose = function () { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - this.$$search = search; - } else { - throw $locationMinErr('isrcharg', - 'The first argument of the `$location#search()` call must be a string or an object.'); - } - break; - default: - if (isUndefined(paramValue) || paramValue === null) { - delete this.$$search[search]; - } else { - this.$$search[search] = paramValue; - } - } + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' + }; - this.$$compose(); - return this; - }, + this.$$parseLinkUrl = function (url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } + var appUrl, prevAppUrl; + var rewrittenUrl; - /** - * @ngdoc method - * @name $location#hash - * - * @description - * This method is getter / setter. - * - * Return hash fragment when called without any parameter. - * - * Change hash fragment when called with parameter and return `$location`. - * - * @param {(string|number)=} hash New hash fragment - * @return {string} hash - */ - hash: locationGetterSetter('$$hash', function(hash) { - return hash !== null ? hash.toString() : ''; - }), - - /** - * @ngdoc method - * @name $location#replace - * - * @description - * If called, all changes to $location during current `$digest` will be replacing current history - * record, instead of adding new one. - */ - replace: function() { - this.$$replace = true; - return this; - } -}; - -forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function (Location) { - Location.prototype = Object.create(locationPrototype); - - /** - * @ngdoc method - * @name $location#state - * - * @description - * This method is getter / setter. - * - * Return the history state object when called without any parameter. - * - * Change the history state object when called with one parameter and return `$location`. - * The state object is later passed to `pushState` or `replaceState`. - * - * NOTE: This method is supported only in HTML5 mode and only in browsers supporting - * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support - * older browsers (like IE9 or Android < 4.0), don't use this method. - * - * @param {object=} state State object for pushState or replaceState - * @return {object} state - */ - Location.prototype.state = function(state) { - if (!arguments.length) - return this.$$state; - - if (Location !== LocationHtml5Url || !this.$$html5) { - throw $locationMinErr('nostate', 'History API state support is available only ' + - 'in HTML5 mode and only in browsers supporting HTML5 History API'); + if ((appUrl = beginsWith(appBase, url)) !== undefined) { + prevAppUrl = appUrl; + if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) { + rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + } else { + rewrittenUrl = appBase + prevAppUrl; + } + } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) { + rewrittenUrl = appBaseNoFile + appUrl; + } else if (appBaseNoFile == url + '/') { + rewrittenUrl = appBaseNoFile; + } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; + }; } - // The user might modify `stateObject` after invoking `$location.state(stateObject)` - // but we're changing the $$state reference to $browser.state() during the $digest - // so the modification window is narrow. - this.$$state = isUndefined(state) ? null : state; - return this; - }; -}); + /** + * LocationHashbangUrl represents url + * This object is exposed as $location service when developer doesn't opt into html5 mode. + * It also serves as the base class for html5 mode fallback on legacy browsers. + * + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix + */ + function LocationHashbangUrl(appBase, hashPrefix) { + var appBaseNoFile = stripFile(appBase); -function locationGetter(property) { - return function() { - return this[property]; - }; -} - + parseAbsoluteUrl(appBase, this, appBase); -function locationGetterSetter(property, preprocess) { - return function(value) { - if (isUndefined(value)) - return this[property]; - this[property] = preprocess(value); - this.$$compose(); + /** + * Parse given hashbang url into properties + * @param {string} url Hashbang url + * @private + */ + this.$$parse = function (url) { + var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); + var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' + ? beginsWith(hashPrefix, withoutBaseUrl) + : (this.$$html5) + ? withoutBaseUrl + : ''; + + if (!isString(withoutHashUrl)) { + throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, + hashPrefix); + } + parseAppUrl(withoutHashUrl, this, appBase); + + this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); + + this.$$compose(); + + /* + * In Windows, on an anchor node on documents loaded from + * the filesystem, the browser will return a pathname + * prefixed with the drive name ('/C:/path') when a + * pathname without a drive is set: + * * a.setAttribute('href', '/foo') + * * a.pathname === '/C:/foo' //true + * + * Inside of Angular, we're always using pathnames that + * do not include drive names for routing. + */ + function removeWindowsDriveName(path, url, base) { + /* + Matches paths for file protocol on windows, + such as /C:/foo/bar, and captures only /foo/bar. + */ + var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; + + var firstPathSegmentMatch; + + //Get the relative path from the input URL. + if (url.indexOf(base) === 0) { + url = url.replace(base, ''); + } - return this; - }; -} + // The input URL intentionally contains a first path segment that ends with a colon. + if (windowsFilePathExp.exec(url)) { + return path; + } + firstPathSegmentMatch = windowsFilePathExp.exec(path); + return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; + } + }; -/** - * @ngdoc service - * @name $location - * - * @requires $rootElement - * - * @description - * The $location service parses the URL in the browser address bar (based on the - * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL - * available to your application. Changes to the URL in the address bar are reflected into - * $location service and changes to $location are reflected into the browser address bar. - * - * **The $location service:** - * - * - Exposes the current URL in the browser address bar, so you can - * - Watch and observe the URL. - * - Change the URL. - * - Synchronizes the URL with the browser when the user - * - Changes the address bar. - * - Clicks the back or forward button (or clicks a History link). - * - Clicks on a link. - * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). - * - * For more information see {@link guide/$location Developer Guide: Using $location} - */ + /** + * Compose hashbang url and update `absUrl` property + * @private + */ + this.$$compose = function () { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; -/** - * @ngdoc provider - * @name $locationProvider - * @description - * Use the `$locationProvider` to configure how the application deep linking paths are stored. - */ -function $LocationProvider(){ - var hashPrefix = '', - html5Mode = { - enabled: false, - requireBase: true, - rewriteLinks: true - }; + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); + }; - /** - * @ngdoc method - * @name $locationProvider#hashPrefix - * @description - * @param {string=} prefix Prefix for hash part (containing path and search) - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.hashPrefix = function(prefix) { - if (isDefined(prefix)) { - hashPrefix = prefix; - return this; - } else { - return hashPrefix; + this.$$parseLinkUrl = function (url, relHref) { + if (stripHash(appBase) == stripHash(url)) { + this.$$parse(url); + return true; + } + return false; + }; } - }; - - /** - * @ngdoc method - * @name $locationProvider#html5Mode - * @description - * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. - * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported - * properties: - * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to - * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not - * support `pushState`. - * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies - * whether or not a tag is required to be present. If `enabled` and `requireBase` are - * true, and a base tag is not present, an error will be thrown when `$location` is injected. - * See the {@link guide/$location $location guide for more information} - * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled, - * enables/disables url rewriting for relative links. - * - * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter - */ - this.html5Mode = function(mode) { - if (isBoolean(mode)) { - html5Mode.enabled = mode; - return this; - } else if (isObject(mode)) { - - if (isBoolean(mode.enabled)) { - html5Mode.enabled = mode.enabled; - } - if (isBoolean(mode.requireBase)) { - html5Mode.requireBase = mode.requireBase; - } - if (isBoolean(mode.rewriteLinks)) { - html5Mode.rewriteLinks = mode.rewriteLinks; - } + /** + * LocationHashbangUrl represents url + * This object is exposed as $location service when html5 history api is enabled but the browser + * does not support it. + * + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix + */ + function LocationHashbangInHtml5Url(appBase, hashPrefix) { + this.$$html5 = true; + LocationHashbangUrl.apply(this, arguments); - return this; - } else { - return html5Mode; - } - }; - - /** - * @ngdoc event - * @name $location#$locationChangeStart - * @eventType broadcast on root scope - * @description - * Broadcasted before a URL will change. - * - * This change can be prevented by calling - * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more - * details about event object. Upon successful change - * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. - * - * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when - * the browser supports the HTML5 History API. - * - * @param {Object} angularEvent Synthetic event object. - * @param {string} newUrl New URL - * @param {string=} oldUrl URL that was before it was changed. - * @param {string=} newState New history state object - * @param {string=} oldState History state object that was before it was changed. - */ - - /** - * @ngdoc event - * @name $location#$locationChangeSuccess - * @eventType broadcast on root scope - * @description - * Broadcasted after a URL was changed. - * - * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when - * the browser supports the HTML5 History API. - * - * @param {Object} angularEvent Synthetic event object. - * @param {string} newUrl New URL - * @param {string=} oldUrl URL that was before it was changed. - * @param {string=} newState New history state object - * @param {string=} oldState History state object that was before it was changed. - */ - - this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', - function( $rootScope, $browser, $sniffer, $rootElement) { - var $location, - LocationMode, - baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' - initialUrl = $browser.url(), - appBase; - - if (html5Mode.enabled) { - if (!baseHref && html5Mode.requireBase) { - throw $locationMinErr('nobase', - "$location in HTML5 mode requires a tag to be present!"); - } - appBase = serverBase(initialUrl) + (baseHref || '/'); - LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; - } else { - appBase = stripHash(initialUrl); - LocationMode = LocationHashbangUrl; - } - $location = new LocationMode(appBase, '#' + hashPrefix); - $location.$$parseLinkUrl(initialUrl, initialUrl); + var appBaseNoFile = stripFile(appBase); + + this.$$parseLinkUrl = function (url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } - $location.$$state = $browser.state(); + var rewrittenUrl; + var appUrl; - var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + if (appBase == stripHash(url)) { + rewrittenUrl = url; + } else if ((appUrl = beginsWith(appBaseNoFile, url))) { + rewrittenUrl = appBase + hashPrefix + appUrl; + } else if (appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; + } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; + }; - function setBrowserUrlWithFallback(url, replace, state) { - var oldUrl = $location.url(); - var oldState = $location.$$state; - try { - $browser.url(url, replace, state); + this.$$compose = function () { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - // Make sure $location.state() returns referentially identical (not just deeply equal) - // state object; this makes possible quick checking if the state changed in the digest - // loop. Checking deep equality would be too expensive. - $location.$$state = $browser.state(); - } catch (e) { - // Restore old values if pushState fails - $location.url(oldUrl); - $location.$$state = oldState; + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' + this.$$absUrl = appBase + hashPrefix + this.$$url; + }; - throw e; - } } - $rootElement.on('click', function(event) { - // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) - // currently we open nice url link and redirect then - - if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return; - var elm = jqLite(event.target); + var locationPrototype = { - // traverse the DOM up to find first A tag - while (nodeName_(elm[0]) !== 'a') { - // ignore rewriting if no A tag (reached root element, or no parent - removed from document) - if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; - } + /** + * Are we in html5 mode? + * @private + */ + $$html5: false, - var absHref = elm.prop('href'); - // get the actual href attribute - see - // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx - var relHref = elm.attr('href') || elm.attr('xlink:href'); + /** + * Has any change been replacing? + * @private + */ + $$replace: false, - if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { - // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during - // an animation. - absHref = urlResolve(absHref.animVal).href; - } + /** + * @ngdoc method + * @name $location#absUrl + * + * @description + * This method is getter only. + * + * Return full url representation with all segments encoded according to rules specified in + * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). + * + * @return {string} full url + */ + absUrl: locationGetter('$$absUrl'), - // Ignore when url is started with javascript: or mailto: - if (IGNORE_URI_REGEXP.test(absHref)) return; - - if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { - if ($location.$$parseLinkUrl(absHref, relHref)) { - // We do a preventDefault for all urls that are part of the angular application, - // in html5mode and also without, so that we are able to abort navigation without - // getting double entries in the location history. - event.preventDefault(); - // update location manually - if ($location.absUrl() != $browser.url()) { - $rootScope.$apply(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - window.angular['ff-684208-preventDefault'] = true; - } - } - } - }); + /** + * @ngdoc method + * @name $location#url + * + * @description + * This method is getter / setter. + * + * Return url (e.g. `/path?a=b#hash`) when called without any parameter. + * + * Change path, search and hash, when called with parameter and return `$location`. + * + * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) + * @return {string} url + */ + url: function (url) { + if (isUndefined(url)) + return this.$$url; + var match = PATH_MATCH.exec(url); + if (match[1]) this.path(decodeURIComponent(match[1])); + if (match[2] || match[1]) this.search(match[3] || ''); + this.hash(match[5] || ''); - // rewrite hashbang url <> html5 url - if ($location.absUrl() != initialUrl) { - $browser.url($location.absUrl(), true); - } + return this; + }, - var initializing = true; - - // update $location when $browser url changes - $browser.onUrlChange(function(newUrl, newState) { - $rootScope.$evalAsync(function() { - var oldUrl = $location.absUrl(); - var oldState = $location.$$state; - - $location.$$parse(newUrl); - $location.$$state = newState; - if ($rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, - newState, oldState).defaultPrevented) { - $location.$$parse(oldUrl); - $location.$$state = oldState; - setBrowserUrlWithFallback(oldUrl, false, oldState); - } else { - initializing = false; - afterLocationChange(oldUrl, oldState); - } - }); - if (!$rootScope.$$phase) $rootScope.$digest(); - }); + /** + * @ngdoc method + * @name $location#protocol + * + * @description + * This method is getter only. + * + * Return protocol of current url. + * + * @return {string} protocol of current url + */ + protocol: locationGetter('$$protocol'), - // update browser - $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); - var oldState = $browser.state(); - var currentReplace = $location.$$replace; - var urlOrStateChanged = oldUrl !== $location.absUrl() || - ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); - - if (initializing || urlOrStateChanged) { - initializing = false; - - $rootScope.$evalAsync(function() { - if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl, - $location.$$state, oldState).defaultPrevented) { - $location.$$parse(oldUrl); - $location.$$state = oldState; - } else { - if (urlOrStateChanged) { - setBrowserUrlWithFallback($location.absUrl(), currentReplace, - oldState === $location.$$state ? null : $location.$$state); - } - afterLocationChange(oldUrl, oldState); - } - }); - } + /** + * @ngdoc method + * @name $location#host + * + * @description + * This method is getter only. + * + * Return host of current url. + * + * @return {string} host of current url. + */ + host: locationGetter('$$host'), - $location.$$replace = false; + /** + * @ngdoc method + * @name $location#port + * + * @description + * This method is getter only. + * + * Return port of current url. + * + * @return {Number} port + */ + port: locationGetter('$$port'), - // we don't need to return anything because $evalAsync will make the digest loop dirty when - // there is a change + /** + * @ngdoc method + * @name $location#path + * + * @description + * This method is getter / setter. + * + * Return path of current url when called without any parameter. + * + * Change path when called with parameter and return `$location`. + * + * Note: Path should always begin with forward slash (/), this method will add the forward slash + * if it is missing. + * + * @param {(string|number)=} path New path + * @return {string} path + */ + path: locationGetterSetter('$$path', function (path) { + path = path !== null ? path.toString() : ''; + return path.charAt(0) == '/' ? path : '/' + path; + }), + + /** + * @ngdoc method + * @name $location#search + * + * @description + * This method is getter / setter. + * + * Return search part (as object) of current url when called without any parameter. + * + * Change search part when called with parameter and return `$location`. + * + * + * ```js + * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * var searchObject = $location.search(); + * // => {foo: 'bar', baz: 'xoxo'} + * + * + * // set foo to 'yipee' + * $location.search('foo', 'yipee'); + * // => $location + * ``` + * + * @param {string|Object.|Object.>} search New search params - string or + * hash object. + * + * When called with a single argument the method acts as a setter, setting the `search` component + * of `$location` to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded + * as duplicate search parameters in the url. + * + * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` + * will override only a single search property. + * + * If `paramValue` is an array, it will override the property of the `search` component of + * `$location` specified via the first argument. + * + * If `paramValue` is `null`, the property specified via the first argument will be deleted. + * + * If `paramValue` is `true`, the property specified via the first argument will be added with no + * value nor trailing equal sign. + * + * @return {Object} If called with no arguments returns the parsed `search` object. If called with + * one or more arguments returns `$location` object itself. + */ + search: function (search, paramValue) { + switch (arguments.length) { + case 0: + return this.$$search; + case 1: + if (isString(search) || isNumber(search)) { + search = search.toString(); + this.$$search = parseKeyValue(search); + } else if (isObject(search)) { + search = copy(search, {}); + // remove object undefined or null properties + forEach(search, function (value, key) { + if (value == null) delete search[key]; + }); + + this.$$search = search; + } else { + throw $locationMinErr('isrcharg', + 'The first argument of the `$location#search()` call must be a string or an object.'); + } + break; + default: + if (isUndefined(paramValue) || paramValue === null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } + } + + this.$$compose(); + return this; + }, + + /** + * @ngdoc method + * @name $location#hash + * + * @description + * This method is getter / setter. + * + * Return hash fragment when called without any parameter. + * + * Change hash fragment when called with parameter and return `$location`. + * + * @param {(string|number)=} hash New hash fragment + * @return {string} hash + */ + hash: locationGetterSetter('$$hash', function (hash) { + return hash !== null ? hash.toString() : ''; + }), + + /** + * @ngdoc method + * @name $location#replace + * + * @description + * If called, all changes to $location during current `$digest` will be replacing current history + * record, instead of adding new one. + */ + replace: function () { + this.$$replace = true; + return this; + } + }; + + forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function (Location) { + Location.prototype = Object.create(locationPrototype); + + /** + * @ngdoc method + * @name $location#state + * + * @description + * This method is getter / setter. + * + * Return the history state object when called without any parameter. + * + * Change the history state object when called with one parameter and return `$location`. + * The state object is later passed to `pushState` or `replaceState`. + * + * NOTE: This method is supported only in HTML5 mode and only in browsers supporting + * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support + * older browsers (like IE9 or Android < 4.0), don't use this method. + * + * @param {object=} state State object for pushState or replaceState + * @return {object} state + */ + Location.prototype.state = function (state) { + if (!arguments.length) + return this.$$state; + + if (Location !== LocationHtml5Url || !this.$$html5) { + throw $locationMinErr('nostate', 'History API state support is available only ' + + 'in HTML5 mode and only in browsers supporting HTML5 History API'); + } + // The user might modify `stateObject` after invoking `$location.state(stateObject)` + // but we're changing the $$state reference to $browser.state() during the $digest + // so the modification window is narrow. + this.$$state = isUndefined(state) ? null : state; + + return this; + }; }); - return $location; - function afterLocationChange(oldUrl, oldState) { - $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, - $location.$$state, oldState); + function locationGetter(property) { + return function () { + return this[property]; + }; } -}]; -} -/** - * @ngdoc service - * @name $log - * @requires $window - * - * @description - * Simple service for logging. Default implementation safely writes the message - * into the browser's console (if present). - * - * The main purpose of this service is to simplify debugging and troubleshooting. - * - * The default is to log `debug` messages. You can use - * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. - * - * @example - + + function locationGetterSetter(property, preprocess) { + return function (value) { + if (isUndefined(value)) + return this[property]; + + this[property] = preprocess(value); + this.$$compose(); + + return this; + }; + } + + + /** + * @ngdoc service + * @name $location + * + * @requires $rootElement + * + * @description + * The $location service parses the URL in the browser address bar (based on the + * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL + * available to your application. Changes to the URL in the address bar are reflected into + * $location service and changes to $location are reflected into the browser address bar. + * + * **The $location service:** + * + * - Exposes the current URL in the browser address bar, so you can + * - Watch and observe the URL. + * - Change the URL. + * - Synchronizes the URL with the browser when the user + * - Changes the address bar. + * - Clicks the back or forward button (or clicks a History link). + * - Clicks on a link. + * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). + * + * For more information see {@link guide/$location Developer Guide: Using $location} + */ + + /** + * @ngdoc provider + * @name $locationProvider + * @description + * Use the `$locationProvider` to configure how the application deep linking paths are stored. + */ + function $LocationProvider() { + var hashPrefix = '', + html5Mode = { + enabled: false, + requireBase: true, + rewriteLinks: true + }; + + /** + * @ngdoc method + * @name $locationProvider#hashPrefix + * @description + * @param {string=} prefix Prefix for hash part (containing path and search) + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.hashPrefix = function (prefix) { + if (isDefined(prefix)) { + hashPrefix = prefix; + return this; + } else { + return hashPrefix; + } + }; + + /** + * @ngdoc method + * @name $locationProvider#html5Mode + * @description + * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. + * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported + * properties: + * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to + * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not + * support `pushState`. + * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies + * whether or not a tag is required to be present. If `enabled` and `requireBase` are + * true, and a base tag is not present, an error will be thrown when `$location` is injected. + * See the {@link guide/$location $location guide for more information} + * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled, + * enables/disables url rewriting for relative links. + * + * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter + */ + this.html5Mode = function (mode) { + if (isBoolean(mode)) { + html5Mode.enabled = mode; + return this; + } else if (isObject(mode)) { + + if (isBoolean(mode.enabled)) { + html5Mode.enabled = mode.enabled; + } + + if (isBoolean(mode.requireBase)) { + html5Mode.requireBase = mode.requireBase; + } + + if (isBoolean(mode.rewriteLinks)) { + html5Mode.rewriteLinks = mode.rewriteLinks; + } + + return this; + } else { + return html5Mode; + } + }; + + /** + * @ngdoc event + * @name $location#$locationChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a URL will change. + * + * This change can be prevented by calling + * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more + * details about event object. Upon successful change + * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. + * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. + */ + + /** + * @ngdoc event + * @name $location#$locationChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a URL was changed. + * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. + */ + + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', + function ($rootScope, $browser, $sniffer, $rootElement) { + var $location, + LocationMode, + baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' + initialUrl = $browser.url(), + appBase; + + if (html5Mode.enabled) { + if (!baseHref && html5Mode.requireBase) { + throw $locationMinErr('nobase', + "$location in HTML5 mode requires a tag to be present!"); + } + appBase = serverBase(initialUrl) + (baseHref || '/'); + LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; + } else { + appBase = stripHash(initialUrl); + LocationMode = LocationHashbangUrl; + } + $location = new LocationMode(appBase, '#' + hashPrefix); + $location.$$parseLinkUrl(initialUrl, initialUrl); + + $location.$$state = $browser.state(); + + var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + + function setBrowserUrlWithFallback(url, replace, state) { + var oldUrl = $location.url(); + var oldState = $location.$$state; + try { + $browser.url(url, replace, state); + + // Make sure $location.state() returns referentially identical (not just deeply equal) + // state object; this makes possible quick checking if the state changed in the digest + // loop. Checking deep equality would be too expensive. + $location.$$state = $browser.state(); + } catch (e) { + // Restore old values if pushState fails + $location.url(oldUrl); + $location.$$state = oldState; + + throw e; + } + } + + $rootElement.on('click', function (event) { + // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) + // currently we open nice url link and redirect then + + if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return; + + var elm = jqLite(event.target); + + // traverse the DOM up to find first A tag + while (nodeName_(elm[0]) !== 'a') { + // ignore rewriting if no A tag (reached root element, or no parent - removed from document) + if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; + } + + var absHref = elm.prop('href'); + // get the actual href attribute - see + // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx + var relHref = elm.attr('href') || elm.attr('xlink:href'); + + if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { + // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during + // an animation. + absHref = urlResolve(absHref.animVal).href; + } + + // Ignore when url is started with javascript: or mailto: + if (IGNORE_URI_REGEXP.test(absHref)) return; + + if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { + if ($location.$$parseLinkUrl(absHref, relHref)) { + // We do a preventDefault for all urls that are part of the angular application, + // in html5mode and also without, so that we are able to abort navigation without + // getting double entries in the location history. + event.preventDefault(); + // update location manually + if ($location.absUrl() != $browser.url()) { + $rootScope.$apply(); + // hack to work around FF6 bug 684208 when scenario runner clicks on links + window.angular['ff-684208-preventDefault'] = true; + } + } + } + }); + + + // rewrite hashbang url <> html5 url + if ($location.absUrl() != initialUrl) { + $browser.url($location.absUrl(), true); + } + + var initializing = true; + + // update $location when $browser url changes + $browser.onUrlChange(function (newUrl, newState) { + $rootScope.$evalAsync(function () { + var oldUrl = $location.absUrl(); + var oldState = $location.$$state; + + $location.$$parse(newUrl); + $location.$$state = newState; + if ($rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + newState, oldState).defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + setBrowserUrlWithFallback(oldUrl, false, oldState); + } else { + initializing = false; + afterLocationChange(oldUrl, oldState); + } + }); + if (!$rootScope.$$phase) $rootScope.$digest(); + }); + + // update browser + $rootScope.$watch(function $locationWatch() { + var oldUrl = $browser.url(); + var oldState = $browser.state(); + var currentReplace = $location.$$replace; + var urlOrStateChanged = oldUrl !== $location.absUrl() || + ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); + + if (initializing || urlOrStateChanged) { + initializing = false; + + $rootScope.$evalAsync(function () { + if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl, + $location.$$state, oldState).defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + } else { + if (urlOrStateChanged) { + setBrowserUrlWithFallback($location.absUrl(), currentReplace, + oldState === $location.$$state ? null : $location.$$state); + } + afterLocationChange(oldUrl, oldState); + } + }); + } + + $location.$$replace = false; + + // we don't need to return anything because $evalAsync will make the digest loop dirty when + // there is a change + }); + + return $location; + + function afterLocationChange(oldUrl, oldState) { + $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, + $location.$$state, oldState); + } + }]; + } + + /** + * @ngdoc service + * @name $log + * @requires $window + * + * @description + * Simple service for logging. Default implementation safely writes the message + * into the browser's console (if present). + * + * The main purpose of this service is to simplify debugging and troubleshooting. + * + * The default is to log `debug` messages. You can use + * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. + * + * @example + - angular.module('logExample', []) - .controller('LogController', ['$scope', '$log', function($scope, $log) { + angular.module('logExample', []) + .controller('LogController', ['$scope', '$log', function($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; }]); -
          -

          Reload this page with open console, enter text and hit the log button...

          - Message: - - - - - -
          +
          +

          Reload this page with open console, enter text and hit the log button...

          + Message: + + + + + +
          -
          - */ +
          + */ -/** - * @ngdoc provider - * @name $logProvider - * @description - * Use the `$logProvider` to configure how the application logs messages - */ -function $LogProvider(){ - var debug = true, - self = this; - - /** - * @ngdoc method - * @name $logProvider#debugEnabled - * @description - * @param {boolean=} flag enable or disable debug level messages - * @returns {*} current value if used as getter or itself (chaining) if used as setter - */ - this.debugEnabled = function(flag) { - if (isDefined(flag)) { - debug = flag; - return this; - } else { - return debug; - } - }; + /** + * @ngdoc provider + * @name $logProvider + * @description + * Use the `$logProvider` to configure how the application logs messages + */ + function $LogProvider() { + var debug = true, + self = this; - this.$get = ['$window', function($window){ - return { - /** - * @ngdoc method - * @name $log#log - * - * @description - * Write a log message - */ - log: consoleLog('log'), - - /** - * @ngdoc method - * @name $log#info - * - * @description - * Write an information message - */ - info: consoleLog('info'), - - /** - * @ngdoc method - * @name $log#warn - * - * @description - * Write a warning message - */ - warn: consoleLog('warn'), - - /** - * @ngdoc method - * @name $log#error - * - * @description - * Write an error message - */ - error: consoleLog('error'), - - /** - * @ngdoc method - * @name $log#debug - * - * @description - * Write a debug message - */ - debug: (function () { - var fn = consoleLog('debug'); - - return function() { - if (debug) { - fn.apply(self, arguments); - } + /** + * @ngdoc method + * @name $logProvider#debugEnabled + * @description + * @param {boolean=} flag enable or disable debug level messages + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.debugEnabled = function (flag) { + if (isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } }; - }()) - }; - function formatError(arg) { - if (arg instanceof Error) { - if (arg.stack) { - arg = (arg.message && arg.stack.indexOf(arg.message) === -1) - ? 'Error: ' + arg.message + '\n' + arg.stack - : arg.stack; - } else if (arg.sourceURL) { - arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; - } - } - return arg; - } + this.$get = ['$window', function ($window) { + return { + /** + * @ngdoc method + * @name $log#log + * + * @description + * Write a log message + */ + log: consoleLog('log'), + + /** + * @ngdoc method + * @name $log#info + * + * @description + * Write an information message + */ + info: consoleLog('info'), + + /** + * @ngdoc method + * @name $log#warn + * + * @description + * Write a warning message + */ + warn: consoleLog('warn'), + + /** + * @ngdoc method + * @name $log#error + * + * @description + * Write an error message + */ + error: consoleLog('error'), + + /** + * @ngdoc method + * @name $log#debug + * + * @description + * Write a debug message + */ + debug: (function () { + var fn = consoleLog('debug'); + + return function () { + if (debug) { + fn.apply(self, arguments); + } + }; + }()) + }; - function consoleLog(type) { - var console = $window.console || {}, - logFn = console[type] || console.log || noop, - hasApply = false; - - // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. - // The reason behind this is that console.log has type "object" in IE8... - try { - hasApply = !!logFn.apply; - } catch (e) {} - - if (hasApply) { - return function() { - var args = []; - forEach(arguments, function(arg) { - args.push(formatError(arg)); - }); - return logFn.apply(console, args); - }; - } + function formatError(arg) { + if (arg instanceof Error) { + if (arg.stack) { + arg = (arg.message && arg.stack.indexOf(arg.message) === -1) + ? 'Error: ' + arg.message + '\n' + arg.stack + : arg.stack; + } else if (arg.sourceURL) { + arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; + } + } + return arg; + } - // we are IE which either doesn't have window.console => this is noop and we do nothing, - // or we are IE where console.log doesn't have apply so we log at least first 2 args - return function(arg1, arg2) { - logFn(arg1, arg2 == null ? '' : arg2); - }; + function consoleLog(type) { + var console = $window.console || {}, + logFn = console[type] || console.log || noop, + hasApply = false; + + // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. + // The reason behind this is that console.log has type "object" in IE8... + try { + hasApply = !!logFn.apply; + } catch (e) { + } + + if (hasApply) { + return function () { + var args = []; + forEach(arguments, function (arg) { + args.push(formatError(arg)); + }); + return logFn.apply(console, args); + }; + } + + // we are IE which either doesn't have window.console => this is noop and we do nothing, + // or we are IE where console.log doesn't have apply so we log at least first 2 args + return function (arg1, arg2) { + logFn(arg1, arg2 == null ? '' : arg2); + }; + } + }]; } - }]; -} -var $parseMinErr = minErr('$parse'); + var $parseMinErr = minErr('$parse'); // Sandboxing Angular Expressions // ------------------------------ @@ -11392,1240 +11456,1284 @@ var $parseMinErr = minErr('$parse'); // native objects. -function ensureSafeMemberName(name, fullExpression) { - if (name === "__defineGetter__" || name === "__defineSetter__" - || name === "__lookupGetter__" || name === "__lookupSetter__" - || name === "__proto__") { - throw $parseMinErr('isecfld', - 'Attempting to access a disallowed field in Angular expressions! ' - +'Expression: {0}', fullExpression); - } - return name; -} - -function ensureSafeObject(obj, fullExpression) { - // nifty check if obj is Function that is fast and works across iframes and other contexts - if (obj) { - if (obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isWindow(obj) - obj.window === obj) { - throw $parseMinErr('isecwindow', - 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isElement(obj) - obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { - throw $parseMinErr('isecdom', - 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// block Object so that we can't get hold of dangerous Object.* methods - obj === Object) { - throw $parseMinErr('isecobj', - 'Referencing Object in Angular expressions is disallowed! Expression: {0}', - fullExpression); + function ensureSafeMemberName(name, fullExpression) { + if (name === "__defineGetter__" || name === "__defineSetter__" + || name === "__lookupGetter__" || name === "__lookupSetter__" + || name === "__proto__") { + throw $parseMinErr('isecfld', + 'Attempting to access a disallowed field in Angular expressions! ' + + 'Expression: {0}', fullExpression); + } + return name; + } + + function ensureSafeObject(obj, fullExpression) { + // nifty check if obj is Function that is fast and works across iframes and other contexts + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isWindow(obj) + obj.window === obj) { + throw $parseMinErr('isecwindow', + 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isElement(obj) + obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { + throw $parseMinErr('isecdom', + 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// block Object so that we can't get hold of dangerous Object.* methods + obj === Object) { + throw $parseMinErr('isecobj', + 'Referencing Object in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } + return obj; } - } - return obj; -} - -var CALL = Function.prototype.call; -var APPLY = Function.prototype.apply; -var BIND = Function.prototype.bind; - -function ensureSafeFunction(obj, fullExpression) { - if (obj) { - if (obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (obj === CALL || obj === APPLY || obj === BIND) { - throw $parseMinErr('isecff', - 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', - fullExpression); + + var CALL = Function.prototype.call; + var APPLY = Function.prototype.apply; + var BIND = Function.prototype.bind; + + function ensureSafeFunction(obj, fullExpression) { + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (obj === CALL || obj === APPLY || obj === BIND) { + throw $parseMinErr('isecff', + 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } } - } -} //Keyword constants -var CONSTANTS = createMap(); -forEach({ - 'null': function() { return null; }, - 'true': function() { return true; }, - 'false': function() { return false; }, - 'undefined': function() {} -}, function(constantGetter, name) { - constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true; - CONSTANTS[name] = constantGetter; -}); + var CONSTANTS = createMap(); + forEach({ + 'null': function () { + return null; + }, + 'true': function () { + return true; + }, + 'false': function () { + return false; + }, + 'undefined': function () { + } + }, function (constantGetter, name) { + constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true; + CONSTANTS[name] = constantGetter; + }); //Not quite a constant, but can be lex/parsed the same -CONSTANTS['this'] = function(self) { return self; }; -CONSTANTS['this'].sharedGetter = true; + CONSTANTS['this'] = function (self) { + return self; + }; + CONSTANTS['this'].sharedGetter = true; //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter -var OPERATORS = extend(createMap(), { - '+':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - if (isDefined(a)) { - if (isDefined(b)) { - return a + b; - } - return a; - } - return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - return (isDefined(a)?a:0)-(isDefined(b)?b:0); + var OPERATORS = extend(createMap(), { + '+': function (self, locals, a, b) { + a = a(self, locals); + b = b(self, locals); + if (isDefined(a)) { + if (isDefined(b)) { + return a + b; + } + return a; + } + return isDefined(b) ? b : undefined; + }, + '-': function (self, locals, a, b) { + a = a(self, locals); + b = b(self, locals); + return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0); + }, + '*': function (self, locals, a, b) { + return a(self, locals) * b(self, locals); + }, + '/': function (self, locals, a, b) { + return a(self, locals) / b(self, locals); + }, + '%': function (self, locals, a, b) { + return a(self, locals) % b(self, locals); + }, + '===': function (self, locals, a, b) { + return a(self, locals) === b(self, locals); + }, + '!==': function (self, locals, a, b) { + return a(self, locals) !== b(self, locals); + }, + '==': function (self, locals, a, b) { + return a(self, locals) == b(self, locals); + }, + '!=': function (self, locals, a, b) { + return a(self, locals) != b(self, locals); + }, + '<': function (self, locals, a, b) { + return a(self, locals) < b(self, locals); + }, + '>': function (self, locals, a, b) { + return a(self, locals) > b(self, locals); + }, + '<=': function (self, locals, a, b) { + return a(self, locals) <= b(self, locals); + }, + '>=': function (self, locals, a, b) { + return a(self, locals) >= b(self, locals); + }, + '&&': function (self, locals, a, b) { + return a(self, locals) && b(self, locals); + }, + '||': function (self, locals, a, b) { + return a(self, locals) || b(self, locals); + }, + '!': function (self, locals, a) { + return !a(self, locals); }, - '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, - '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, - '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, - '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, - '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, - '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, - '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, - '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, - '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, - '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, - '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, - '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, - '!':function(self, locals, a){return !a(self, locals);}, - - //Tokenized as operators but parsed as assignment/filters - '=':true, - '|':true -}); -var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; - - -///////////////////////////////////////// - - -/** - * @constructor - */ -var Lexer = function (options) { - this.options = options; -}; - -Lexer.prototype = { - constructor: Lexer, - - lex: function (text) { - this.text = text; - this.index = 0; - this.ch = undefined; - this.tokens = []; - - while (this.index < this.text.length) { - this.ch = this.text.charAt(this.index); - if (this.is('"\'')) { - this.readString(this.ch); - } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { - this.readNumber(); - } else if (this.isIdent(this.ch)) { - this.readIdent(); - } else if (this.is('(){}[].,;:?')) { - this.tokens.push({ - index: this.index, - text: this.ch - }); - this.index++; - } else if (this.isWhitespace(this.ch)) { - this.index++; - } else { - var ch2 = this.ch + this.peek(); - var ch3 = ch2 + this.peek(2); - var fn = OPERATORS[this.ch]; - var fn2 = OPERATORS[ch2]; - var fn3 = OPERATORS[ch3]; - if (fn3) { - this.tokens.push({index: this.index, text: ch3, fn: fn3}); - this.index += 3; - } else if (fn2) { - this.tokens.push({index: this.index, text: ch2, fn: fn2}); - this.index += 2; - } else if (fn) { - this.tokens.push({ - index: this.index, - text: this.ch, - fn: fn - }); - this.index += 1; - } else { - this.throwError('Unexpected next character ', this.index, this.index + 1); - } - } - } - return this.tokens; - }, - - is: function(chars) { - return chars.indexOf(this.ch) !== -1; - }, - - peek: function(i) { - var num = i || 1; - return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; - }, - isNumber: function(ch) { - return ('0' <= ch && ch <= '9'); - }, + //Tokenized as operators but parsed as assignment/filters + '=': true, + '|': true + }); + var ESCAPE = {"n": "\n", "f": "\f", "r": "\r", "t": "\t", "v": "\v", "'": "'", '"': '"'}; - isWhitespace: function(ch) { - // IE treats non-breaking space as \u00A0 - return (ch === ' ' || ch === '\r' || ch === '\t' || - ch === '\n' || ch === '\v' || ch === '\u00A0'); - }, - isIdent: function(ch) { - return ('a' <= ch && ch <= 'z' || - 'A' <= ch && ch <= 'Z' || - '_' === ch || ch === '$'); - }, - - isExpOperator: function(ch) { - return (ch === '-' || ch === '+' || this.isNumber(ch)); - }, - - throwError: function(error, start, end) { - end = end || this.index; - var colStr = (isDefined(start) - ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' - : ' ' + end); - throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', - error, colStr, this.text); - }, - - readNumber: function() { - var number = ''; - var start = this.index; - while (this.index < this.text.length) { - var ch = lowercase(this.text.charAt(this.index)); - if (ch == '.' || this.isNumber(ch)) { - number += ch; - } else { - var peekCh = this.peek(); - if (ch == 'e' && this.isExpOperator(peekCh)) { - number += ch; - } else if (this.isExpOperator(ch) && - peekCh && this.isNumber(peekCh) && - number.charAt(number.length - 1) == 'e') { - number += ch; - } else if (this.isExpOperator(ch) && - (!peekCh || !this.isNumber(peekCh)) && - number.charAt(number.length - 1) == 'e') { - this.throwError('Invalid exponent'); - } else { - break; - } - } - this.index++; - } - number = 1 * number; - this.tokens.push({ - index: start, - text: number, - constant: true, - fn: function() { return number; } - }); - }, +///////////////////////////////////////// - readIdent: function() { - var expression = this.text; - var ident = ''; - var start = this.index; + /** + * @constructor + */ + var Lexer = function (options) { + this.options = options; + }; - var lastDot, peekIndex, methodName, ch; + Lexer.prototype = { + constructor: Lexer, + + lex: function (text) { + this.text = text; + this.index = 0; + this.ch = undefined; + this.tokens = []; + + while (this.index < this.text.length) { + this.ch = this.text.charAt(this.index); + if (this.is('"\'')) { + this.readString(this.ch); + } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { + this.readNumber(); + } else if (this.isIdent(this.ch)) { + this.readIdent(); + } else if (this.is('(){}[].,;:?')) { + this.tokens.push({ + index: this.index, + text: this.ch + }); + this.index++; + } else if (this.isWhitespace(this.ch)) { + this.index++; + } else { + var ch2 = this.ch + this.peek(); + var ch3 = ch2 + this.peek(2); + var fn = OPERATORS[this.ch]; + var fn2 = OPERATORS[ch2]; + var fn3 = OPERATORS[ch3]; + if (fn3) { + this.tokens.push({index: this.index, text: ch3, fn: fn3}); + this.index += 3; + } else if (fn2) { + this.tokens.push({index: this.index, text: ch2, fn: fn2}); + this.index += 2; + } else if (fn) { + this.tokens.push({ + index: this.index, + text: this.ch, + fn: fn + }); + this.index += 1; + } else { + this.throwError('Unexpected next character ', this.index, this.index + 1); + } + } + } + return this.tokens; + }, - while (this.index < this.text.length) { - ch = this.text.charAt(this.index); - if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { - if (ch === '.') lastDot = this.index; - ident += ch; - } else { - break; - } - this.index++; - } + is: function (chars) { + return chars.indexOf(this.ch) !== -1; + }, - //check if the identifier ends with . and if so move back one char - if (lastDot && ident[ident.length - 1] === '.') { - this.index--; - ident = ident.slice(0, -1); - lastDot = ident.lastIndexOf('.'); - if (lastDot === -1) { - lastDot = undefined; - } - } + peek: function (i) { + var num = i || 1; + return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; + }, - //check if this is not a method invocation and if it is back out to last dot - if (lastDot) { - peekIndex = this.index; - while (peekIndex < this.text.length) { - ch = this.text.charAt(peekIndex); - if (ch === '(') { - methodName = ident.substr(lastDot - start + 1); - ident = ident.substr(0, lastDot - start); - this.index = peekIndex; - break; - } - if (this.isWhitespace(ch)) { - peekIndex++; - } else { - break; - } - } - } + isNumber: function (ch) { + return ('0' <= ch && ch <= '9'); + }, - this.tokens.push({ - index: start, - text: ident, - fn: CONSTANTS[ident] || getterFn(ident, this.options, expression) - }); + isWhitespace: function (ch) { + // IE treats non-breaking space as \u00A0 + return (ch === ' ' || ch === '\r' || ch === '\t' || + ch === '\n' || ch === '\v' || ch === '\u00A0'); + }, - if (methodName) { - this.tokens.push({ - index: lastDot, - text: '.' - }); - this.tokens.push({ - index: lastDot + 1, - text: methodName - }); - } - }, - - readString: function(quote) { - var start = this.index; - this.index++; - var string = ''; - var rawString = quote; - var escape = false; - while (this.index < this.text.length) { - var ch = this.text.charAt(this.index); - rawString += ch; - if (escape) { - if (ch === 'u') { - var hex = this.text.substring(this.index + 1, this.index + 5); - if (!hex.match(/[\da-f]{4}/i)) - this.throwError('Invalid unicode escape [\\u' + hex + ']'); - this.index += 4; - string += String.fromCharCode(parseInt(hex, 16)); - } else { - var rep = ESCAPE[ch]; - string = string + (rep || ch); - } - escape = false; - } else if (ch === '\\') { - escape = true; - } else if (ch === quote) { - this.index++; - this.tokens.push({ - index: start, - text: rawString, - string: string, - constant: true, - fn: function() { return string; } - }); - return; - } else { - string += ch; - } - this.index++; - } - this.throwError('Unterminated quote', start); - } -}; + isIdent: function (ch) { + return ('a' <= ch && ch <= 'z' || + 'A' <= ch && ch <= 'Z' || + '_' === ch || ch === '$'); + }, + isExpOperator: function (ch) { + return (ch === '-' || ch === '+' || this.isNumber(ch)); + }, -function isConstant(exp) { - return exp.constant; -} + throwError: function (error, start, end) { + end = end || this.index; + var colStr = (isDefined(start) + ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' + : ' ' + end); + throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', + error, colStr, this.text); + }, -/** - * @constructor - */ -var Parser = function (lexer, $filter, options) { - this.lexer = lexer; - this.$filter = $filter; - this.options = options; -}; - -Parser.ZERO = extend(function () { - return 0; -}, { - sharedGetter: true, - constant: true -}); - -Parser.prototype = { - constructor: Parser, - - parse: function (text) { - this.text = text; - this.tokens = this.lexer.lex(text); - - var value = this.statements(); - - if (this.tokens.length !== 0) { - this.throwError('is an unexpected token', this.tokens[0]); - } + readNumber: function () { + var number = ''; + var start = this.index; + while (this.index < this.text.length) { + var ch = lowercase(this.text.charAt(this.index)); + if (ch == '.' || this.isNumber(ch)) { + number += ch; + } else { + var peekCh = this.peek(); + if (ch == 'e' && this.isExpOperator(peekCh)) { + number += ch; + } else if (this.isExpOperator(ch) && + peekCh && this.isNumber(peekCh) && + number.charAt(number.length - 1) == 'e') { + number += ch; + } else if (this.isExpOperator(ch) && + (!peekCh || !this.isNumber(peekCh)) && + number.charAt(number.length - 1) == 'e') { + this.throwError('Invalid exponent'); + } else { + break; + } + } + this.index++; + } + number = 1 * number; + this.tokens.push({ + index: start, + text: number, + constant: true, + fn: function () { + return number; + } + }); + }, - value.literal = !!value.literal; - value.constant = !!value.constant; - - return value; - }, - - primary: function () { - var primary; - if (this.expect('(')) { - primary = this.filterChain(); - this.consume(')'); - } else if (this.expect('[')) { - primary = this.arrayDeclaration(); - } else if (this.expect('{')) { - primary = this.object(); - } else { - var token = this.expect(); - primary = token.fn; - if (!primary) { - this.throwError('not a primary expression', token); - } - if (token.constant) { - primary.constant = true; - primary.literal = true; - } - } + readIdent: function () { + var expression = this.text; - var next, context; - while ((next = this.expect('(', '[', '.'))) { - if (next.text === '(') { - primary = this.functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = this.objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = this.fieldAccess(primary); - } else { - this.throwError('IMPOSSIBLE'); - } - } - return primary; - }, - - throwError: function(msg, token) { - throw $parseMinErr('syntax', - 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', - token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); - }, - - peekToken: function() { - if (this.tokens.length === 0) - throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); - return this.tokens[0]; - }, - - peek: function(e1, e2, e3, e4) { - if (this.tokens.length > 0) { - var token = this.tokens[0]; - var t = token.text; - if (t === e1 || t === e2 || t === e3 || t === e4 || - (!e1 && !e2 && !e3 && !e4)) { - return token; - } - } - return false; - }, - - expect: function(e1, e2, e3, e4){ - var token = this.peek(e1, e2, e3, e4); - if (token) { - this.tokens.shift(); - return token; - } - return false; - }, + var ident = ''; + var start = this.index; - consume: function(e1){ - if (!this.expect(e1)) { - this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); - } - }, + var lastDot, peekIndex, methodName, ch; - unaryFn: function(fn, right) { - return extend(function $parseUnaryFn(self, locals) { - return fn(self, locals, right); - }, { - constant:right.constant, - inputs: [right] - }); - }, + while (this.index < this.text.length) { + ch = this.text.charAt(this.index); + if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { + if (ch === '.') lastDot = this.index; + ident += ch; + } else { + break; + } + this.index++; + } - binaryFn: function(left, fn, right, isBranching) { - return extend(function $parseBinaryFn(self, locals) { - return fn(self, locals, left, right); - }, { - constant: left.constant && right.constant, - inputs: !isBranching && [left, right] - }); - }, - - statements: function() { - var statements = []; - while (true) { - if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) - statements.push(this.filterChain()); - if (!this.expect(';')) { - // optimize for the common case where there is only one statement. - // TODO(size): maybe we should not support multiple statements? - return (statements.length === 1) - ? statements[0] - : function $parseStatements(self, locals) { - var value; - for (var i = 0, ii = statements.length; i < ii; i++) { - value = statements[i](self, locals); + //check if the identifier ends with . and if so move back one char + if (lastDot && ident[ident.length - 1] === '.') { + this.index--; + ident = ident.slice(0, -1); + lastDot = ident.lastIndexOf('.'); + if (lastDot === -1) { + lastDot = undefined; } - return value; - }; - } - } - }, + } - filterChain: function() { - var left = this.expression(); - var token; - while ((token = this.expect('|'))) { - left = this.filter(left); - } - return left; - }, - - filter: function(inputFn) { - var token = this.expect(); - var fn = this.$filter(token.text); - var argsFn; - var args; - - if (this.peek(':')) { - argsFn = []; - args = []; // we can safely reuse the array - while (this.expect(':')) { - argsFn.push(this.expression()); - } - } + //check if this is not a method invocation and if it is back out to last dot + if (lastDot) { + peekIndex = this.index; + while (peekIndex < this.text.length) { + ch = this.text.charAt(peekIndex); + if (ch === '(') { + methodName = ident.substr(lastDot - start + 1); + ident = ident.substr(0, lastDot - start); + this.index = peekIndex; + break; + } + if (this.isWhitespace(ch)) { + peekIndex++; + } else { + break; + } + } + } - var inputs = [inputFn].concat(argsFn || []); + this.tokens.push({ + index: start, + text: ident, + fn: CONSTANTS[ident] || getterFn(ident, this.options, expression) + }); - return extend(function $parseFilter(self, locals) { - var input = inputFn(self, locals); - if (args) { - args[0] = input; + if (methodName) { + this.tokens.push({ + index: lastDot, + text: '.' + }); + this.tokens.push({ + index: lastDot + 1, + text: methodName + }); + } + }, - var i = argsFn.length; - while (i--) { - args[i + 1] = argsFn[i](self, locals); + readString: function (quote) { + var start = this.index; + this.index++; + var string = ''; + var rawString = quote; + var escape = false; + while (this.index < this.text.length) { + var ch = this.text.charAt(this.index); + rawString += ch; + if (escape) { + if (ch === 'u') { + var hex = this.text.substring(this.index + 1, this.index + 5); + if (!hex.match(/[\da-f]{4}/i)) + this.throwError('Invalid unicode escape [\\u' + hex + ']'); + this.index += 4; + string += String.fromCharCode(parseInt(hex, 16)); + } else { + var rep = ESCAPE[ch]; + string = string + (rep || ch); + } + escape = false; + } else if (ch === '\\') { + escape = true; + } else if (ch === quote) { + this.index++; + this.tokens.push({ + index: start, + text: rawString, + string: string, + constant: true, + fn: function () { + return string; + } + }); + return; + } else { + string += ch; + } + this.index++; + } + this.throwError('Unterminated quote', start); } + }; - return fn.apply(undefined, args); - } - - return fn(input); - }, { - constant: !fn.$stateful && inputs.every(isConstant), - inputs: !fn.$stateful && inputs - }); - }, - - expression: function() { - return this.assignment(); - }, - - assignment: function() { - var left = this.ternary(); - var right; - var token; - if ((token = this.expect('='))) { - if (!left.assign) { - this.throwError('implies assignment but [' + - this.text.substring(0, token.index) + '] can not be assigned to', token); - } - right = this.ternary(); - return extend(function $parseAssignment(scope, locals) { - return left.assign(scope, right(scope, locals), locals); - }, { - inputs: [left, right] - }); - } - return left; - }, - - ternary: function() { - var left = this.logicalOR(); - var middle; - var token; - if ((token = this.expect('?'))) { - middle = this.assignment(); - if ((token = this.expect(':'))) { - var right = this.assignment(); - - return extend(function $parseTernary(self, locals){ - return left(self, locals) ? middle(self, locals) : right(self, locals); - }, { - constant: left.constant && middle.constant && right.constant - }); - - } else { - this.throwError('expected :', token); - } - } - - return left; - }, - logicalOR: function() { - var left = this.logicalAND(); - var token; - while ((token = this.expect('||'))) { - left = this.binaryFn(left, token.fn, this.logicalAND(), true); - } - return left; - }, - - logicalAND: function() { - var left = this.equality(); - var token; - if ((token = this.expect('&&'))) { - left = this.binaryFn(left, token.fn, this.logicalAND(), true); - } - return left; - }, - - equality: function() { - var left = this.relational(); - var token; - if ((token = this.expect('==','!=','===','!=='))) { - left = this.binaryFn(left, token.fn, this.equality()); - } - return left; - }, - - relational: function() { - var left = this.additive(); - var token; - if ((token = this.expect('<', '>', '<=', '>='))) { - left = this.binaryFn(left, token.fn, this.relational()); - } - return left; - }, - - additive: function() { - var left = this.multiplicative(); - var token; - while ((token = this.expect('+','-'))) { - left = this.binaryFn(left, token.fn, this.multiplicative()); - } - return left; - }, - - multiplicative: function() { - var left = this.unary(); - var token; - while ((token = this.expect('*','/','%'))) { - left = this.binaryFn(left, token.fn, this.unary()); - } - return left; - }, - - unary: function() { - var token; - if (this.expect('+')) { - return this.primary(); - } else if ((token = this.expect('-'))) { - return this.binaryFn(Parser.ZERO, token.fn, this.unary()); - } else if ((token = this.expect('!'))) { - return this.unaryFn(token.fn, this.unary()); - } else { - return this.primary(); + function isConstant(exp) { + return exp.constant; } - }, - fieldAccess: function(object) { - var expression = this.text; - var field = this.expect().text; - var getter = getterFn(field, this.options, expression); + /** + * @constructor + */ + var Parser = function (lexer, $filter, options) { + this.lexer = lexer; + this.$filter = $filter; + this.options = options; + }; - return extend(function $parseFieldAccess(scope, locals, self) { - return getter(self || object(scope, locals)); + Parser.ZERO = extend(function () { + return 0; }, { - assign: function(scope, value, locals) { - var o = object(scope, locals); - if (!o) object.assign(scope, o = {}); - return setter(o, field, value, expression); - } + sharedGetter: true, + constant: true }); - }, - objectIndex: function(obj) { - var expression = this.text; + Parser.prototype = { + constructor: Parser, - var indexFn = this.expression(); - this.consume(']'); + parse: function (text) { + this.text = text; + this.tokens = this.lexer.lex(text); - return extend(function $parseObjectIndex(self, locals) { - var o = obj(self, locals), - i = indexFn(self, locals), - v; - - ensureSafeMemberName(i, expression); - if (!o) return undefined; - v = ensureSafeObject(o[i], expression); - return v; - }, { - assign: function(self, value, locals) { - var key = ensureSafeMemberName(indexFn(self, locals), expression); - // prevent overwriting of Function.constructor which would break ensureSafeObject check - var o = ensureSafeObject(obj(self, locals), expression); - if (!o) obj.assign(self, o = {}); - return o[key] = value; - } - }); - }, - - functionCall: function(fnGetter, contextGetter) { - var argsFn = []; - if (this.peekToken().text !== ')') { - do { - argsFn.push(this.expression()); - } while (this.expect(',')); - } - this.consume(')'); + var value = this.statements(); - var expressionText = this.text; - // we can safely reuse the array across invocations - var args = argsFn.length ? [] : null; + if (this.tokens.length !== 0) { + this.throwError('is an unexpected token', this.tokens[0]); + } - return function $parseFunctionCall(scope, locals) { - var context = contextGetter ? contextGetter(scope, locals) : scope; - var fn = fnGetter(scope, locals, context) || noop; + value.literal = !!value.literal; + value.constant = !!value.constant; - if (args) { - var i = argsFn.length; - while (i--) { - args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText); - } - } + return value; + }, - ensureSafeObject(context, expressionText); - ensureSafeFunction(fn, expressionText); + primary: function () { + var primary; + if (this.expect('(')) { + primary = this.filterChain(); + this.consume(')'); + } else if (this.expect('[')) { + primary = this.arrayDeclaration(); + } else if (this.expect('{')) { + primary = this.object(); + } else { + var token = this.expect(); + primary = token.fn; + if (!primary) { + this.throwError('not a primary expression', token); + } + if (token.constant) { + primary.constant = true; + primary.literal = true; + } + } - // IE stupidity! (IE doesn't have apply for some native functions) - var v = fn.apply - ? fn.apply(context, args) - : fn(args[0], args[1], args[2], args[3], args[4]); + var next, context; + while ((next = this.expect('(', '[', '.'))) { + if (next.text === '(') { + primary = this.functionCall(primary, context); + context = null; + } else if (next.text === '[') { + context = primary; + primary = this.objectIndex(primary); + } else if (next.text === '.') { + context = primary; + primary = this.fieldAccess(primary); + } else { + this.throwError('IMPOSSIBLE'); + } + } + return primary; + }, - return ensureSafeObject(v, expressionText); - }; - }, - - // This is used with json array declaration - arrayDeclaration: function () { - var elementFns = []; - if (this.peekToken().text !== ']') { - do { - if (this.peek(']')) { - // Support trailing commas per ES5.1. - break; - } - var elementFn = this.expression(); - elementFns.push(elementFn); - } while (this.expect(',')); - } - this.consume(']'); + throwError: function (msg, token) { + throw $parseMinErr('syntax', + 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', + token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); + }, - return extend(function $parseArrayLiteral(self, locals) { - var array = []; - for (var i = 0, ii = elementFns.length; i < ii; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }, { - literal: true, - constant: elementFns.every(isConstant), - inputs: elementFns - }); - }, - - object: function () { - var keys = [], valueFns = []; - if (this.peekToken().text !== '}') { - do { - if (this.peek('}')) { - // Support trailing commas per ES5.1. - break; - } - var token = this.expect(); - keys.push(token.string || token.text); - this.consume(':'); - var value = this.expression(); - valueFns.push(value); - } while (this.expect(',')); - } - this.consume('}'); + peekToken: function () { + if (this.tokens.length === 0) + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); + return this.tokens[0]; + }, - return extend(function $parseObjectLiteral(self, locals) { - var object = {}; - for (var i = 0, ii = valueFns.length; i < ii; i++) { - object[keys[i]] = valueFns[i](self, locals); - } - return object; - }, { - literal: true, - constant: valueFns.every(isConstant), - inputs: valueFns - }); - } -}; + peek: function (e1, e2, e3, e4) { + if (this.tokens.length > 0) { + var token = this.tokens[0]; + var t = token.text; + if (t === e1 || t === e2 || t === e3 || t === e4 || + (!e1 && !e2 && !e3 && !e4)) { + return token; + } + } + return false; + }, + expect: function (e1, e2, e3, e4) { + var token = this.peek(e1, e2, e3, e4); + if (token) { + this.tokens.shift(); + return token; + } + return false; + }, -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// + consume: function (e1) { + if (!this.expect(e1)) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + } + }, -function setter(obj, path, setValue, fullExp) { - ensureSafeObject(obj, fullExp); + unaryFn: function (fn, right) { + return extend(function $parseUnaryFn(self, locals) { + return fn(self, locals, right); + }, { + constant: right.constant, + inputs: [right] + }); + }, - var element = path.split('.'), key; - for (var i = 0; element.length > 1; i++) { - key = ensureSafeMemberName(element.shift(), fullExp); - var propertyObj = ensureSafeObject(obj[key], fullExp); - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; - } - obj = propertyObj; - } - key = ensureSafeMemberName(element.shift(), fullExp); - ensureSafeObject(obj[key], fullExp); - obj[key] = setValue; - return setValue; -} + binaryFn: function (left, fn, right, isBranching) { + return extend(function $parseBinaryFn(self, locals) { + return fn(self, locals, left, right); + }, { + constant: left.constant && right.constant, + inputs: !isBranching && [left, right] + }); + }, -var getterFnCache = createMap(); + statements: function () { + var statements = []; + while (true) { + if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) + statements.push(this.filterChain()); + if (!this.expect(';')) { + // optimize for the common case where there is only one statement. + // TODO(size): maybe we should not support multiple statements? + return (statements.length === 1) + ? statements[0] + : function $parseStatements(self, locals) { + var value; + for (var i = 0, ii = statements.length; i < ii; i++) { + value = statements[i](self, locals); + } + return value; + }; + } + } + }, -/** - * Implementation of the "Black Hole" variant from: - * - http://jsperf.com/angularjs-parse-getter/4 - * - http://jsperf.com/path-evaluation-simplified/7 - */ -function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); - ensureSafeMemberName(key2, fullExp); - ensureSafeMemberName(key3, fullExp); - ensureSafeMemberName(key4, fullExp); - - return function cspSafeGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; - - if (pathVal == null) return pathVal; - pathVal = pathVal[key0]; - - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key1]; - - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key2]; - - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key3]; - - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key4]; - - return pathVal; - }; -} - -function getterFn(path, options, fullExp) { - var fn = getterFnCache[path]; - - if (fn) return fn; - - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length; - - // http://jsperf.com/angularjs-parse-getter/6 - if (options.csp) { - if (pathKeysLength < 6) { - fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp); - } else { - fn = function cspSafeGetter(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], - pathKeys[i++], fullExp)(scope, locals); + filterChain: function () { + var left = this.expression(); + var token; + while ((token = this.expect('|'))) { + left = this.filter(left); + } + return left; + }, - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - }; - } - } else { - var code = ''; - forEach(pathKeys, function(key, index) { - ensureSafeMemberName(key, fullExp); - code += 'if(s == null) return undefined;\n' + - 's='+ (index - // we simply dereference 's' on any .dot notation - ? 's' - // but if we are first then we check locals first, and if so read it first - : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key + ';\n'; - }); - code += 'return s;'; + filter: function (inputFn) { + var token = this.expect(); + var fn = this.$filter(token.text); + var argsFn; + var args; + + if (this.peek(':')) { + argsFn = []; + args = []; // we can safely reuse the array + while (this.expect(':')) { + argsFn.push(this.expression()); + } + } - /* jshint -W054 */ - var evaledFnGetter = new Function('s', 'l', code); // s=scope, l=locals - /* jshint +W054 */ - evaledFnGetter.toString = valueFn(code); + var inputs = [inputFn].concat(argsFn || []); - fn = evaledFnGetter; - } + return extend(function $parseFilter(self, locals) { + var input = inputFn(self, locals); + if (args) { + args[0] = input; - fn.sharedGetter = true; - fn.assign = function(self, value) { - return setter(self, path, value, path); - }; - getterFnCache[path] = fn; - return fn; -} + var i = argsFn.length; + while (i--) { + args[i + 1] = argsFn[i](self, locals); + } -/////////////////////////////////// + return fn.apply(undefined, args); + } -/** - * @ngdoc service - * @name $parse - * @kind function - * - * @description - * - * Converts Angular {@link guide/expression expression} into a function. - * - * ```js - * var getter = $parse('user.name'); - * var setter = getter.assign; - * var context = {user:{name:'angular'}}; - * var locals = {user:{name:'local'}}; - * - * expect(getter(context)).toEqual('angular'); - * setter(context, 'newValue'); - * expect(context.user.name).toEqual('newValue'); - * expect(getter(context, locals)).toEqual('local'); - * ``` - * - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - * - * The returned function also has the following properties: - * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript - * literal. - * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript - * constant literals. - * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be - * set to a function to change its value on the given context. - * - */ + return fn(input); + }, { + constant: !fn.$stateful && inputs.every(isConstant), + inputs: !fn.$stateful && inputs + }); + }, + expression: function () { + return this.assignment(); + }, -/** - * @ngdoc provider - * @name $parseProvider - * - * @description - * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} - * service. - */ -function $ParseProvider() { - var cache = createMap(); + assignment: function () { + var left = this.ternary(); + var right; + var token; + if ((token = this.expect('='))) { + if (!left.assign) { + this.throwError('implies assignment but [' + + this.text.substring(0, token.index) + '] can not be assigned to', token); + } + right = this.ternary(); + return extend(function $parseAssignment(scope, locals) { + return left.assign(scope, right(scope, locals), locals); + }, { + inputs: [left, right] + }); + } + return left; + }, - var $parseOptions = { - csp: false - }; + ternary: function () { + var left = this.logicalOR(); + var middle; + var token; + if ((token = this.expect('?'))) { + middle = this.assignment(); + if ((token = this.expect(':'))) { + var right = this.assignment(); + + return extend(function $parseTernary(self, locals) { + return left(self, locals) ? middle(self, locals) : right(self, locals); + }, { + constant: left.constant && middle.constant && right.constant + }); + } else { + this.throwError('expected :', token); + } + } - this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { - $parseOptions.csp = $sniffer.csp; + return left; + }, - function wrapSharedExpression(exp) { - var wrapped = exp; + logicalOR: function () { + var left = this.logicalAND(); + var token; + while ((token = this.expect('||'))) { + left = this.binaryFn(left, token.fn, this.logicalAND(), true); + } + return left; + }, - if (exp.sharedGetter) { - wrapped = function $parseWrapper(self, locals) { - return exp(self, locals); - }; - wrapped.literal = exp.literal; - wrapped.constant = exp.constant; - wrapped.assign = exp.assign; - } + logicalAND: function () { + var left = this.equality(); + var token; + if ((token = this.expect('&&'))) { + left = this.binaryFn(left, token.fn, this.logicalAND(), true); + } + return left; + }, - return wrapped; - } + equality: function () { + var left = this.relational(); + var token; + if ((token = this.expect('==', '!=', '===', '!=='))) { + left = this.binaryFn(left, token.fn, this.equality()); + } + return left; + }, - return function $parse(exp, interceptorFn) { - var parsedExpression, oneTime, cacheKey; + relational: function () { + var left = this.additive(); + var token; + if ((token = this.expect('<', '>', '<=', '>='))) { + left = this.binaryFn(left, token.fn, this.relational()); + } + return left; + }, - switch (typeof exp) { - case 'string': - cacheKey = exp = exp.trim(); + additive: function () { + var left = this.multiplicative(); + var token; + while ((token = this.expect('+', '-'))) { + left = this.binaryFn(left, token.fn, this.multiplicative()); + } + return left; + }, - parsedExpression = cache[cacheKey]; + multiplicative: function () { + var left = this.unary(); + var token; + while ((token = this.expect('*', '/', '%'))) { + left = this.binaryFn(left, token.fn, this.unary()); + } + return left; + }, - if (!parsedExpression) { - if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { - oneTime = true; - exp = exp.substring(2); + unary: function () { + var token; + if (this.expect('+')) { + return this.primary(); + } else if ((token = this.expect('-'))) { + return this.binaryFn(Parser.ZERO, token.fn, this.unary()); + } else if ((token = this.expect('!'))) { + return this.unaryFn(token.fn, this.unary()); + } else { + return this.primary(); } + }, + + fieldAccess: function (object) { + var expression = this.text; + var field = this.expect().text; + var getter = getterFn(field, this.options, expression); + + return extend(function $parseFieldAccess(scope, locals, self) { + return getter(self || object(scope, locals)); + }, { + assign: function (scope, value, locals) { + var o = object(scope, locals); + if (!o) object.assign(scope, o = {}); + return setter(o, field, value, expression); + } + }); + }, - var lexer = new Lexer($parseOptions); - var parser = new Parser(lexer, $filter, $parseOptions); - parsedExpression = parser.parse(exp); + objectIndex: function (obj) { + var expression = this.text; + + var indexFn = this.expression(); + this.consume(']'); + + return extend(function $parseObjectIndex(self, locals) { + var o = obj(self, locals), + i = indexFn(self, locals), + v; + + ensureSafeMemberName(i, expression); + if (!o) return undefined; + v = ensureSafeObject(o[i], expression); + return v; + }, { + assign: function (self, value, locals) { + var key = ensureSafeMemberName(indexFn(self, locals), expression); + // prevent overwriting of Function.constructor which would break ensureSafeObject check + var o = ensureSafeObject(obj(self, locals), expression); + if (!o) obj.assign(self, o = {}); + return o[key] = value; + } + }); + }, - if (parsedExpression.constant) { - parsedExpression.$$watchDelegate = constantWatchDelegate; - } else if (oneTime) { - //oneTime is not part of the exp passed to the Parser so we may have to - //wrap the parsedExpression before adding a $$watchDelegate - parsedExpression = wrapSharedExpression(parsedExpression); - parsedExpression.$$watchDelegate = parsedExpression.literal ? - oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; - } else if (parsedExpression.inputs) { - parsedExpression.$$watchDelegate = inputsWatchDelegate; + functionCall: function (fnGetter, contextGetter) { + var argsFn = []; + if (this.peekToken().text !== ')') { + do { + argsFn.push(this.expression()); + } while (this.expect(',')); } + this.consume(')'); - cache[cacheKey] = parsedExpression; - } - return addInterceptor(parsedExpression, interceptorFn); + var expressionText = this.text; + // we can safely reuse the array across invocations + var args = argsFn.length ? [] : null; - case 'function': - return addInterceptor(exp, interceptorFn); + return function $parseFunctionCall(scope, locals) { + var context = contextGetter ? contextGetter(scope, locals) : scope; + var fn = fnGetter(scope, locals, context) || noop; - default: - return addInterceptor(noop, interceptorFn); - } - }; + if (args) { + var i = argsFn.length; + while (i--) { + args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText); + } + } - function collectExpressionInputs(inputs, list) { - for (var i = 0, ii = inputs.length; i < ii; i++) { - var input = inputs[i]; - if (!input.constant) { - if (input.inputs) { - collectExpressionInputs(input.inputs, list); - } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better? - list.push(input); - } - } - } + ensureSafeObject(context, expressionText); + ensureSafeFunction(fn, expressionText); - return list; - } + // IE stupidity! (IE doesn't have apply for some native functions) + var v = fn.apply + ? fn.apply(context, args) + : fn(args[0], args[1], args[2], args[3], args[4]); - function expressionInputDirtyCheck(newValue, oldValueOfValue) { + return ensureSafeObject(v, expressionText); + }; + }, - if (newValue == null || oldValueOfValue == null) { // null/undefined - return newValue === oldValueOfValue; - } + // This is used with json array declaration + arrayDeclaration: function () { + var elementFns = []; + if (this.peekToken().text !== ']') { + do { + if (this.peek(']')) { + // Support trailing commas per ES5.1. + break; + } + var elementFn = this.expression(); + elementFns.push(elementFn); + } while (this.expect(',')); + } + this.consume(']'); - if (typeof newValue === 'object') { + return extend(function $parseArrayLiteral(self, locals) { + var array = []; + for (var i = 0, ii = elementFns.length; i < ii; i++) { + array.push(elementFns[i](self, locals)); + } + return array; + }, { + literal: true, + constant: elementFns.every(isConstant), + inputs: elementFns + }); + }, - // attempt to convert the value to a primitive type - // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can - // be cheaply dirty-checked - newValue = newValue.valueOf(); + object: function () { + var keys = [], valueFns = []; + if (this.peekToken().text !== '}') { + do { + if (this.peek('}')) { + // Support trailing commas per ES5.1. + break; + } + var token = this.expect(); + keys.push(token.string || token.text); + this.consume(':'); + var value = this.expression(); + valueFns.push(value); + } while (this.expect(',')); + } + this.consume('}'); - if (typeof newValue === 'object') { - // objects/arrays are not supported - deep-watching them would be too expensive - return false; + return extend(function $parseObjectLiteral(self, locals) { + var object = {}; + for (var i = 0, ii = valueFns.length; i < ii; i++) { + object[keys[i]] = valueFns[i](self, locals); + } + return object; + }, { + literal: true, + constant: valueFns.every(isConstant), + inputs: valueFns + }); } + }; - // fall-through to the primitive equality check - } - //Primitive or NaN - return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); +////////////////////////////////////////////////// +// Parser helper functions +////////////////////////////////////////////////// + + function setter(obj, path, setValue, fullExp) { + ensureSafeObject(obj, fullExp); + + var element = path.split('.'), key; + for (var i = 0; element.length > 1; i++) { + key = ensureSafeMemberName(element.shift(), fullExp); + var propertyObj = ensureSafeObject(obj[key], fullExp); + if (!propertyObj) { + propertyObj = {}; + obj[key] = propertyObj; + } + obj = propertyObj; + } + key = ensureSafeMemberName(element.shift(), fullExp); + ensureSafeObject(obj[key], fullExp); + obj[key] = setValue; + return setValue; } - function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var inputExpressions = parsedExpression.$$inputs || - (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, [])); + var getterFnCache = createMap(); - var lastResult; + /** + * Implementation of the "Black Hole" variant from: + * - http://jsperf.com/angularjs-parse-getter/4 + * - http://jsperf.com/path-evaluation-simplified/7 + */ + function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) { + ensureSafeMemberName(key0, fullExp); + ensureSafeMemberName(key1, fullExp); + ensureSafeMemberName(key2, fullExp); + ensureSafeMemberName(key3, fullExp); + ensureSafeMemberName(key4, fullExp); - if (inputExpressions.length === 1) { - var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails - inputExpressions = inputExpressions[0]; - return scope.$watch(function expressionInputWatch(scope) { - var newInputValue = inputExpressions(scope); - if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) { - lastResult = parsedExpression(scope); - oldInputValue = newInputValue && newInputValue.valueOf(); - } - return lastResult; - }, listener, objectEquality); - } + return function cspSafeGetter(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; - var oldInputValueOfValues = []; - for (var i = 0, ii = inputExpressions.length; i < ii; i++) { - oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails - } + if (pathVal == null) return pathVal; + pathVal = pathVal[key0]; - return scope.$watch(function expressionInputsWatch(scope) { - var changed = false; + if (!key1) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key1]; - for (var i = 0, ii = inputExpressions.length; i < ii; i++) { - var newInputValue = inputExpressions[i](scope); - if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) { - oldInputValueOfValues[i] = newInputValue && newInputValue.valueOf(); - } - } + if (!key2) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key2]; - if (changed) { - lastResult = parsedExpression(scope); - } + if (!key3) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key3]; + + if (!key4) return pathVal; + if (pathVal == null) return undefined; + pathVal = pathVal[key4]; - return lastResult; - }, listener, objectEquality); + return pathVal; + }; } - function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch, lastValue; - return unwatch = scope.$watch(function oneTimeWatch(scope) { - return parsedExpression(scope); - }, function oneTimeListener(value, old, scope) { - lastValue = value; - if (isFunction(listener)) { - listener.apply(this, arguments); - } - if (isDefined(value)) { - scope.$$postDigest(function () { - if (isDefined(lastValue)) { - unwatch(); + function getterFn(path, options, fullExp) { + var fn = getterFnCache[path]; + + if (fn) return fn; + + var pathKeys = path.split('.'), + pathKeysLength = pathKeys.length; + + // http://jsperf.com/angularjs-parse-getter/6 + if (options.csp) { + if (pathKeysLength < 6) { + fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp); + } else { + fn = function cspSafeGetter(scope, locals) { + var i = 0, val; + do { + val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], + pathKeys[i++], fullExp)(scope, locals); + + locals = undefined; // clear after first iteration + scope = val; + } while (i < pathKeysLength); + return val; + }; } - }); - } - }, objectEquality); - } + } else { + var code = ''; + forEach(pathKeys, function (key, index) { + ensureSafeMemberName(key, fullExp); + code += 'if(s == null) return undefined;\n' + + 's=' + (index + // we simply dereference 's' on any .dot notation + ? 's' + // but if we are first then we check locals first, and if so read it first + : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key + ';\n'; + }); + code += 'return s;'; - function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch, lastValue; - return unwatch = scope.$watch(function oneTimeWatch(scope) { - return parsedExpression(scope); - }, function oneTimeListener(value, old, scope) { - lastValue = value; - if (isFunction(listener)) { - listener.call(this, value, old, scope); - } - if (isAllDefined(value)) { - scope.$$postDigest(function () { - if(isAllDefined(lastValue)) unwatch(); - }); + /* jshint -W054 */ + var evaledFnGetter = new Function('s', 'l', code); // s=scope, l=locals + /* jshint +W054 */ + evaledFnGetter.toString = valueFn(code); + + fn = evaledFnGetter; } - }, objectEquality); - function isAllDefined(value) { - var allDefined = true; - forEach(value, function (val) { - if (!isDefined(val)) allDefined = false; - }); - return allDefined; - } + fn.sharedGetter = true; + fn.assign = function (self, value) { + return setter(self, path, value, path); + }; + getterFnCache[path] = fn; + return fn; } - function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch; - return unwatch = scope.$watch(function constantWatch(scope) { - return parsedExpression(scope); - }, function constantListener(value, old, scope) { - if (isFunction(listener)) { - listener.apply(this, arguments); - } - unwatch(); - }, objectEquality); - } +/////////////////////////////////// + + /** + * @ngdoc service + * @name $parse + * @kind function + * + * @description + * + * Converts Angular {@link guide/expression expression} into a function. + * + * ```js + * var getter = $parse('user.name'); + * var setter = getter.assign; + * var context = {user:{name:'angular'}}; + * var locals = {user:{name:'local'}}; + * + * expect(getter(context)).toEqual('angular'); + * setter(context, 'newValue'); + * expect(context.user.name).toEqual('newValue'); + * expect(getter(context, locals)).toEqual('local'); + * ``` + * + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + * + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. + * + */ - function addInterceptor(parsedExpression, interceptorFn) { - if (!interceptorFn) return parsedExpression; - var fn = function interceptedExpression(scope, locals) { - var value = parsedExpression(scope, locals); - var result = interceptorFn(value, scope, locals); - // we only return the interceptor's result if the - // initial value is defined (for bind-once) - return isDefined(value) ? result : value; - }; + /** + * @ngdoc provider + * @name $parseProvider + * + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. + */ + function $ParseProvider() { + var cache = createMap(); - // Propagate $$watchDelegates other then inputsWatchDelegate - if (parsedExpression.$$watchDelegate && - parsedExpression.$$watchDelegate !== inputsWatchDelegate) { - fn.$$watchDelegate = parsedExpression.$$watchDelegate; - } else if (!interceptorFn.$stateful) { - // If there is an interceptor, but no watchDelegate then treat the interceptor like - // we treat filters - it is assumed to be a pure function unless flagged with $stateful - fn.$$watchDelegate = inputsWatchDelegate; - fn.inputs = [parsedExpression]; - } + var $parseOptions = { + csp: false + }; + + + this.$get = ['$filter', '$sniffer', function ($filter, $sniffer) { + $parseOptions.csp = $sniffer.csp; + + function wrapSharedExpression(exp) { + var wrapped = exp; + + if (exp.sharedGetter) { + wrapped = function $parseWrapper(self, locals) { + return exp(self, locals); + }; + wrapped.literal = exp.literal; + wrapped.constant = exp.constant; + wrapped.assign = exp.assign; + } + + return wrapped; + } + + return function $parse(exp, interceptorFn) { + var parsedExpression, oneTime, cacheKey; + + switch (typeof exp) { + case 'string': + cacheKey = exp = exp.trim(); + + parsedExpression = cache[cacheKey]; + + if (!parsedExpression) { + if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { + oneTime = true; + exp = exp.substring(2); + } + + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + parsedExpression = parser.parse(exp); + + if (parsedExpression.constant) { + parsedExpression.$$watchDelegate = constantWatchDelegate; + } else if (oneTime) { + //oneTime is not part of the exp passed to the Parser so we may have to + //wrap the parsedExpression before adding a $$watchDelegate + parsedExpression = wrapSharedExpression(parsedExpression); + parsedExpression.$$watchDelegate = parsedExpression.literal ? + oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; + } else if (parsedExpression.inputs) { + parsedExpression.$$watchDelegate = inputsWatchDelegate; + } + + cache[cacheKey] = parsedExpression; + } + return addInterceptor(parsedExpression, interceptorFn); + + case 'function': + return addInterceptor(exp, interceptorFn); + + default: + return addInterceptor(noop, interceptorFn); + } + }; + + function collectExpressionInputs(inputs, list) { + for (var i = 0, ii = inputs.length; i < ii; i++) { + var input = inputs[i]; + if (!input.constant) { + if (input.inputs) { + collectExpressionInputs(input.inputs, list); + } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better? + list.push(input); + } + } + } + + return list; + } + + function expressionInputDirtyCheck(newValue, oldValueOfValue) { + + if (newValue == null || oldValueOfValue == null) { // null/undefined + return newValue === oldValueOfValue; + } + + if (typeof newValue === 'object') { + + // attempt to convert the value to a primitive type + // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can + // be cheaply dirty-checked + newValue = newValue.valueOf(); + + if (typeof newValue === 'object') { + // objects/arrays are not supported - deep-watching them would be too expensive + return false; + } + + // fall-through to the primitive equality check + } + + //Primitive or NaN + return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); + } + + function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var inputExpressions = parsedExpression.$$inputs || + (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, [])); + + var lastResult; + + if (inputExpressions.length === 1) { + var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails + inputExpressions = inputExpressions[0]; + return scope.$watch(function expressionInputWatch(scope) { + var newInputValue = inputExpressions(scope); + if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) { + lastResult = parsedExpression(scope); + oldInputValue = newInputValue && newInputValue.valueOf(); + } + return lastResult; + }, listener, objectEquality); + } + + var oldInputValueOfValues = []; + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails + } + + return scope.$watch(function expressionInputsWatch(scope) { + var changed = false; + + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + var newInputValue = inputExpressions[i](scope); + if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) { + oldInputValueOfValues[i] = newInputValue && newInputValue.valueOf(); + } + } + + if (changed) { + lastResult = parsedExpression(scope); + } + + return lastResult; + }, listener, objectEquality); + } - return fn; + function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch, lastValue; + return unwatch = scope.$watch(function oneTimeWatch(scope) { + return parsedExpression(scope); + }, function oneTimeListener(value, old, scope) { + lastValue = value; + if (isFunction(listener)) { + listener.apply(this, arguments); + } + if (isDefined(value)) { + scope.$$postDigest(function () { + if (isDefined(lastValue)) { + unwatch(); + } + }); + } + }, objectEquality); + } + + function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch, lastValue; + return unwatch = scope.$watch(function oneTimeWatch(scope) { + return parsedExpression(scope); + }, function oneTimeListener(value, old, scope) { + lastValue = value; + if (isFunction(listener)) { + listener.call(this, value, old, scope); + } + if (isAllDefined(value)) { + scope.$$postDigest(function () { + if (isAllDefined(lastValue)) unwatch(); + }); + } + }, objectEquality); + + function isAllDefined(value) { + var allDefined = true; + forEach(value, function (val) { + if (!isDefined(val)) allDefined = false; + }); + return allDefined; + } + } + + function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch; + return unwatch = scope.$watch(function constantWatch(scope) { + return parsedExpression(scope); + }, function constantListener(value, old, scope) { + if (isFunction(listener)) { + listener.apply(this, arguments); + } + unwatch(); + }, objectEquality); + } + + function addInterceptor(parsedExpression, interceptorFn) { + if (!interceptorFn) return parsedExpression; + + var fn = function interceptedExpression(scope, locals) { + var value = parsedExpression(scope, locals); + var result = interceptorFn(value, scope, locals); + // we only return the interceptor's result if the + // initial value is defined (for bind-once) + return isDefined(value) ? result : value; + }; + + // Propagate $$watchDelegates other then inputsWatchDelegate + if (parsedExpression.$$watchDelegate && + parsedExpression.$$watchDelegate !== inputsWatchDelegate) { + fn.$$watchDelegate = parsedExpression.$$watchDelegate; + } else if (!interceptorFn.$stateful) { + // If there is an interceptor, but no watchDelegate then treat the interceptor like + // we treat filters - it is assumed to be a pure function unless flagged with $stateful + fn.$$watchDelegate = inputsWatchDelegate; + fn.inputs = [parsedExpression]; + } + + return fn; + } + }]; } - }]; -} -/** - * @ngdoc service - * @name $q - * @requires $rootScope - * - * @description - * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). - * - * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred - * implementations, and the other which resembles ES6 promises to some degree. - * - * # $q constructor - * - * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` - * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony, - * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). - * - * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are - * available yet. - * - * It can be used like so: - * - * ```js - * // for the purpose of this example let's assume that variables `$q` and `okToGreet` - * // are available in the current lexical scope (they could have been injected or passed in). - * - * function asyncGreet(name) { + /** + * @ngdoc service + * @name $q + * @requires $rootScope + * + * @description + * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). + * + * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred + * implementations, and the other which resembles ES6 promises to some degree. + * + * # $q constructor + * + * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` + * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony, + * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are + * available yet. + * + * It can be used like so: + * + * ```js + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). + * + * function asyncGreet(name) { * // perform some asynchronous operation, resolve or reject the promise when appropriate. * return $q(function(resolve, reject) { * setTimeout(function() { @@ -12637,31 +12745,31 @@ function $ParseProvider() { * }, 1000); * }); * } - * - * var promise = asyncGreet('Robin Hood'); - * promise.then(function(greeting) { + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); - * ``` - * - * Note: progress/notify callbacks are not currently supported via the ES6-style interface. - * - * However, the more traditional CommonJS-style usage is still available, and documented below. - * - * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an - * interface for interacting with an object that represents the result of an action that is - * performed asynchronously, and may or may not be finished at any given point in time. - * - * From the perspective of dealing with error handling, deferred and promise APIs are to - * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. - * - * ```js - * // for the purpose of this example let's assume that variables `$q` and `okToGreet` - * // are available in the current lexical scope (they could have been injected or passed in). - * - * function asyncGreet(name) { + * ``` + * + * Note: progress/notify callbacks are not currently supported via the ES6-style interface. + * + * However, the more traditional CommonJS-style usage is still available, and documented below. + * + * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an + * interface for interacting with an object that represents the result of an action that is + * performed asynchronously, and may or may not be finished at any given point in time. + * + * From the perspective of dealing with error handling, deferred and promise APIs are to + * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. + * + * ```js + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). + * + * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { @@ -12676,115 +12784,115 @@ function $ParseProvider() { * * return deferred.promise; * } - * - * var promise = asyncGreet('Robin Hood'); - * promise.then(function(greeting) { + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }, function(update) { * alert('Got notification: ' + update); * }); - * ``` - * - * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of guarantees that promise and deferred APIs make, see - * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. - * - * Additionally the promise api allows for composition that is very hard to do with the - * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. - * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the - * section on serial or parallel joining of promises. - * - * # The Deferred API - * - * A new instance of deferred is constructed by calling `$q.defer()`. - * - * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion, as well as the status - * of the task. - * - * **Methods** - * - * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection - * constructed via `$q.reject`, the promise will be rejected instead. - * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to - * resolving it with a rejection constructed via `$q.reject`. - * - `notify(value)` - provides updates on the status of the promise's execution. This may be called - * multiple times before the promise is either resolved or rejected. - * - * **Properties** - * - * - promise – `{Promise}` – promise object associated with this deferred. - * - * - * # The Promise API - * - * A new promise instance is created when a deferred instance is created and can be retrieved by - * calling `deferred.promise`. - * - * The purpose of the promise object is to allow for interested parties to get access to the result - * of the deferred task when it completes. - * - * **Methods** - * - * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or - * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously - * as soon as the result is available. The callbacks are called with a single argument: the result - * or rejection reason. Additionally, the notify callback may be called zero or more times to - * provide a progress indication, before the promise is resolved or rejected. - * - * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback`, `errorCallback`. It also notifies via the return value of the - * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback - * method. - * - * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` - * - * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, - * but to do so without modifying the final value. This is useful to release resources or do some - * clean-up that needs to be done whether the promise was rejected or resolved. See the [full - * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for - * more information. - * - * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as - * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to - * make your code IE8 and Android 2.x compatible. - * - * # Chaining promises - * - * Because calling the `then` method of a promise returns a new derived promise, it is easily - * possible to create a chain of promises: - * - * ```js - * promiseB = promiseA.then(function(result) { + * ``` + * + * At first it might not be obvious why this extra complexity is worth the trouble. The payoff + * comes in the way of guarantees that promise and deferred APIs make, see + * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. + * + * Additionally the promise api allows for composition that is very hard to do with the + * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. + * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the + * section on serial or parallel joining of promises. + * + * # The Deferred API + * + * A new instance of deferred is constructed by calling `$q.defer()`. + * + * The purpose of the deferred object is to expose the associated Promise instance as well as APIs + * that can be used for signaling the successful or unsuccessful completion, as well as the status + * of the task. + * + * **Methods** + * + * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection + * constructed via `$q.reject`, the promise will be rejected instead. + * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to + * resolving it with a rejection constructed via `$q.reject`. + * - `notify(value)` - provides updates on the status of the promise's execution. This may be called + * multiple times before the promise is either resolved or rejected. + * + * **Properties** + * + * - promise – `{Promise}` – promise object associated with this deferred. + * + * + * # The Promise API + * + * A new promise instance is created when a deferred instance is created and can be retrieved by + * calling `deferred.promise`. + * + * The purpose of the promise object is to allow for interested parties to get access to the result + * of the deferred task when it completes. + * + * **Methods** + * + * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or + * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously + * as soon as the result is available. The callbacks are called with a single argument: the result + * or rejection reason. Additionally, the notify callback may be called zero or more times to + * provide a progress indication, before the promise is resolved or rejected. + * + * This method *returns a new promise* which is resolved or rejected via the return value of the + * `successCallback`, `errorCallback`. It also notifies via the return value of the + * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback + * method. + * + * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` + * + * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. This is useful to release resources or do some + * clean-up that needs to be done whether the promise was rejected or resolved. See the [full + * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for + * more information. + * + * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as + * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to + * make your code IE8 and Android 2.x compatible. + * + * # Chaining promises + * + * Because calling the `then` method of a promise returns a new derived promise, it is easily + * possible to create a chain of promises: + * + * ```js + * promiseB = promiseA.then(function(result) { * return result + 1; * }); - * - * // promiseB will be resolved immediately after promiseA is resolved and its value - * // will be the result of promiseA incremented by 1 - * ``` - * - * It is possible to create chains of any length and since a promise can be resolved with another - * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful APIs like - * $http's response interceptors. - * - * - * # Differences between Kris Kowal's Q and $q - * - * There are two main differences: - * - * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation - * mechanism in angular, which means faster propagation of resolution or rejection into your - * models and avoiding unnecessary browser repaints, which would result in flickering UI. - * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains - * all the important functionality needed for common async tasks. - * - * # Testing - * - * ```js - * it('should simulate promise', inject(function($q, $rootScope) { + * + * // promiseB will be resolved immediately after promiseA is resolved and its value + * // will be the result of promiseA incremented by 1 + * ``` + * + * It is possible to create chains of any length and since a promise can be resolved with another + * promise (which will defer its resolution further), it is possible to pause/defer resolution of + * the promises at any point in the chain. This makes it possible to implement powerful APIs like + * $http's response interceptors. + * + * + * # Differences between Kris Kowal's Q and $q + * + * There are two main differences: + * + * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation + * mechanism in angular, which means faster propagation of resolution or rejection into your + * models and avoiding unnecessary browser repaints, which would result in flickering UI. + * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains + * all the important functionality needed for common async tasks. + * + * # Testing + * + * ```js + * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; @@ -12803,225 +12911,229 @@ function $ParseProvider() { * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * })); - * ``` - * - * @param {function(function, function)} resolver Function which is responsible for resolving or - * rejecting the newly created promise. The first parameter is a function which resolves the - * promise, the second parameter is a function which rejects the promise. - * - * @returns {Promise} The newly created promise. - */ -function $QProvider() { - - this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { - return qFactory(function(callback) { - $rootScope.$evalAsync(callback); - }, $exceptionHandler); - }]; -} - -function $$QProvider() { - this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { - return qFactory(function(callback) { - $browser.defer(callback); - }, $exceptionHandler); - }]; -} + * ``` + * + * @param {function(function, function)} resolver Function which is responsible for resolving or + * rejecting the newly created promise. The first parameter is a function which resolves the + * promise, the second parameter is a function which rejects the promise. + * + * @returns {Promise} The newly created promise. + */ + function $QProvider() { -/** - * Constructs a promise manager. - * - * @param {function(function)} nextTick Function for executing functions in the next turn. - * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for - * debugging purposes. - * @returns {object} Promise manager. - */ -function qFactory(nextTick, exceptionHandler) { - var $qMinErr = minErr('$q', TypeError); - function callOnce(self, resolveFn, rejectFn) { - var called = false; - function wrap(fn) { - return function(value) { - if (called) return; - called = true; - fn.call(self, value); - }; + this.$get = ['$rootScope', '$exceptionHandler', function ($rootScope, $exceptionHandler) { + return qFactory(function (callback) { + $rootScope.$evalAsync(callback); + }, $exceptionHandler); + }]; } - return [wrap(resolveFn), wrap(rejectFn)]; - } - - /** - * @ngdoc method - * @name ng.$q#defer - * @kind function - * - * @description - * Creates a `Deferred` object which represents a task which will finish in the future. - * - * @returns {Deferred} Returns a new instance of deferred. - */ - var defer = function() { - return new Deferred(); - }; - - function Promise() { - this.$$state = { status: 0 }; - } - - Promise.prototype = { - then: function(onFulfilled, onRejected, progressBack) { - var result = new Deferred(); - - this.$$state.pending = this.$$state.pending || []; - this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); - if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); - - return result.promise; - }, - - "catch": function(callback) { - return this.then(null, callback); - }, - - "finally": function(callback, progressBack) { - return this.then(function(value) { - return handleCallback(value, true, callback); - }, function(error) { - return handleCallback(error, false, callback); - }, progressBack); + function $$QProvider() { + this.$get = ['$browser', '$exceptionHandler', function ($browser, $exceptionHandler) { + return qFactory(function (callback) { + $browser.defer(callback); + }, $exceptionHandler); + }]; } - }; - //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native - function simpleBind(context, fn) { - return function(value) { - fn.call(context, value); - }; - } - - function processQueue(state) { - var fn, promise, pending; - - pending = state.pending; - state.processScheduled = false; - state.pending = undefined; - for (var i = 0, ii = pending.length; i < ii; ++i) { - promise = pending[i][0]; - fn = pending[i][state.status]; - try { - if (isFunction(fn)) { - promise.resolve(fn(state.value)); - } else if (state.status === 1) { - promise.resolve(state.value); - } else { - promise.reject(state.value); + /** + * Constructs a promise manager. + * + * @param {function(function)} nextTick Function for executing functions in the next turn. + * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for + * debugging purposes. + * @returns {object} Promise manager. + */ + function qFactory(nextTick, exceptionHandler) { + var $qMinErr = minErr('$q', TypeError); + + function callOnce(self, resolveFn, rejectFn) { + var called = false; + + function wrap(fn) { + return function (value) { + if (called) return; + called = true; + fn.call(self, value); + }; + } + + return [wrap(resolveFn), wrap(rejectFn)]; + } + + /** + * @ngdoc method + * @name ng.$q#defer + * @kind function + * + * @description + * Creates a `Deferred` object which represents a task which will finish in the future. + * + * @returns {Deferred} Returns a new instance of deferred. + */ + var defer = function () { + return new Deferred(); + }; + + function Promise() { + this.$$state = {status: 0}; } - } catch(e) { - promise.reject(e); - exceptionHandler(e); - } - } - } - - function scheduleProcessQueue(state) { - if (state.processScheduled || !state.pending) return; - state.processScheduled = true; - nextTick(function() { processQueue(state); }); - } - - function Deferred() { - this.promise = new Promise(); - //Necessary to support unbound execution :/ - this.resolve = simpleBind(this, this.resolve); - this.reject = simpleBind(this, this.reject); - this.notify = simpleBind(this, this.notify); - } - - Deferred.prototype = { - resolve: function(val) { - if (this.promise.$$state.status) return; - if (val === this.promise) { - this.$$reject($qMinErr( - 'qcycle', - "Expected promise to be resolved with value other than itself '{0}'", - val)); - } - else { - this.$$resolve(val); - } - }, + Promise.prototype = { + then: function (onFulfilled, onRejected, progressBack) { + var result = new Deferred(); - $$resolve: function(val) { - var then, fns; + this.$$state.pending = this.$$state.pending || []; + this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); + if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); - fns = callOnce(this, this.$$resolve, this.$$reject); - try { - if ((isObject(val) || isFunction(val))) then = val && val.then; - if (isFunction(then)) { - this.promise.$$state.status = -1; - then.call(val, fns[0], fns[1], this.notify); - } else { - this.promise.$$state.value = val; - this.promise.$$state.status = 1; - scheduleProcessQueue(this.promise.$$state); + return result.promise; + }, + + "catch": function (callback) { + return this.then(null, callback); + }, + + "finally": function (callback, progressBack) { + return this.then(function (value) { + return handleCallback(value, true, callback); + }, function (error) { + return handleCallback(error, false, callback); + }, progressBack); + } + }; + + //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native + function simpleBind(context, fn) { + return function (value) { + fn.call(context, value); + }; } - } catch(e) { - fns[1](e); - exceptionHandler(e); - } - }, - - reject: function(reason) { - if (this.promise.$$state.status) return; - this.$$reject(reason); - }, - - $$reject: function(reason) { - this.promise.$$state.value = reason; - this.promise.$$state.status = 2; - scheduleProcessQueue(this.promise.$$state); - }, - - notify: function(progress) { - var callbacks = this.promise.$$state.pending; - - if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) { - nextTick(function() { - var callback, result; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - result = callbacks[i][0]; - callback = callbacks[i][3]; - try { - result.notify(isFunction(callback) ? callback(progress) : progress); - } catch(e) { - exceptionHandler(e); + + function processQueue(state) { + var fn, promise, pending; + + pending = state.pending; + state.processScheduled = false; + state.pending = undefined; + for (var i = 0, ii = pending.length; i < ii; ++i) { + promise = pending[i][0]; + fn = pending[i][state.status]; + try { + if (isFunction(fn)) { + promise.resolve(fn(state.value)); + } else if (state.status === 1) { + promise.resolve(state.value); + } else { + promise.reject(state.value); + } + } catch (e) { + promise.reject(e); + exceptionHandler(e); + } } - } - }); - } - } - }; + } - /** - * @ngdoc method - * @name $q#reject - * @kind function - * - * @description - * Creates a promise that is resolved as rejected with the specified `reason`. This api should be - * used to forward rejection in a chain of promises. If you are dealing with the last promise in - * a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of - * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via - * a promise error callback and you want to forward the error to the promise derived from the - * current promise, you have to "rethrow" the error by returning a rejection constructed via - * `reject`. - * - * ```js - * promiseB = promiseA.then(function(result) { + function scheduleProcessQueue(state) { + if (state.processScheduled || !state.pending) return; + state.processScheduled = true; + nextTick(function () { + processQueue(state); + }); + } + + function Deferred() { + this.promise = new Promise(); + //Necessary to support unbound execution :/ + this.resolve = simpleBind(this, this.resolve); + this.reject = simpleBind(this, this.reject); + this.notify = simpleBind(this, this.notify); + } + + Deferred.prototype = { + resolve: function (val) { + if (this.promise.$$state.status) return; + if (val === this.promise) { + this.$$reject($qMinErr( + 'qcycle', + "Expected promise to be resolved with value other than itself '{0}'", + val)); + } + else { + this.$$resolve(val); + } + + }, + + $$resolve: function (val) { + var then, fns; + + fns = callOnce(this, this.$$resolve, this.$$reject); + try { + if ((isObject(val) || isFunction(val))) then = val && val.then; + if (isFunction(then)) { + this.promise.$$state.status = -1; + then.call(val, fns[0], fns[1], this.notify); + } else { + this.promise.$$state.value = val; + this.promise.$$state.status = 1; + scheduleProcessQueue(this.promise.$$state); + } + } catch (e) { + fns[1](e); + exceptionHandler(e); + } + }, + + reject: function (reason) { + if (this.promise.$$state.status) return; + this.$$reject(reason); + }, + + $$reject: function (reason) { + this.promise.$$state.value = reason; + this.promise.$$state.status = 2; + scheduleProcessQueue(this.promise.$$state); + }, + + notify: function (progress) { + var callbacks = this.promise.$$state.pending; + + if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) { + nextTick(function () { + var callback, result; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + result = callbacks[i][0]; + callback = callbacks[i][3]; + try { + result.notify(isFunction(callback) ? callback(progress) : progress); + } catch (e) { + exceptionHandler(e); + } + } + }); + } + } + }; + + /** + * @ngdoc method + * @name $q#reject + * @kind function + * + * @description + * Creates a promise that is resolved as rejected with the specified `reason`. This api should be + * used to forward rejection in a chain of promises. If you are dealing with the last promise in + * a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of + * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via + * a promise error callback and you want to forward the error to the promise derived from the + * current promise, you have to "rethrow" the error by returning a rejection constructed via + * `reject`. + * + * ```js + * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; @@ -13035,1673 +13147,1677 @@ function qFactory(nextTick, exceptionHandler) { * } * return $q.reject(reason); * }); - * ``` - * - * @param {*} reason Constant, message, exception or an object representing the rejection reason. - * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. - */ - var reject = function(reason) { - var result = new Deferred(); - result.reject(reason); - return result.promise; - }; - - var makePromise = function makePromise(value, resolved) { - var result = new Deferred(); - if (resolved) { - result.resolve(value); - } else { - result.reject(value); - } - return result.promise; - }; - - var handleCallback = function handleCallback(value, isResolved, callback) { - var callbackOutput = null; - try { - if (isFunction(callback)) callbackOutput = callback(); - } catch(e) { - return makePromise(e, false); - } - if (isPromiseLike(callbackOutput)) { - return callbackOutput.then(function() { - return makePromise(value, isResolved); - }, function(error) { - return makePromise(error, false); - }); - } else { - return makePromise(value, isResolved); - } - }; - - /** - * @ngdoc method - * @name $q#when - * @kind function - * - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise - */ - + * ``` + * + * @param {*} reason Constant, message, exception or an object representing the rejection reason. + * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. + */ + var reject = function (reason) { + var result = new Deferred(); + result.reject(reason); + return result.promise; + }; - var when = function(value, callback, errback, progressBack) { - var result = new Deferred(); - result.resolve(value); - return result.promise.then(callback, errback, progressBack); - }; + var makePromise = function makePromise(value, resolved) { + var result = new Deferred(); + if (resolved) { + result.resolve(value); + } else { + result.reject(value); + } + return result.promise; + }; - /** - * @ngdoc method - * @name $q#all - * @kind function - * - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.|Object.} promises An array or hash of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, - * each value corresponding to the promise at the same index/key in the `promises` array/hash. - * If any of the promises is resolved with a rejection, this resulting promise will be rejected - * with the same rejection value. - */ - - function all(promises) { - var deferred = new Deferred(), - counter = 0, - results = isArray(promises) ? [] : {}; - - forEach(promises, function(promise, key) { - counter++; - when(promise).then(function(value) { - if (results.hasOwnProperty(key)) return; - results[key] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (results.hasOwnProperty(key)) return; - deferred.reject(reason); - }); - }); + var handleCallback = function handleCallback(value, isResolved, callback) { + var callbackOutput = null; + try { + if (isFunction(callback)) callbackOutput = callback(); + } catch (e) { + return makePromise(e, false); + } + if (isPromiseLike(callbackOutput)) { + return callbackOutput.then(function () { + return makePromise(value, isResolved); + }, function (error) { + return makePromise(error, false); + }); + } else { + return makePromise(value, isResolved); + } + }; - if (counter === 0) { - deferred.resolve(results); - } + /** + * @ngdoc method + * @name $q#when + * @kind function + * + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @returns {Promise} Returns a promise of the passed value or promise + */ - return deferred.promise; - } - var $Q = function Q(resolver) { - if (!isFunction(resolver)) { - throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver); - } + var when = function (value, callback, errback, progressBack) { + var result = new Deferred(); + result.resolve(value); + return result.promise.then(callback, errback, progressBack); + }; - if (!(this instanceof Q)) { - // More useful when $Q is the Promise itself. - return new Q(resolver); - } + /** + * @ngdoc method + * @name $q#all + * @kind function + * + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. + * If any of the promises is resolved with a rejection, this resulting promise will be rejected + * with the same rejection value. + */ - var deferred = new Deferred(); + function all(promises) { + var deferred = new Deferred(), + counter = 0, + results = isArray(promises) ? [] : {}; + + forEach(promises, function (promise, key) { + counter++; + when(promise).then(function (value) { + if (results.hasOwnProperty(key)) return; + results[key] = value; + if (!(--counter)) deferred.resolve(results); + }, function (reason) { + if (results.hasOwnProperty(key)) return; + deferred.reject(reason); + }); + }); - function resolveFn(value) { - deferred.resolve(value); - } + if (counter === 0) { + deferred.resolve(results); + } - function rejectFn(reason) { - deferred.reject(reason); - } + return deferred.promise; + } - resolver(resolveFn, rejectFn); + var $Q = function Q(resolver) { + if (!isFunction(resolver)) { + throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver); + } - return deferred.promise; - }; + if (!(this instanceof Q)) { + // More useful when $Q is the Promise itself. + return new Q(resolver); + } - $Q.defer = defer; - $Q.reject = reject; - $Q.when = when; - $Q.all = all; + var deferred = new Deferred(); - return $Q; -} + function resolveFn(value) { + deferred.resolve(value); + } -function $$RAFProvider(){ //rAF - this.$get = ['$window', '$timeout', function($window, $timeout) { - var requestAnimationFrame = $window.requestAnimationFrame || - $window.webkitRequestAnimationFrame || - $window.mozRequestAnimationFrame; + function rejectFn(reason) { + deferred.reject(reason); + } - var cancelAnimationFrame = $window.cancelAnimationFrame || - $window.webkitCancelAnimationFrame || - $window.mozCancelAnimationFrame || - $window.webkitCancelRequestAnimationFrame; + resolver(resolveFn, rejectFn); - var rafSupported = !!requestAnimationFrame; - var raf = rafSupported - ? function(fn) { - var id = requestAnimationFrame(fn); - return function() { - cancelAnimationFrame(id); - }; - } - : function(fn) { - var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 - return function() { - $timeout.cancel(timer); - }; + return deferred.promise; }; - raf.supported = rafSupported; - - return raf; - }]; -} + $Q.defer = defer; + $Q.reject = reject; + $Q.when = when; + $Q.all = all; -/** - * DESIGN NOTES - * - * The design decisions behind the scope are heavily favored for speed and memory consumption. - * - * The typical use of scope is to watch the expressions, which most of the time return the same - * value as last time so we optimize the operation. - * - * Closures construction is expensive in terms of speed as well as memory: - * - No closures, instead use prototypical inheritance for API - * - Internal state needs to be stored on scope directly, which means that private state is - * exposed as $$____ properties - * - * Loop operations are optimized by using while(count--) { ... } - * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (unshift) instead of at the end (push) - * - * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list - * - * There are few watches then a lot of observers. This is why you don't want the observer to be - * implemented in the same way as watch. Watch requires return of initialization function which - * are expensive to construct. - */ + return $Q; + } + function $$RAFProvider() { //rAF + this.$get = ['$window', '$timeout', function ($window, $timeout) { + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame || + $window.mozRequestAnimationFrame; -/** - * @ngdoc provider - * @name $rootScopeProvider - * @description - * - * Provider for the $rootScope service. - */ + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.mozCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; -/** - * @ngdoc method - * @name $rootScopeProvider#digestTtl - * @description - * - * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and - * assuming that the model is unstable. - * - * The current default is 10 iterations. - * - * In complex applications it's possible that the dependencies between `$watch`s will result in - * several digest iterations. However if an application needs more than the default 10 digest - * iterations for its model to stabilize then you should investigate what is causing the model to - * continuously change during the digest. - * - * Increasing the TTL could have performance implications, so you should not change it without - * proper justification. - * - * @param {number} limit The number of digest iterations. - */ + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported + ? function (fn) { + var id = requestAnimationFrame(fn); + return function () { + cancelAnimationFrame(id); + }; + } + : function (fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function () { + $timeout.cancel(timer); + }; + }; + raf.supported = rafSupported; -/** - * @ngdoc service - * @name $rootScope - * @description - * - * Every application has a single root {@link ng.$rootScope.Scope scope}. - * All other scopes are descendant scopes of the root scope. Scopes provide separation - * between the model and the view, via a mechanism for watching the model for changes. - * They also provide an event emission/broadcast and subscription facility. See the - * {@link guide/scope developer guide on scopes}. - */ -function $RootScopeProvider(){ - var TTL = 10; - var $rootScopeMinErr = minErr('$rootScope'); - var lastDirtyWatch = null; - var applyAsyncId = null; - - this.digestTtl = function(value) { - if (arguments.length) { - TTL = value; + return raf; + }]; } - return TTL; - }; - - this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', - function( $injector, $exceptionHandler, $parse, $browser) { /** - * @ngdoc type - * @name $rootScope.Scope + * DESIGN NOTES * - * @description - * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the - * {@link auto.$injector $injector}. Child scopes are created using the - * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when - * compiled HTML template is executed.) + * The design decisions behind the scope are heavily favored for speed and memory consumption. * - * Here is a simple scope snippet to show how you can interact with the scope. - * ```html - * - * ``` + * The typical use of scope is to watch the expressions, which most of the time return the same + * value as last time so we optimize the operation. * - * # Inheritance - * A scope can inherit from a parent scope, as in this example: - * ```js - var parent = $rootScope; - var child = parent.$new(); - - parent.salutation = "Hello"; - child.name = "World"; - expect(child.salutation).toEqual('Hello'); - - child.salutation = "Welcome"; - expect(child.salutation).toEqual('Welcome'); - expect(parent.salutation).toEqual('Hello'); - * ``` + * Closures construction is expensive in terms of speed as well as memory: + * - No closures, instead use prototypical inheritance for API + * - Internal state needs to be stored on scope directly, which means that private state is + * exposed as $$____ properties * + * Loop operations are optimized by using while(count--) { ... } + * - this means that in order to keep the same order of execution as addition we have to add + * items to the array at the beginning (unshift) instead of at the end (push) * - * @param {Object.=} providers Map of service factory which need to be - * provided for the current scope. Defaults to {@link ng}. - * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy - * when unit-testing and having the need to override a default - * service. - * @returns {Object} Newly created scope. + * Child scopes are created and removed often + * - Using an array would be slow since inserts in middle are expensive so we use linked list * + * There are few watches then a lot of observers. This is why you don't want the observer to be + * implemented in the same way as watch. Watch requires return of initialization function which + * are expensive to construct. */ - function Scope() { - this.$id = nextUid(); - this.$$phase = this.$parent = this.$$watchers = - this.$$nextSibling = this.$$prevSibling = - this.$$childHead = this.$$childTail = null; - this.$root = this; - this.$$destroyed = false; - this.$$listeners = {}; - this.$$listenerCount = {}; - this.$$isolateBindings = null; - } + /** - * @ngdoc property - * @name $rootScope.Scope#$id - * + * @ngdoc provider + * @name $rootScopeProvider * @description - * Unique scope ID (monotonically increasing) useful for debugging. + * + * Provider for the $rootScope service. */ - /** - * @ngdoc property - * @name $rootScope.Scope#$parent - * - * @description - * Reference to the parent scope. - */ - - /** - * @ngdoc property - * @name $rootScope.Scope#$root - * - * @description - * Reference to the root scope. - */ - - Scope.prototype = { - constructor: Scope, - /** - * @ngdoc method - * @name $rootScope.Scope#$new - * @kind function - * - * @description - * Creates a new child {@link ng.$rootScope.Scope scope}. - * - * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. - * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. - * - * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is - * desired for the scope and its child scopes to be permanently detached from the parent and - * thus stop participating in model change detection and listener notification by invoking. - * - * @param {boolean} isolate If true, then the scope does not prototypically inherit from the - * parent scope. The scope is isolated, as it can not see parent scope properties. - * When creating widgets, it is useful for the widget to not accidentally read parent - * state. - * - * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` - * of the newly created scope. Defaults to `this` scope if not provided. - * This is used when creating a transclude scope to correctly place it - * in the scope hierarchy while maintaining the correct prototypical - * inheritance. - * - * @returns {Object} The newly created child scope. - * - */ - $new: function(isolate, parent) { - var child; - - parent = parent || this; - - if (isolate) { - child = new Scope(); - child.$root = this.$root; - } else { - // Only create a child scope class if somebody asks for one, - // but cache it to allow the VM to optimize lookups. - if (!this.$$ChildScope) { - this.$$ChildScope = function ChildScope() { - this.$$watchers = this.$$nextSibling = - this.$$childHead = this.$$childTail = null; - this.$$listeners = {}; - this.$$listenerCount = {}; - this.$id = nextUid(); - this.$$ChildScope = null; - }; - this.$$ChildScope.prototype = this; - } - child = new this.$$ChildScope(); - } - child.$parent = parent; - child.$$prevSibling = parent.$$childTail; - if (parent.$$childHead) { - parent.$$childTail.$$nextSibling = child; - parent.$$childTail = child; - } else { - parent.$$childHead = parent.$$childTail = child; - } + /** + * @ngdoc method + * @name $rootScopeProvider#digestTtl + * @description + * + * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that the dependencies between `$watch`s will result in + * several digest iterations. However if an application needs more than the default 10 digest + * iterations for its model to stabilize then you should investigate what is causing the model to + * continuously change during the digest. + * + * Increasing the TTL could have performance implications, so you should not change it without + * proper justification. + * + * @param {number} limit The number of digest iterations. + */ - // When the new scope is not isolated or we inherit from `this`, and - // the parent scope is destroyed, the property `$$destroyed` is inherited - // prototypically. In all other cases, this property needs to be set - // when the parent scope is destroyed. - // The listener needs to be added after the parent is set - if (isolate || parent != this) child.$on('$destroy', destroyChild); - return child; + /** + * @ngdoc service + * @name $rootScope + * @description + * + * Every application has a single root {@link ng.$rootScope.Scope scope}. + * All other scopes are descendant scopes of the root scope. Scopes provide separation + * between the model and the view, via a mechanism for watching the model for changes. + * They also provide an event emission/broadcast and subscription facility. See the + * {@link guide/scope developer guide on scopes}. + */ + function $RootScopeProvider() { + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + var lastDirtyWatch = null; + var applyAsyncId = null; + + this.digestTtl = function (value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; - function destroyChild() { - child.$$destroyed = true; - } - }, + this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', + function ($injector, $exceptionHandler, $parse, $browser) { + + /** + * @ngdoc type + * @name $rootScope.Scope + * + * @description + * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the + * {@link auto.$injector $injector}. Child scopes are created using the + * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when + * compiled HTML template is executed.) + * + * Here is a simple scope snippet to show how you can interact with the scope. + * ```html + * + * ``` + * + * # Inheritance + * A scope can inherit from a parent scope, as in this example: + * ```js + var parent = $rootScope; + var child = parent.$new(); + + parent.salutation = "Hello"; + child.name = "World"; + expect(child.salutation).toEqual('Hello'); + + child.salutation = "Welcome"; + expect(child.salutation).toEqual('Welcome'); + expect(parent.salutation).toEqual('Hello'); + * ``` + * + * + * @param {Object.=} providers Map of service factory which need to be + * provided for the current scope. Defaults to {@link ng}. + * @param {Object.=} instanceCache Provides pre-instantiated services which should + * append/override services provided by `providers`. This is handy + * when unit-testing and having the need to override a default + * service. + * @returns {Object} Newly created scope. + * + */ + function Scope() { + this.$id = nextUid(); + this.$$phase = this.$parent = this.$$watchers = + this.$$nextSibling = this.$$prevSibling = + this.$$childHead = this.$$childTail = null; + this.$root = this; + this.$$destroyed = false; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$isolateBindings = null; + } - /** - * @ngdoc method - * @name $rootScope.Scope#$watch - * @kind function - * - * @description - * Registers a `listener` callback to be executed whenever the `watchExpression` changes. - * - * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest + /** + * @ngdoc property + * @name $rootScope.Scope#$id + * + * @description + * Unique scope ID (monotonically increasing) useful for debugging. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$parent + * + * @description + * Reference to the parent scope. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$root + * + * @description + * Reference to the root scope. + */ + + Scope.prototype = { + constructor: Scope, + /** + * @ngdoc method + * @name $rootScope.Scope#$new + * @kind function + * + * @description + * Creates a new child {@link ng.$rootScope.Scope scope}. + * + * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. + * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. + * + * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is + * desired for the scope and its child scopes to be permanently detached from the parent and + * thus stop participating in model change detection and listener notification by invoking. + * + * @param {boolean} isolate If true, then the scope does not prototypically inherit from the + * parent scope. The scope is isolated, as it can not see parent scope properties. + * When creating widgets, it is useful for the widget to not accidentally read parent + * state. + * + * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` + * of the newly created scope. Defaults to `this` scope if not provided. + * This is used when creating a transclude scope to correctly place it + * in the scope hierarchy while maintaining the correct prototypical + * inheritance. + * + * @returns {Object} The newly created child scope. + * + */ + $new: function (isolate, parent) { + var child; + + parent = parent || this; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + } else { + // Only create a child scope class if somebody asks for one, + // but cache it to allow the VM to optimize lookups. + if (!this.$$ChildScope) { + this.$$ChildScope = function ChildScope() { + this.$$watchers = this.$$nextSibling = + this.$$childHead = this.$$childTail = null; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$id = nextUid(); + this.$$ChildScope = null; + }; + this.$$ChildScope.prototype = this; + } + child = new this.$$ChildScope(); + } + child.$parent = parent; + child.$$prevSibling = parent.$$childTail; + if (parent.$$childHead) { + parent.$$childTail.$$nextSibling = child; + parent.$$childTail = child; + } else { + parent.$$childHead = parent.$$childTail = child; + } + + // When the new scope is not isolated or we inherit from `this`, and + // the parent scope is destroyed, the property `$$destroyed` is inherited + // prototypically. In all other cases, this property needs to be set + // when the parent scope is destroyed. + // The listener needs to be added after the parent is set + if (isolate || parent != this) child.$on('$destroy', destroyChild); + + return child; + + function destroyChild() { + child.$$destroyed = true; + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$watch + * @kind function + * + * @description + * Registers a `listener` callback to be executed whenever the `watchExpression` changes. + * + * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest * $digest()} and should return the value that will be watched. (Since - * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the - * `watchExpression` can execute multiple times per - * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) - * - The `listener` is called only when the value from the current `watchExpression` and the - * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). Inequality is determined according to reference inequality, - * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) - * via the `!==` Javascript operator, unless `objectEquality == true` - * (see next point) - * - When `objectEquality == true`, inequality of the `watchExpression` is determined - * according to the {@link angular.equals} function. To save the value of the object for - * later comparison, the {@link angular.copy} function is used. This therefore means that - * watching complex objects will have adverse memory and performance implications. - * - The watch `listener` may change the model, which may trigger other `listener`s to fire. - * This is achieved by rerunning the watchers until no changes are detected. The rerun - * iteration limit is 10 to prevent an infinite loop deadlock. - * - * - * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, - * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a - * change is detected, be prepared for multiple calls to your listener.) - * - * After a watcher is registered with the scope, the `listener` fn is called asynchronously - * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the - * watcher. In rare cases, this is undesirable because the listener is called when the result - * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you - * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the - * listener was called due to initialization. - * - * - * - * # Example - * ```js - // let's assume that scope was dependency injected as the $rootScope - var scope = $rootScope; - scope.name = 'misko'; - scope.counter = 0; - - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { + * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the + * `watchExpression` can execute multiple times per + * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) + * - The `listener` is called only when the value from the current `watchExpression` and the + * previous call to `watchExpression` are not equal (with the exception of the initial run, + * see below). Inequality is determined according to reference inequality, + * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) + * via the `!==` Javascript operator, unless `objectEquality == true` + * (see next point) + * - When `objectEquality == true`, inequality of the `watchExpression` is determined + * according to the {@link angular.equals} function. To save the value of the object for + * later comparison, the {@link angular.copy} function is used. This therefore means that + * watching complex objects will have adverse memory and performance implications. + * - The watch `listener` may change the model, which may trigger other `listener`s to fire. + * This is achieved by rerunning the watchers until no changes are detected. The rerun + * iteration limit is 10 to prevent an infinite loop deadlock. + * + * + * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, + * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` + * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a + * change is detected, be prepared for multiple calls to your listener.) + * + * After a watcher is registered with the scope, the `listener` fn is called asynchronously + * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the + * watcher. In rare cases, this is undesirable because the listener is called when the result + * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you + * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the + * listener was called due to initialization. + * + * + * + * # Example + * ```js + // let's assume that scope was dependency injected as the $rootScope + var scope = $rootScope; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); - expect(scope.counter).toEqual(0); + expect(scope.counter).toEqual(0); - scope.$digest(); - // the listener is always called during the first $digest loop after it was registered - expect(scope.counter).toEqual(1); + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); - scope.$digest(); - // but now it will not be called unless the value changes - expect(scope.counter).toEqual(1); + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); - scope.name = 'adam'; - scope.$digest(); - expect(scope.counter).toEqual(2); + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); - // Using a function as a watchExpression - var food; - scope.foodCounter = 0; - expect(scope.foodCounter).toEqual(0); - scope.$watch( - // This function returns the value being watched. It is called for each turn of the $digest loop - function() { return food; }, - // This is the change listener, called when the value returned from the above function changes - function(newValue, oldValue) { + // Using a function as a watchExpression + var food; + scope.foodCounter = 0; + expect(scope.foodCounter).toEqual(0); + scope.$watch( + // This function returns the value being watched. It is called for each turn of the $digest loop + function() { return food; }, + // This is the change listener, called when the value returned from the above function changes + function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } - ); - // No digest has been run so the counter will be zero - expect(scope.foodCounter).toEqual(0); + ); + // No digest has been run so the counter will be zero + expect(scope.foodCounter).toEqual(0); + + // Run the digest but since food has not changed count will still be zero + scope.$digest(); + expect(scope.foodCounter).toEqual(0); + + // Update food and run digest. Now the counter will increment + food = 'cheeseburger'; + scope.$digest(); + expect(scope.foodCounter).toEqual(1); + + * ``` + * + * + * + * @param {(function()|string)} watchExpression Expression that is evaluated on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers + * a call to the `listener`. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(scope)`: called with current `scope` as a parameter. + * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value + * of `watchExpression` changes. + * + * - `newVal` contains the current value of the `watchExpression` + * - `oldVal` contains the previous value of the `watchExpression` + * - `scope` refers to the current scope + * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of + * comparing for reference equality. + * @returns {function()} Returns a deregistration function for this listener. + */ + $watch: function (watchExp, listener, objectEquality) { + var get = $parse(watchExp); + + if (get.$$watchDelegate) { + return get.$$watchDelegate(this, listener, objectEquality, get); + } + var scope = this, + array = scope.$$watchers, + watcher = { + fn: listener, + last: initWatchVal, + get: get, + exp: watchExp, + eq: !!objectEquality + }; + + lastDirtyWatch = null; + + if (!isFunction(listener)) { + watcher.fn = noop; + } + + if (!array) { + array = scope.$$watchers = []; + } + // we use unshift since we use a while loop in $digest for speed. + // the while loop reads in reverse order. + array.unshift(watcher); + + return function deregisterWatch() { + arrayRemove(array, watcher); + lastDirtyWatch = null; + }; + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$watchGroup + * @kind function + * + * @description + * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. + * If any one expression in the collection changes the `listener` is executed. + * + * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every + * call to $digest() to see if any items changes. + * - The `listener` is called whenever any expression in the `watchExpressions` array changes. + * + * @param {Array.} watchExpressions Array of expressions that will be individually + * watched using {@link ng.$rootScope.Scope#$watch $watch()} + * + * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any + * expression in `watchExpressions` changes + * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching + * those of `watchExpression` + * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching + * those of `watchExpression` + * The `scope` refers to the current scope. + * @returns {function()} Returns a de-registration function for all listeners. + */ + $watchGroup: function (watchExpressions, listener) { + var oldValues = new Array(watchExpressions.length); + var newValues = new Array(watchExpressions.length); + var deregisterFns = []; + var self = this; + var changeReactionScheduled = false; + var firstRun = true; + + if (!watchExpressions.length) { + // No expressions means we call the listener ASAP + var shouldCall = true; + self.$evalAsync(function () { + if (shouldCall) listener(newValues, newValues, self); + }); + return function deregisterWatchGroup() { + shouldCall = false; + }; + } + + if (watchExpressions.length === 1) { + // Special case size of one + return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { + newValues[0] = value; + oldValues[0] = oldValue; + listener(newValues, (value === oldValue) ? newValues : oldValues, scope); + }); + } + + forEach(watchExpressions, function (expr, i) { + var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { + newValues[i] = value; + oldValues[i] = oldValue; + if (!changeReactionScheduled) { + changeReactionScheduled = true; + self.$evalAsync(watchGroupAction); + } + }); + deregisterFns.push(unwatchFn); + }); + + function watchGroupAction() { + changeReactionScheduled = false; + + if (firstRun) { + firstRun = false; + listener(newValues, newValues, self); + } else { + listener(newValues, oldValues, self); + } + } + + return function deregisterWatchGroup() { + while (deregisterFns.length) { + deregisterFns.shift()(); + } + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$watchCollection + * @kind function + * + * @description + * Shallow watches the properties of an object and fires whenever any of the properties change + * (for arrays, this implies watching the array items; for object maps, this implies watching + * the properties). If a change is detected, the `listener` callback is fired. + * + * - The `obj` collection is observed via standard $watch operation and is examined on every + * call to $digest() to see if any items have been added, removed, or moved. + * - The `listener` is called whenever anything within the `obj` has changed. Examples include + * adding, removing, and moving items belonging to an object or array. + * + * + * # Example + * ```js + $scope.names = ['igor', 'matias', 'misko', 'james']; + $scope.dataCount = 4; + + $scope.$watchCollection('names', function(newNames, oldNames) { + $scope.dataCount = newNames.length; + }); - // Run the digest but since food has not changed count will still be zero - scope.$digest(); - expect(scope.foodCounter).toEqual(0); + expect($scope.dataCount).toEqual(4); + $scope.$digest(); + + //still at 4 ... no changes + expect($scope.dataCount).toEqual(4); + + $scope.names.pop(); + $scope.$digest(); + + //now there's been a change + expect($scope.dataCount).toEqual(3); + * ``` + * + * + * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The + * expression value should evaluate to an object or an array which is observed on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the + * collection will trigger a call to the `listener`. + * + * @param {function(newCollection, oldCollection, scope)} listener a callback function called + * when a change is detected. + * - The `newCollection` object is the newly modified data obtained from the `obj` expression + * - The `oldCollection` object is a copy of the former collection data. + * Due to performance considerations, the`oldCollection` value is computed only if the + * `listener` function declares two or more arguments. + * - The `scope` argument refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the + * de-registration function is executed, the internal watch operation is terminated. + */ + $watchCollection: function (obj, listener) { + $watchCollectionInterceptor.$stateful = true; + + var self = this; + // the current value, updated on each dirty-check run + var newValue; + // a shallow copy of the newValue from the last dirty-check run, + // updated to match newValue during dirty-check run + var oldValue; + // a shallow copy of the newValue from when the last change happened + var veryOldValue; + // only track veryOldValue if the listener is asking for it + var trackVeryOldValue = (listener.length > 1); + var changeDetected = 0; + var changeDetector = $parse(obj, $watchCollectionInterceptor); + var internalArray = []; + var internalObject = {}; + var initRun = true; + var oldLength = 0; + + function $watchCollectionInterceptor(_value) { + newValue = _value; + var newLength, key, bothNaN, newItem, oldItem; + + if (!isObject(newValue)) { // if primitive + if (oldValue !== newValue) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } + + newLength = newValue.length; + + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; i++) { + oldItem = oldValue[i]; + newItem = newValue[i]; + + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { + changeDetected++; + oldValue[i] = newItem; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (newValue.hasOwnProperty(key)) { + newLength++; + newItem = newValue[key]; + oldItem = oldValue[key]; + + if (key in oldValue) { + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { + changeDetected++; + oldValue[key] = newItem; + } + } else { + oldLength++; + oldValue[key] = newItem; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for (key in oldValue) { + if (!newValue.hasOwnProperty(key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; + } + + function $watchCollectionAction() { + if (initRun) { + initRun = false; + listener(newValue, newValue, self); + } else { + listener(newValue, veryOldValue, self); + } + + // make a copy for the next time a collection is changed + if (trackVeryOldValue) { + if (!isObject(newValue)) { + //primitive + veryOldValue = newValue; + } else if (isArrayLike(newValue)) { + veryOldValue = new Array(newValue.length); + for (var i = 0; i < newValue.length; i++) { + veryOldValue[i] = newValue[i]; + } + } else { // if object + veryOldValue = {}; + for (var key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + veryOldValue[key] = newValue[key]; + } + } + } + } + } + + return this.$watch(changeDetector, $watchCollectionAction); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$digest + * @kind function + * + * @description + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and + * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change + * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} + * until no more listeners are firing. This means that it is possible to get into an infinite + * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of + * iterations exceeds 10. + * + * Usually, you don't call `$digest()` directly in + * {@link ng.directive:ngController controllers} or in + * {@link ng.$compileProvider#directive directives}. + * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within + * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. + * + * If you want to be notified whenever `$digest()` is called, + * you can register a `watchExpression` function with + * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. + * + * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. + * + * # Example + * ```js + var scope = ...; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + * ``` + * + */ + $digest: function () { + var watch, value, last, + watchers, + length, + dirty, ttl = TTL, + next, current, target = this, + watchLog = [], + logIdx, logMsg, asyncTask; + + beginPhase('$digest'); + // Check for changes to browser url that happened in sync before the call to $digest + $browser.$$checkUrlChange(); + + if (this === $rootScope && applyAsyncId !== null) { + // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then + // cancel the scheduled $apply and flush the queue of expressions to be evaluated. + $browser.defer.cancel(applyAsyncId); + flushApplyAsync(); + } + + lastDirtyWatch = null; + + do { // "while dirty" loop + dirty = false; + current = target; + + while (asyncQueue.length) { + try { + asyncTask = asyncQueue.shift(); + asyncTask.scope.$eval(asyncTask.expression); + } catch (e) { + $exceptionHandler(e); + } + lastDirtyWatch = null; + } + + traverseScopesLoop: + do { // "traverse the scopes" loop + if ((watchers = current.$$watchers)) { + // process our watches + length = watchers.length; + while (length--) { + try { + watch = watchers[length]; + // Most common watches are on primitives, in which case we can short + // circuit it with === operator, only when === fails do we use .equals + if (watch) { + if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq + ? equals(value, last) + : (typeof value === 'number' && typeof last === 'number' + && isNaN(value) && isNaN(last)))) { + dirty = true; + lastDirtyWatch = watch; + watch.last = watch.eq ? copy(value, null) : value; + watch.fn(value, ((last === initWatchVal) ? value : last), current); + if (ttl < 5) { + logIdx = 4 - ttl; + if (!watchLog[logIdx]) watchLog[logIdx] = []; + logMsg = (isFunction(watch.exp)) + ? 'fn: ' + (watch.exp.name || watch.exp.toString()) + : watch.exp; + logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); + watchLog[logIdx].push(logMsg); + } + } else if (watch === lastDirtyWatch) { + // If the most recently dirty watcher is now clean, short circuit since the remaining watchers + // have already been tested. + dirty = false; + break traverseScopesLoop; + } + } + } catch (e) { + $exceptionHandler(e); + } + } + } + + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $broadcast + if (!(next = (current.$$childHead || + (current !== target && current.$$nextSibling)))) { + while (current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } while ((current = next)); + + // `break traverseScopesLoop;` takes us to here + + if ((dirty || asyncQueue.length) && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\n' + + 'Watchers fired in the last 5 iterations: {1}', + TTL, toJson(watchLog)); + } + + } while (dirty || asyncQueue.length); + + clearPhase(); + + while (postDigestQueue.length) { + try { + postDigestQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } + } + }, + + + /** + * @ngdoc event + * @name $rootScope.Scope#$destroy + * @eventType broadcast on scope being destroyed + * + * @description + * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + + /** + * @ngdoc method + * @name $rootScope.Scope#$destroy + * @kind function + * + * @description + * Removes the current scope (and all of its children) from the parent scope. Removal implies + * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer + * propagate to the current scope and its children. Removal also implies that the current + * scope is eligible for garbage collection. + * + * The `$destroy()` is usually used by directives such as + * {@link ng.directive:ngRepeat ngRepeat} for managing the + * unrolling of the loop. + * + * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. + * Application code can register a `$destroy` event handler that will give it a chance to + * perform any necessary cleanup. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + $destroy: function () { + // we can't destroy the root scope or a scope that has been already destroyed + if (this.$$destroyed) return; + var parent = this.$parent; + + this.$broadcast('$destroy'); + this.$$destroyed = true; + if (this === $rootScope) return; + + for (var eventName in this.$$listenerCount) { + decrementListenerCount(this, this.$$listenerCount[eventName], eventName); + } + + // sever all the references to parent scopes (after this cleanup, the current scope should + // not be retained by any of our references and should be eligible for garbage collection) + if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; + if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; + if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; + if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + + // Disable listeners, watchers and apply/digest methods + this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; + this.$on = this.$watch = this.$watchGroup = function () { + return noop; + }; + this.$$listeners = {}; + + // All of the code below is bogus code that works around V8's memory leak via optimized code + // and inline caches. + // + // see: + // - https://code.google.com/p/v8/issues/detail?id=2073#c26 + // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 + // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + + this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = + this.$$childTail = this.$root = this.$$watchers = null; + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$eval + * @kind function + * + * @description + * Executes the `expression` on the current scope and returns the result. Any exceptions in + * the expression are propagated (uncaught). This is useful when evaluating Angular + * expressions. + * + * # Example + * ```js + var scope = ng.$rootScope.Scope(); + scope.a = 1; + scope.b = 2; + + expect(scope.$eval('a+b')).toEqual(3); + expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); + * ``` + * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. + * @returns {*} The result of evaluating the expression. + */ + $eval: function (expr, locals) { + return $parse(expr)(this, locals); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$evalAsync + * @kind function + * + * @description + * Executes the expression on the current scope at a later point in time. + * + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only + * that: + * + * - it will execute after the function that scheduled the evaluation (preferably before DOM + * rendering). + * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after + * `expression` execution. + * + * Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle + * will be scheduled. However, it is encouraged to always call code that changes the model + * from within an `$apply` call. That includes code evaluated via `$evalAsync`. + * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + */ + $evalAsync: function (expr) { + // if we are outside of an $digest loop and this is the first time we are scheduling async + // task also schedule async auto-flush + if (!$rootScope.$$phase && !asyncQueue.length) { + $browser.defer(function () { + if (asyncQueue.length) { + $rootScope.$digest(); + } + }); + } + + asyncQueue.push({scope: this, expression: expr}); + }, + + $$postDigest: function (fn) { + postDigestQueue.push(fn); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$apply + * @kind function + * + * @description + * `$apply()` is used to execute an expression in angular from outside of the angular + * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). + * Because we are calling into the angular framework we need to perform proper scope life + * cycle of {@link ng.$exceptionHandler exception handling}, + * {@link ng.$rootScope.Scope#$digest executing watches}. + * + * ## Life cycle + * + * # Pseudo-Code of `$apply()` + * ```js + function $apply(expr) { + try { + return $eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + $root.$digest(); + } + } + * ``` + * + * + * Scope's `$apply()` method transitions through the following stages: + * + * 1. The {@link guide/expression expression} is executed using the + * {@link ng.$rootScope.Scope#$eval $eval()} method. + * 2. Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the + * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * + * + * @param {(string|function())=} exp An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + * + * @returns {*} The result of evaluating the expression. + */ + $apply: function (expr) { + try { + beginPhase('$apply'); + return this.$eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + clearPhase(); + try { + $rootScope.$digest(); + } catch (e) { + $exceptionHandler(e); + throw e; + } + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$applyAsync + * @kind function + * + * @description + * Schedule the invokation of $apply to occur at a later time. The actual time difference + * varies across browsers, but is typically around ~10 milliseconds. + * + * This can be used to queue up multiple expressions which need to be evaluated in the same + * digest. + * + * @param {(string|function())=} exp An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + */ + $applyAsync: function (expr) { + var scope = this; + expr && applyAsyncQueue.push($applyAsyncExpression); + scheduleApplyAsync(); + + function $applyAsyncExpression() { + scope.$eval(expr); + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$on + * @kind function + * + * @description + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for + * discussion of event life cycle. + * + * The event listener function format is: `function(event, args...)`. The `event` object + * passed into the listener has the following attributes: + * + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or + * `$broadcast`-ed. + * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the + * event propagates through the scope hierarchy, this property is set to null. + * - `name` - `{string}`: name of the event. + * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel + * further event propagation (available only for events that were `$emit`-ed). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag + * to true. + * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * + * @param {string} name Event name to listen on. + * @param {function(event, ...args)} listener Function to call when the event is emitted. + * @returns {function()} Returns a deregistration function for this listener. + */ + $on: function (name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); + + var current = this; + do { + if (!current.$$listenerCount[name]) { + current.$$listenerCount[name] = 0; + } + current.$$listenerCount[name]++; + } while ((current = current.$parent)); + + var self = this; + return function () { + namedListeners[namedListeners.indexOf(listener)] = null; + decrementListenerCount(self, 1, name); + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$emit + * @kind function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event traverses upwards toward the root scope and calls all + * registered listeners along the way. The event will stop propagating if one of the listeners + * cancels it. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). + */ + $emit: function (name, args) { + var empty = [], + namedListeners, + scope = this, + stopPropagation = false, + event = { + name: name, + targetScope: scope, + stopPropagation: function () { + stopPropagation = true; + }, + preventDefault: function () { + event.defaultPrevented = true; + }, + defaultPrevented: false + }, + listenerArgs = concat([event], arguments, 1), + i, length; + + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i = 0, length = namedListeners.length; i < length; i++) { + + // if listeners were deregistered, defragment the array + if (!namedListeners[i]) { + namedListeners.splice(i, 1); + i--; + length--; + continue; + } + try { + //allow all listeners attached to the current scope to run + namedListeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + //if any listener on the current scope stops propagation, prevent bubbling + if (stopPropagation) { + event.currentScope = null; + return event; + } + //traverse upwards + scope = scope.$parent; + } while (scope); + + event.currentScope = null; + + return event; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$broadcast + * @kind function + * + * @description + * Dispatches an event `name` downwards to all child scopes (and their children) notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$broadcast` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event propagates to all direct and indirect scopes of the current + * scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to broadcast. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} + */ + $broadcast: function (name, args) { + var target = this, + current = target, + next = target, + event = { + name: name, + targetScope: target, + preventDefault: function () { + event.defaultPrevented = true; + }, + defaultPrevented: false + }; + + if (!target.$$listenerCount[name]) return event; + + var listenerArgs = concat([event], arguments, 1), + listeners, i, length; + + //down while you can, then up and next sibling or up and next sibling until back at root + while ((current = next)) { + event.currentScope = current; + listeners = current.$$listeners[name] || []; + for (i = 0, length = listeners.length; i < length; i++) { + // if listeners were deregistered, defragment the array + if (!listeners[i]) { + listeners.splice(i, 1); + i--; + length--; + continue; + } + + try { + listeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $digest + // (though it differs due to having the extra check for $$listenerCount) + if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || + (current !== target && current.$$nextSibling)))) { + while (current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } + + event.currentScope = null; + return event; + } + }; - // Update food and run digest. Now the counter will increment - food = 'cheeseburger'; - scope.$digest(); - expect(scope.foodCounter).toEqual(1); + var $rootScope = new Scope(); - * ``` - * - * - * - * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers - * a call to the `listener`. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(scope)`: called with current `scope` as a parameter. - * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value - * of `watchExpression` changes. - * - * - `newVal` contains the current value of the `watchExpression` - * - `oldVal` contains the previous value of the `watchExpression` - * - `scope` refers to the current scope - * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of - * comparing for reference equality. - * @returns {function()} Returns a deregistration function for this listener. - */ - $watch: function(watchExp, listener, objectEquality) { - var get = $parse(watchExp); - - if (get.$$watchDelegate) { - return get.$$watchDelegate(this, listener, objectEquality, get); - } - var scope = this, - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; + //The internal queues. Expose them on the $rootScope for debugging/testing purposes. + var asyncQueue = $rootScope.$$asyncQueue = []; + var postDigestQueue = $rootScope.$$postDigestQueue = []; + var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; - lastDirtyWatch = null; + return $rootScope; - if (!isFunction(listener)) { - watcher.fn = noop; - } - if (!array) { - array = scope.$$watchers = []; - } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); + function beginPhase(phase) { + if ($rootScope.$$phase) { + throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); + } - return function deregisterWatch() { - arrayRemove(array, watcher); - lastDirtyWatch = null; - }; - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$watchGroup - * @kind function - * - * @description - * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. - * If any one expression in the collection changes the `listener` is executed. - * - * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every - * call to $digest() to see if any items changes. - * - The `listener` is called whenever any expression in the `watchExpressions` array changes. - * - * @param {Array.} watchExpressions Array of expressions that will be individually - * watched using {@link ng.$rootScope.Scope#$watch $watch()} - * - * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any - * expression in `watchExpressions` changes - * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching - * those of `watchExpression` - * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching - * those of `watchExpression` - * The `scope` refers to the current scope. - * @returns {function()} Returns a de-registration function for all listeners. - */ - $watchGroup: function(watchExpressions, listener) { - var oldValues = new Array(watchExpressions.length); - var newValues = new Array(watchExpressions.length); - var deregisterFns = []; - var self = this; - var changeReactionScheduled = false; - var firstRun = true; - - if (!watchExpressions.length) { - // No expressions means we call the listener ASAP - var shouldCall = true; - self.$evalAsync(function () { - if (shouldCall) listener(newValues, newValues, self); - }); - return function deregisterWatchGroup() { - shouldCall = false; - }; - } - - if (watchExpressions.length === 1) { - // Special case size of one - return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { - newValues[0] = value; - oldValues[0] = oldValue; - listener(newValues, (value === oldValue) ? newValues : oldValues, scope); - }); - } - - forEach(watchExpressions, function (expr, i) { - var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { - newValues[i] = value; - oldValues[i] = oldValue; - if (!changeReactionScheduled) { - changeReactionScheduled = true; - self.$evalAsync(watchGroupAction); - } - }); - deregisterFns.push(unwatchFn); - }); - - function watchGroupAction() { - changeReactionScheduled = false; - - if (firstRun) { - firstRun = false; - listener(newValues, newValues, self); - } else { - listener(newValues, oldValues, self); - } - } - - return function deregisterWatchGroup() { - while (deregisterFns.length) { - deregisterFns.shift()(); - } - }; - }, - - - /** - * @ngdoc method - * @name $rootScope.Scope#$watchCollection - * @kind function - * - * @description - * Shallow watches the properties of an object and fires whenever any of the properties change - * (for arrays, this implies watching the array items; for object maps, this implies watching - * the properties). If a change is detected, the `listener` callback is fired. - * - * - The `obj` collection is observed via standard $watch operation and is examined on every - * call to $digest() to see if any items have been added, removed, or moved. - * - The `listener` is called whenever anything within the `obj` has changed. Examples include - * adding, removing, and moving items belonging to an object or array. - * - * - * # Example - * ```js - $scope.names = ['igor', 'matias', 'misko', 'james']; - $scope.dataCount = 4; - - $scope.$watchCollection('names', function(newNames, oldNames) { - $scope.dataCount = newNames.length; - }); - - expect($scope.dataCount).toEqual(4); - $scope.$digest(); - - //still at 4 ... no changes - expect($scope.dataCount).toEqual(4); - - $scope.names.pop(); - $scope.$digest(); - - //now there's been a change - expect($scope.dataCount).toEqual(3); - * ``` - * - * - * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The - * expression value should evaluate to an object or an array which is observed on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the - * collection will trigger a call to the `listener`. - * - * @param {function(newCollection, oldCollection, scope)} listener a callback function called - * when a change is detected. - * - The `newCollection` object is the newly modified data obtained from the `obj` expression - * - The `oldCollection` object is a copy of the former collection data. - * Due to performance considerations, the`oldCollection` value is computed only if the - * `listener` function declares two or more arguments. - * - The `scope` argument refers to the current scope. - * - * @returns {function()} Returns a de-registration function for this listener. When the - * de-registration function is executed, the internal watch operation is terminated. - */ - $watchCollection: function(obj, listener) { - $watchCollectionInterceptor.$stateful = true; - - var self = this; - // the current value, updated on each dirty-check run - var newValue; - // a shallow copy of the newValue from the last dirty-check run, - // updated to match newValue during dirty-check run - var oldValue; - // a shallow copy of the newValue from when the last change happened - var veryOldValue; - // only track veryOldValue if the listener is asking for it - var trackVeryOldValue = (listener.length > 1); - var changeDetected = 0; - var changeDetector = $parse(obj, $watchCollectionInterceptor); - var internalArray = []; - var internalObject = {}; - var initRun = true; - var oldLength = 0; - - function $watchCollectionInterceptor(_value) { - newValue = _value; - var newLength, key, bothNaN, newItem, oldItem; - - if (!isObject(newValue)) { // if primitive - if (oldValue !== newValue) { - oldValue = newValue; - changeDetected++; - } - } else if (isArrayLike(newValue)) { - if (oldValue !== internalArray) { - // we are transitioning from something which was not an array into array. - oldValue = internalArray; - oldLength = oldValue.length = 0; - changeDetected++; - } - - newLength = newValue.length; - - if (oldLength !== newLength) { - // if lengths do not match we need to trigger change notification - changeDetected++; - oldValue.length = oldLength = newLength; - } - // copy the items to oldValue and look for changes. - for (var i = 0; i < newLength; i++) { - oldItem = oldValue[i]; - newItem = newValue[i]; - - bothNaN = (oldItem !== oldItem) && (newItem !== newItem); - if (!bothNaN && (oldItem !== newItem)) { - changeDetected++; - oldValue[i] = newItem; - } - } - } else { - if (oldValue !== internalObject) { - // we are transitioning from something which was not an object into object. - oldValue = internalObject = {}; - oldLength = 0; - changeDetected++; - } - // copy the items to oldValue and look for changes. - newLength = 0; - for (key in newValue) { - if (newValue.hasOwnProperty(key)) { - newLength++; - newItem = newValue[key]; - oldItem = oldValue[key]; - - if (key in oldValue) { - bothNaN = (oldItem !== oldItem) && (newItem !== newItem); - if (!bothNaN && (oldItem !== newItem)) { - changeDetected++; - oldValue[key] = newItem; - } - } else { - oldLength++; - oldValue[key] = newItem; - changeDetected++; - } - } - } - if (oldLength > newLength) { - // we used to have more keys, need to find them and destroy them. - changeDetected++; - for(key in oldValue) { - if (!newValue.hasOwnProperty(key)) { - oldLength--; - delete oldValue[key]; + $rootScope.$$phase = phase; } - } - } - } - return changeDetected; - } - function $watchCollectionAction() { - if (initRun) { - initRun = false; - listener(newValue, newValue, self); - } else { - listener(newValue, veryOldValue, self); - } - - // make a copy for the next time a collection is changed - if (trackVeryOldValue) { - if (!isObject(newValue)) { - //primitive - veryOldValue = newValue; - } else if (isArrayLike(newValue)) { - veryOldValue = new Array(newValue.length); - for (var i = 0; i < newValue.length; i++) { - veryOldValue[i] = newValue[i]; - } - } else { // if object - veryOldValue = {}; - for (var key in newValue) { - if (hasOwnProperty.call(newValue, key)) { - veryOldValue[key] = newValue[key]; + function clearPhase() { + $rootScope.$$phase = null; } - } - } - } - } - - return this.$watch(changeDetector, $watchCollectionAction); - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$digest - * @kind function - * - * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and - * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change - * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} - * until no more listeners are firing. This means that it is possible to get into an infinite - * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of - * iterations exceeds 10. - * - * Usually, you don't call `$digest()` directly in - * {@link ng.directive:ngController controllers} or in - * {@link ng.$compileProvider#directive directives}. - * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within - * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. - * - * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with - * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. - * - * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. - * - * # Example - * ```js - var scope = ...; - scope.name = 'misko'; - scope.counter = 0; - - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { - scope.counter = scope.counter + 1; - }); - expect(scope.counter).toEqual(0); - - scope.$digest(); - // the listener is always called during the first $digest loop after it was registered - expect(scope.counter).toEqual(1); - scope.$digest(); - // but now it will not be called unless the value changes - expect(scope.counter).toEqual(1); - - scope.name = 'adam'; - scope.$digest(); - expect(scope.counter).toEqual(2); - * ``` - * - */ - $digest: function() { - var watch, value, last, - watchers, - length, - dirty, ttl = TTL, - next, current, target = this, - watchLog = [], - logIdx, logMsg, asyncTask; - - beginPhase('$digest'); - // Check for changes to browser url that happened in sync before the call to $digest - $browser.$$checkUrlChange(); - - if (this === $rootScope && applyAsyncId !== null) { - // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then - // cancel the scheduled $apply and flush the queue of expressions to be evaluated. - $browser.defer.cancel(applyAsyncId); - flushApplyAsync(); - } - lastDirtyWatch = null; + function decrementListenerCount(current, count, name) { + do { + current.$$listenerCount[name] -= count; - do { // "while dirty" loop - dirty = false; - current = target; + if (current.$$listenerCount[name] === 0) { + delete current.$$listenerCount[name]; + } + } while ((current = current.$parent)); + } - while(asyncQueue.length) { - try { - asyncTask = asyncQueue.shift(); - asyncTask.scope.$eval(asyncTask.expression); - } catch (e) { - $exceptionHandler(e); - } - lastDirtyWatch = null; - } + /** + * function used as an initial value for watchers. + * because it's unique we can easily tell it apart from other values + */ + function initWatchVal() { + } - traverseScopesLoop: - do { // "traverse the scopes" loop - if ((watchers = current.$$watchers)) { - // process our watches - length = watchers.length; - while (length--) { - try { - watch = watchers[length]; - // Most common watches are on primitives, in which case we can short - // circuit it with === operator, only when === fails do we use .equals - if (watch) { - if ((value = watch.get(current)) !== (last = watch.last) && - !(watch.eq - ? equals(value, last) - : (typeof value === 'number' && typeof last === 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - lastDirtyWatch = watch; - watch.last = watch.eq ? copy(value, null) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); - } - } else if (watch === lastDirtyWatch) { - // If the most recently dirty watcher is now clean, short circuit since the remaining watchers - // have already been tested. - dirty = false; - break traverseScopesLoop; + function flushApplyAsync() { + while (applyAsyncQueue.length) { + try { + applyAsyncQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } } - } - } catch (e) { - $exceptionHandler(e); + applyAsyncId = null; } - } - } - - // Insanity Warning: scope depth-first traversal - // yes, this code is a bit crazy, but it works and we have tests to prove it! - // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || - (current !== target && current.$$nextSibling)))) { - while(current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } - } - } while ((current = next)); - - // `break traverseScopesLoop;` takes us to here - - if((dirty || asyncQueue.length) && !(ttl--)) { - clearPhase(); - throw $rootScopeMinErr('infdig', - '{0} $digest() iterations reached. Aborting!\n' + - 'Watchers fired in the last 5 iterations: {1}', - TTL, toJson(watchLog)); - } - - } while (dirty || asyncQueue.length); - - clearPhase(); - - while(postDigestQueue.length) { - try { - postDigestQueue.shift()(); - } catch (e) { - $exceptionHandler(e); - } - } - }, + function scheduleApplyAsync() { + if (applyAsyncId === null) { + applyAsyncId = $browser.defer(function () { + $rootScope.$apply(flushApplyAsync); + }); + } + } + }]; + } - /** - * @ngdoc event - * @name $rootScope.Scope#$destroy - * @eventType broadcast on scope being destroyed - * - * @description - * Broadcasted when a scope and its children are being destroyed. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ - - /** - * @ngdoc method - * @name $rootScope.Scope#$destroy - * @kind function - * - * @description - * Removes the current scope (and all of its children) from the parent scope. Removal implies - * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer - * propagate to the current scope and its children. Removal also implies that the current - * scope is eligible for garbage collection. - * - * The `$destroy()` is usually used by directives such as - * {@link ng.directive:ngRepeat ngRepeat} for managing the - * unrolling of the loop. - * - * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. - * Application code can register a `$destroy` event handler that will give it a chance to - * perform any necessary cleanup. - * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. - */ - $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed - if (this.$$destroyed) return; - var parent = this.$parent; - - this.$broadcast('$destroy'); - this.$$destroyed = true; - if (this === $rootScope) return; - - for (var eventName in this.$$listenerCount) { - decrementListenerCount(this, this.$$listenerCount[eventName], eventName); - } + /** + * @description + * Private service to sanitize uris for links and images. Used by $compile and $sanitize. + */ + function $$SanitizeUriProvider() { + var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, + imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; - // sever all the references to parent scopes (after this cleanup, the current scope should - // not be retained by any of our references and should be eligible for garbage collection) - if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; - if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; - if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; - if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; - - // Disable listeners, watchers and apply/digest methods - this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; - this.$on = this.$watch = this.$watchGroup = function() { return noop; }; - this.$$listeners = {}; - - // All of the code below is bogus code that works around V8's memory leak via optimized code - // and inline caches. - // - // see: - // - https://code.google.com/p/v8/issues/detail?id=2073#c26 - // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 - // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 - - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = this.$root = this.$$watchers = null; - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$eval - * @kind function - * - * @description - * Executes the `expression` on the current scope and returns the result. Any exceptions in - * the expression are propagated (uncaught). This is useful when evaluating Angular - * expressions. - * - * # Example - * ```js - var scope = ng.$rootScope.Scope(); - scope.a = 1; - scope.b = 2; - - expect(scope.$eval('a+b')).toEqual(3); - expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); - * ``` - * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - * @param {(object)=} locals Local variables object, useful for overriding values in scope. - * @returns {*} The result of evaluating the expression. - */ - $eval: function(expr, locals) { - return $parse(expr)(this, locals); - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$evalAsync - * @kind function - * - * @description - * Executes the expression on the current scope at a later point in time. - * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only - * that: - * - * - it will execute after the function that scheduled the evaluation (preferably before DOM - * rendering). - * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after - * `expression` execution. - * - * Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle - * will be scheduled. However, it is encouraged to always call code that changes the model - * from within an `$apply` call. That includes code evaluated via `$evalAsync`. - * - * @param {(string|function())=} expression An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with the current `scope` parameter. - * - */ - $evalAsync: function(expr) { - // if we are outside of an $digest loop and this is the first time we are scheduling async - // task also schedule async auto-flush - if (!$rootScope.$$phase && !asyncQueue.length) { - $browser.defer(function() { - if (asyncQueue.length) { - $rootScope.$digest(); + /** + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during a[href] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function (regexp) { + if (isDefined(regexp)) { + aHrefSanitizationWhitelist = regexp; + return this; } - }); - } - - asyncQueue.push({scope: this, expression: expr}); - }, - - $$postDigest : function(fn) { - postDigestQueue.push(fn); - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$apply - * @kind function - * - * @description - * `$apply()` is used to execute an expression in angular from outside of the angular - * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life - * cycle of {@link ng.$exceptionHandler exception handling}, - * {@link ng.$rootScope.Scope#$digest executing watches}. - * - * ## Life cycle - * - * # Pseudo-Code of `$apply()` - * ```js - function $apply(expr) { - try { - return $eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - $root.$digest(); - } - } - * ``` - * - * - * Scope's `$apply()` method transitions through the following stages: - * - * 1. The {@link guide/expression expression} is executed using the - * {@link ng.$rootScope.Scope#$eval $eval()} method. - * 2. Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the - * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. - * - * - * @param {(string|function())=} exp An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with current `scope` parameter. - * - * @returns {*} The result of evaluating the expression. - */ - $apply: function(expr) { - try { - beginPhase('$apply'); - return this.$eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - clearPhase(); - try { - $rootScope.$digest(); - } catch (e) { - $exceptionHandler(e); - throw e; - } - } - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$applyAsync - * @kind function - * - * @description - * Schedule the invokation of $apply to occur at a later time. The actual time difference - * varies across browsers, but is typically around ~10 milliseconds. - * - * This can be used to queue up multiple expressions which need to be evaluated in the same - * digest. - * - * @param {(string|function())=} exp An angular expression to be executed. - * - * - `string`: execute using the rules as defined in {@link guide/expression expression}. - * - `function(scope)`: execute the function with current `scope` parameter. - */ - $applyAsync: function(expr) { - var scope = this; - expr && applyAsyncQueue.push($applyAsyncExpression); - scheduleApplyAsync(); - - function $applyAsyncExpression() { - scope.$eval(expr); - } - }, - - /** - * @ngdoc method - * @name $rootScope.Scope#$on - * @kind function - * - * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for - * discussion of event life cycle. - * - * The event listener function format is: `function(event, args...)`. The `event` object - * passed into the listener has the following attributes: - * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or - * `$broadcast`-ed. - * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the - * event propagates through the scope hierarchy, this property is set to null. - * - `name` - `{string}`: name of the event. - * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel - * further event propagation (available only for events that were `$emit`-ed). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag - * to true. - * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. - * - * @param {string} name Event name to listen on. - * @param {function(event, ...args)} listener Function to call when the event is emitted. - * @returns {function()} Returns a deregistration function for this listener. - */ - $on: function(name, listener) { - var namedListeners = this.$$listeners[name]; - if (!namedListeners) { - this.$$listeners[name] = namedListeners = []; - } - namedListeners.push(listener); - - var current = this; - do { - if (!current.$$listenerCount[name]) { - current.$$listenerCount[name] = 0; - } - current.$$listenerCount[name]++; - } while ((current = current.$parent)); - - var self = this; - return function() { - namedListeners[namedListeners.indexOf(listener)] = null; - decrementListenerCount(self, 1, name); + return aHrefSanitizationWhitelist; }; - }, - /** - * @ngdoc method - * @name $rootScope.Scope#$emit - * @kind function - * - * @description - * Dispatches an event `name` upwards through the scope hierarchy notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. - * - * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get - * notified. Afterwards, the event traverses upwards toward the root scope and calls all - * registered listeners along the way. The event will stop propagating if one of the listeners - * cancels it. - * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {string} name Event name to emit. - * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. - * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). - */ - $emit: function(name, args) { - var empty = [], - namedListeners, - scope = this, - stopPropagation = false, - event = { - name: name, - targetScope: scope, - stopPropagation: function() {stopPropagation = true;}, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }, - listenerArgs = concat([event], arguments, 1), - i, length; - - do { - namedListeners = scope.$$listeners[name] || empty; - event.currentScope = scope; - for (i=0, length=namedListeners.length; i -1) { - throw $sceMinErr('iwcard', - 'Illegal sequence *** in string matcher. String: {0}', matcher); + function escapeForRegexp(s) { + return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) { + throw $sceMinErr('iwcard', + 'Illegal sequence *** in string matcher. String: {0}', matcher); + } + matcher = escapeForRegexp(matcher). + replace('\\*\\*', '.*'). + replace('\\*', '[^:/.?&;]*'); + return new RegExp('^' + matcher + '$'); + } else if (isRegExp(matcher)) { + // The only other type of matcher allowed is a Regexp. + // Match entire URL / disallow partial matches. + // Flags are reset (i.e. no global, ignoreCase or multiline) + return new RegExp('^' + matcher.source + '$'); + } else { + throw $sceMinErr('imatcher', + 'Matchers may only be "self", string patterns or RegExp objects'); + } } - matcher = escapeForRegexp(matcher). - replace('\\*\\*', '.*'). - replace('\\*', '[^:/.?&;]*'); - return new RegExp('^' + matcher + '$'); - } else if (isRegExp(matcher)) { - // The only other type of matcher allowed is a Regexp. - // Match entire URL / disallow partial matches. - // Flags are reset (i.e. no global, ignoreCase or multiline) - return new RegExp('^' + matcher.source + '$'); - } else { - throw $sceMinErr('imatcher', - 'Matchers may only be "self", string patterns or RegExp objects'); - } -} - - -function adjustMatchers(matchers) { - var adjustedMatchers = []; - if (isDefined(matchers)) { - forEach(matchers, function(matcher) { - adjustedMatchers.push(adjustMatcher(matcher)); - }); - } - return adjustedMatchers; -} -/** - * @ngdoc service - * @name $sceDelegate - * @kind function - * - * @description - * - * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict + function adjustMatchers(matchers) { + var adjustedMatchers = []; + if (isDefined(matchers)) { + forEach(matchers, function (matcher) { + adjustedMatchers.push(adjustMatcher(matcher)); + }); + } + return adjustedMatchers; + } + + + /** + * @ngdoc service + * @name $sceDelegate + * @kind function + * + * @description + * + * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict * Contextual Escaping (SCE)} services to AngularJS. - * - * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of - * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is - * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to - * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things - * work because `$sce` delegates to `$sceDelegate` for these operations. - * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. - * - * The default instance of `$sceDelegate` should work out of the box with little pain. While you - * can override it completely to change the behavior of `$sce`, the common case would - * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting - * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as - * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist + * + * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of + * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is + * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to + * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things + * work because `$sce` delegates to `$sceDelegate` for these operations. + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. + * + * The default instance of `$sceDelegate` should work out of the box with little pain. While you + * can override it completely to change the behavior of `$sce`, the common case would + * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting + * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as + * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist * $sceDelegateProvider.resourceUrlWhitelist} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} - */ + * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + */ -/** - * @ngdoc provider - * @name $sceDelegateProvider - * @description - * - * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate + /** + * @ngdoc provider + * @name $sceDelegateProvider + * @description + * + * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure - * that the URLs used for sourcing Angular templates are safe. Refer {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and - * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} - * - * For the general details about this service in Angular, read the main page for {@link ng.$sce + * that the URLs used for sourcing Angular templates are safe. Refer {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and + * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + * + * For the general details about this service in Angular, read the main page for {@link ng.$sce * Strict Contextual Escaping (SCE)}. - * - * **Example**: Consider the following case. - * - * - your app is hosted at url `http://myapp.example.com/` - * - but some of your templates are hosted on other domains you control such as - * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. - * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. - * - * Here is what a secure configuration for this scenario might look like: - * - * ``` - * angular.module('myApp', []).config(function($sceDelegateProvider) { + * + * **Example**: Consider the following case. + * + * - your app is hosted at url `http://myapp.example.com/` + * - but some of your templates are hosted on other domains you control such as + * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. + * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. + * + * Here is what a secure configuration for this scenario might look like: + * + * ``` + * angular.module('myApp', []).config(function($sceDelegateProvider) { * $sceDelegateProvider.resourceUrlWhitelist([ * // Allow same origin resource loads. * 'self', @@ -14714,1271 +14830,1274 @@ function adjustMatchers(matchers) { * 'http://myapp.example.com/clickThru**' * ]); * }); - * ``` - */ - -function $SceDelegateProvider() { - this.SCE_CONTEXTS = SCE_CONTEXTS; - - // Resource URLs can also be trusted by policy. - var resourceUrlWhitelist = ['self'], - resourceUrlBlacklist = []; - - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlWhitelist - * @kind function - * - * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. - * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. - * - * Note: **an empty whitelist array will block all URLs**! - * - * @return {Array} the currently set whitelist array. - * - * The **default value** when no whitelist has been explicitly set is `['self']` allowing only - * same origin resource requests. - * - * @description - * Sets/Gets the whitelist of trusted resource URLs. - */ - this.resourceUrlWhitelist = function (value) { - if (arguments.length) { - resourceUrlWhitelist = adjustMatchers(value); - } - return resourceUrlWhitelist; - }; - - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlBlacklist - * @kind function - * - * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. - * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. - * - * The typical usage for the blacklist is to **block - * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as - * these would otherwise be trusted but actually return content from the redirected domain. - * - * Finally, **the blacklist overrides the whitelist** and has the final say. - * - * @return {Array} the currently set blacklist array. - * - * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there - * is no blacklist.) - * - * @description - * Sets/Gets the blacklist of trusted resource URLs. - */ - - this.resourceUrlBlacklist = function (value) { - if (arguments.length) { - resourceUrlBlacklist = adjustMatchers(value); - } - return resourceUrlBlacklist; - }; - - this.$get = ['$injector', function($injector) { - - var htmlSanitizer = function htmlSanitizer(html) { - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); - }; + * ``` + */ - if ($injector.has('$sanitize')) { - htmlSanitizer = $injector.get('$sanitize'); - } + function $SceDelegateProvider() { + this.SCE_CONTEXTS = SCE_CONTEXTS; + // Resource URLs can also be trusted by policy. + var resourceUrlWhitelist = ['self'], + resourceUrlBlacklist = []; - function matchUrl(matcher, parsedUrl) { - if (matcher === 'self') { - return urlIsSameOrigin(parsedUrl); - } else { - // definitely a regex. See adjustMatchers() - return !!matcher.exec(parsedUrl.href); - } - } - - function isResourceUrlAllowedByPolicy(url) { - var parsedUrl = urlResolve(url.toString()); - var i, n, allowed = false; - // Ensure that at least one item from the whitelist allows this url. - for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { - if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { - allowed = true; - break; - } - } - if (allowed) { - // Ensure that no item from the blacklist blocked this url. - for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { - if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { - allowed = false; - break; - } - } - } - return allowed; - } - - function generateHolderType(Base) { - var holderType = function TrustedValueHolderType(trustedValue) { - this.$$unwrapTrustedValue = function() { - return trustedValue; + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function + * + * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * Note: **an empty whitelist array will block all URLs**! + * + * @return {Array} the currently set whitelist array. + * + * The **default value** when no whitelist has been explicitly set is `['self']` allowing only + * same origin resource requests. + * + * @description + * Sets/Gets the whitelist of trusted resource URLs. + */ + this.resourceUrlWhitelist = function (value) { + if (arguments.length) { + resourceUrlWhitelist = adjustMatchers(value); + } + return resourceUrlWhitelist; }; - }; - if (Base) { - holderType.prototype = new Base(); - } - holderType.prototype.valueOf = function sceValueOf() { - return this.$$unwrapTrustedValue(); - }; - holderType.prototype.toString = function sceToString() { - return this.$$unwrapTrustedValue().toString(); - }; - return holderType; - } - - var trustedValueHolderBase = generateHolderType(), - byType = {}; - - byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); - /** - * @ngdoc method - * @name $sceDelegate#trustAs - * - * @description - * Returns an object that is trusted by angular for use in specified strict - * contextual escaping contexts (such as ng-bind-html, ng-include, any src - * attribute interpolation, any dom event binding attribute interpolation - * such as for onclick, etc.) that uses the provided value. - * See {@link ng.$sce $sce} for enabling strict contextual escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resourceUrl, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. - */ - function trustAs(type, trustedValue) { - var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - if (!Constructor) { - throw $sceMinErr('icontext', - 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', - type, trustedValue); - } - if (trustedValue === null || trustedValue === undefined || trustedValue === '') { - return trustedValue; - } - // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting - // mutable objects, we ensure here that the value passed in is actually a string. - if (typeof trustedValue !== 'string') { - throw $sceMinErr('itype', - 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', - type); - } - return new Constructor(trustedValue); - } - - /** - * @ngdoc method - * @name $sceDelegate#valueOf - * - * @description - * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link - * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. - * - * If the passed parameter is not a value that had been returned by {@link - * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. - * - * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} - * call or anything else. - * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns - * `value` unchanged. - */ - function valueOf(maybeTrusted) { - if (maybeTrusted instanceof trustedValueHolderBase) { - return maybeTrusted.$$unwrapTrustedValue(); - } else { - return maybeTrusted; - } - } - - /** - * @ngdoc method - * @name $sceDelegate#getTrusted - * - * @description - * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and - * returns the originally supplied value if the queried context type is a supertype of the - * created type. If this condition isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} call. - * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. - */ - function getTrusted(type, maybeTrusted) { - if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { - return maybeTrusted; - } - var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - if (constructor && maybeTrusted instanceof constructor) { - return maybeTrusted.$$unwrapTrustedValue(); - } - // If we get here, then we may only take one of two actions. - // 1. sanitize the value for the requested type, or - // 2. throw an exception. - if (type === SCE_CONTEXTS.RESOURCE_URL) { - if (isResourceUrlAllowedByPolicy(maybeTrusted)) { - return maybeTrusted; - } else { - throw $sceMinErr('insecurl', - 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', - maybeTrusted.toString()); - } - } else if (type === SCE_CONTEXTS.HTML) { - return htmlSanitizer(maybeTrusted); - } - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); - } + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlBlacklist + * @kind function + * + * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * The typical usage for the blacklist is to **block + * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as + * these would otherwise be trusted but actually return content from the redirected domain. + * + * Finally, **the blacklist overrides the whitelist** and has the final say. + * + * @return {Array} the currently set blacklist array. + * + * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there + * is no blacklist.) + * + * @description + * Sets/Gets the blacklist of trusted resource URLs. + */ - return { trustAs: trustAs, - getTrusted: getTrusted, - valueOf: valueOf }; - }]; -} + this.resourceUrlBlacklist = function (value) { + if (arguments.length) { + resourceUrlBlacklist = adjustMatchers(value); + } + return resourceUrlBlacklist; + }; + this.$get = ['$injector', function ($injector) { -/** - * @ngdoc provider - * @name $sceProvider - * @description - * - * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. - * - enable/disable Strict Contextual Escaping (SCE) in a module - * - override the default implementation with a custom delegate - * - * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. - */ + var htmlSanitizer = function htmlSanitizer(html) { + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + }; -/* jshint maxlen: false*/ + if ($injector.has('$sanitize')) { + htmlSanitizer = $injector.get('$sanitize'); + } -/** - * @ngdoc service - * @name $sce - * @kind function - * - * @description - * - * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. - * - * # Strict Contextual Escaping - * - * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain - * contexts to result in a value that is marked as safe to use for that context. One example of - * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer - * to these contexts as privileged or SCE contexts. - * - * As of version 1.2, Angular ships with SCE enabled by default. - * - * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow - * one to execute arbitrary javascript by the use of the expression() syntax. Refer - * to learn more about them. - * You can ensure your document is in standards mode and not quirks mode by adding `` - * to the top of your HTML document. - * - * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for - * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. - * - * Here's an example of a binding in a privileged context: - * - * ``` - * - *
          - * ``` - * - * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE - * disabled, this application allows the user to render arbitrary HTML into the DIV. - * In a more realistic example, one may be rendering user comments, blog articles, etc. via - * bindings. (HTML is just one example of a context where rendering user controlled input creates - * security vulnerabilities.) - * - * For the case of HTML, you might use a library, either on the client side, or on the server side, - * to sanitize unsafe HTML before binding to the value and rendering it in the document. - * - * How would you ensure that every place that used these types of bindings was bound to a value that - * was sanitized by your library (or returned as safe for rendering by your server?) How can you - * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some - * properties/fields and forgot to update the binding to the sanitized value? - * - * To be secure by default, you want to ensure that any such bindings are disallowed unless you can - * determine that something explicitly says it's safe to use a value for binding in that - * context. You can then audit your code (a simple grep would do) to ensure that this is only done - * for those values that you can easily tell are safe - because they were received from your server, - * sanitized by your library, etc. You can organize your codebase to help with this - perhaps - * allowing only the files in a specific directory to do this. Ensuring that the internal API - * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. - * - * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} - * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to - * obtain values that will be accepted by SCE / privileged contexts. - * - * - * ## How does it work? - * - * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted - * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link - * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the - * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. - * - * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link - * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly - * simplified): - * - * ``` - * var ngBindHtmlDirective = ['$sce', function($sce) { - * return function(scope, element, attr) { - * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { - * element.html(value || ''); - * }); - * }; - * }]; - * ``` - * - * ## Impact on loading templates - * - * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as - * `templateUrl`'s specified by {@link guide/directive directives}. - * - * By default, Angular only loads templates from the same domain and protocol as the application - * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or - * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist - * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. - * - * *Please note*: - * The browser's - * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) - * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) - * policy apply in addition to this and may further restrict whether the template is successfully - * loaded. This means that without the right CORS policy, loading templates from a different domain - * won't work on all browsers. Also, loading templates from `file://` URL does not work on some - * browsers. - * - * ## This feels like too much overhead - * - * It's important to remember that SCE only applies to interpolation expressions. - * - * If your expressions are constant literals, they're automatically trusted and you don't need to - * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. - * `
          `) just works. - * - * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them - * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. - * - * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load - * templates in `ng-include` from your application's domain without having to even know about SCE. - * It blocks loading templates from other domains or loading templates over http from an https - * served document. You can change these by setting your own custom {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. - * - * This significantly reduces the overhead. It is far easier to pay the small overhead and have an - * application that's secure and can be audited to verify that with much more ease than bolting - * security onto an application later. - * - * - * ## What trusted context types are supported? - * - * | Context | Notes | - * |---------------------|----------------| - * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | - * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | - * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
          Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | - * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | - * - * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
          - * - * Each element in these arrays must be one of the following: - * - * - **'self'** - * - The special **string**, `'self'`, can be used to match against all URLs of the **same - * domain** as the application document using the **same protocol**. - * - **String** (except the special value `'self'`) - * - The string is matched against the full *normalized / absolute URL* of the resource - * being tested (substring matches are not good enough.) - * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters - * match themselves. - * - `*`: matches zero or more occurrences of any character other than one of the following 6 - * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use - * in a whitelist. - * - `**`: matches zero or more occurrences of *any* character. As such, it's not - * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. - * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might - * not have been the intention.) Its usage at the very end of the path is ok. (e.g. - * http://foo.example.com/templates/**). - * - **RegExp** (*see caveat below*) - * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax - * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to - * accidentally introduce a bug when one updates a complex expression (imho, all regexes should - * have good test coverage.). For instance, the use of `.` in the regex is correct only in a - * small number of cases. A `.` character in the regex used when matching the scheme or a - * subdomain could be matched against a `:` or literal `.` that was likely not intended. It - * is highly recommended to use the string patterns and only fall back to regular expressions - * if they as a last resort. - * - The regular expression must be an instance of RegExp (i.e. not a string.) It is - * matched against the **entire** *normalized / absolute URL* of the resource being tested - * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags - * present on the RegExp (such as multiline, global, ignoreCase) are ignored. - * - If you are generating your JavaScript from some other templating engine (not - * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), - * remember to escape your regular expression (and be aware that you might need more than - * one level of escaping depending on your templating engine and the way you interpolated - * the value.) Do make use of your platform's escaping mechanism as it might be good - * enough before coding your own. e.g. Ruby has - * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) - * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). - * Javascript lacks a similar built in function for escaping. Take a look at Google - * Closure library's [goog.string.regExpEscape(s)]( - * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). - * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. - * - * ## Show me an example using SCE. - * - * - * - *
          - *

          - * User comments
          - * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when - * $sanitize is available. If $sanitize isn't available, this results in an error instead of an - * exploit. - *
          - *
          - * {{userComment.name}}: - * - *
          - *
          - *
          - *
          - *
          - * - * - * angular.module('mySceApp', ['ngSanitize']) - * .controller('AppController', ['$http', '$templateCache', '$sce', - * function($http, $templateCache, $sce) { - * var self = this; - * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { - * self.userComments = userComments; - * }); - * self.explicitlyTrustedHtml = $sce.trustAsHtml( - * 'Hover over this text.'); - * }]); - * - * - * - * [ - * { "name": "Alice", - * "htmlComment": - * "Is anyone reading this?" - * }, - * { "name": "Bob", - * "htmlComment": "Yes! Am I the only other one?" - * } - * ] - * - * - * - * describe('SCE doc demo', function() { - * it('should sanitize untrusted values', function() { - * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) - * .toBe('Is anyone reading this?'); - * }); - * - * it('should NOT sanitize explicitly trusted values', function() { - * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( - * 'Hover over this text.'); - * }); - * }); - * - *
          - * - * - * - * ## Can I disable SCE completely? - * - * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits - * for little coding overhead. It will be much harder to take an SCE disabled application and - * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE - * for cases where you have a lot of existing code that was written before SCE was introduced and - * you're migrating them a module at a time. - * - * That said, here's how you can completely disable SCE: - * - * ``` - * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { - * // Completely disable SCE. For demonstration purposes only! - * // Do not use in new projects. - * $sceProvider.enabled(false); - * }); - * ``` - * - */ -/* jshint maxlen: 100 */ -function $SceProvider() { - var enabled = true; + function matchUrl(matcher, parsedUrl) { + if (matcher === 'self') { + return urlIsSameOrigin(parsedUrl); + } else { + // definitely a regex. See adjustMatchers() + return !!matcher.exec(parsedUrl.href); + } + } - /** - * @ngdoc method - * @name $sceProvider#enabled - * @kind function - * - * @param {boolean=} value If provided, then enables/disables SCE. - * @return {boolean} true if SCE is enabled, false otherwise. - * - * @description - * Enables/disables SCE and returns the current value. - */ - this.enabled = function (value) { - if (arguments.length) { - enabled = !!value; - } - return enabled; - }; + function isResourceUrlAllowedByPolicy(url) { + var parsedUrl = urlResolve(url.toString()); + var i, n, allowed = false; + // Ensure that at least one item from the whitelist allows this url. + for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { + if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { + allowed = true; + break; + } + } + if (allowed) { + // Ensure that no item from the blacklist blocked this url. + for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { + if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { + allowed = false; + break; + } + } + } + return allowed; + } + + function generateHolderType(Base) { + var holderType = function TrustedValueHolderType(trustedValue) { + this.$$unwrapTrustedValue = function () { + return trustedValue; + }; + }; + if (Base) { + holderType.prototype = new Base(); + } + holderType.prototype.valueOf = function sceValueOf() { + return this.$$unwrapTrustedValue(); + }; + holderType.prototype.toString = function sceToString() { + return this.$$unwrapTrustedValue().toString(); + }; + return holderType; + } + var trustedValueHolderBase = generateHolderType(), + byType = {}; + + byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + + /** + * @ngdoc method + * @name $sceDelegate#trustAs + * + * @description + * Returns an object that is trusted by angular for use in specified strict + * contextual escaping contexts (such as ng-bind-html, ng-include, any src + * attribute interpolation, any dom event binding attribute interpolation + * such as for onclick, etc.) that uses the provided value. + * See {@link ng.$sce $sce} for enabling strict contextual escaping. + * + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resourceUrl, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + function trustAs(type, trustedValue) { + var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (!Constructor) { + throw $sceMinErr('icontext', + 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', + type, trustedValue); + } + if (trustedValue === null || trustedValue === undefined || trustedValue === '') { + return trustedValue; + } + // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting + // mutable objects, we ensure here that the value passed in is actually a string. + if (typeof trustedValue !== 'string') { + throw $sceMinErr('itype', + 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', + type); + } + return new Constructor(trustedValue); + } - /* Design notes on the default implementation for SCE. - * - * The API contract for the SCE delegate - * ------------------------------------- - * The SCE delegate object must provide the following 3 methods: - * - * - trustAs(contextEnum, value) - * This method is used to tell the SCE service that the provided value is OK to use in the - * contexts specified by contextEnum. It must return an object that will be accepted by - * getTrusted() for a compatible contextEnum and return this value. - * - * - valueOf(value) - * For values that were not produced by trustAs(), return them as is. For values that were - * produced by trustAs(), return the corresponding input value to trustAs. Basically, if - * trustAs is wrapping the given values into some type, this operation unwraps it when given - * such a value. - * - * - getTrusted(contextEnum, value) - * This function should return the a value that is safe to use in the context specified by - * contextEnum or throw and exception otherwise. - * - * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be - * opaque or wrapped in some holder object. That happens to be an implementation detail. For - * instance, an implementation could maintain a registry of all trusted objects by context. In - * such a case, trustAs() would return the same object that was passed in. getTrusted() would - * return the same object passed in if it was found in the registry under a compatible context or - * throw an exception otherwise. An implementation might only wrap values some of the time based - * on some criteria. getTrusted() might return a value and not throw an exception for special - * constants or objects even if not wrapped. All such implementations fulfill this contract. - * - * - * A note on the inheritance model for SCE contexts - * ------------------------------------------------ - * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This - * is purely an implementation details. - * - * The contract is simply this: - * - * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) - * will also succeed. - * - * Inheritance happens to capture this in a natural way. In some future, we - * may not use inheritance anymore. That is OK because no code outside of - * sce.js and sceSpecs.js would need to be aware of this detail. - */ - - this.$get = ['$document', '$parse', '$sceDelegate', function( - $document, $parse, $sceDelegate) { - // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow - // the "expression(javascript expression)" syntax which is insecure. - if (enabled && $document[0].documentMode < 8) { - throw $sceMinErr('iequirks', - 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + - 'mode. You can fix this by adding the text to the top of your HTML ' + - 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + /** + * @ngdoc method + * @name $sceDelegate#valueOf + * + * @description + * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. + * + * If the passed parameter is not a value that had been returned by {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. + * + * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} + * call or anything else. + * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns + * `value` unchanged. + */ + function valueOf(maybeTrusted) { + if (maybeTrusted instanceof trustedValueHolderBase) { + return maybeTrusted.$$unwrapTrustedValue(); + } else { + return maybeTrusted; + } + } + + /** + * @ngdoc method + * @name $sceDelegate#getTrusted + * + * @description + * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and + * returns the originally supplied value if the queried context type is a supertype of the + * created type. If this condition isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} call. + * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. + */ + function getTrusted(type, maybeTrusted) { + if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { + return maybeTrusted; + } + var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (constructor && maybeTrusted instanceof constructor) { + return maybeTrusted.$$unwrapTrustedValue(); + } + // If we get here, then we may only take one of two actions. + // 1. sanitize the value for the requested type, or + // 2. throw an exception. + if (type === SCE_CONTEXTS.RESOURCE_URL) { + if (isResourceUrlAllowedByPolicy(maybeTrusted)) { + return maybeTrusted; + } else { + throw $sceMinErr('insecurl', + 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', + maybeTrusted.toString()); + } + } else if (type === SCE_CONTEXTS.HTML) { + return htmlSanitizer(maybeTrusted); + } + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + } + + return { + trustAs: trustAs, + getTrusted: getTrusted, + valueOf: valueOf + }; + }]; } - var sce = shallowCopy(SCE_CONTEXTS); /** - * @ngdoc method - * @name $sce#isEnabled - * @kind function + * @ngdoc provider + * @name $sceProvider + * @description * - * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you - * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. + * - enable/disable Strict Contextual Escaping (SCE) in a module + * - override the default implementation with a custom delegate * - * @description - * Returns a boolean indicating if SCE is enabled. + * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. */ - sce.isEnabled = function () { - return enabled; - }; - sce.trustAs = $sceDelegate.trustAs; - sce.getTrusted = $sceDelegate.getTrusted; - sce.valueOf = $sceDelegate.valueOf; - if (!enabled) { - sce.trustAs = sce.getTrusted = function(type, value) { return value; }; - sce.valueOf = identity; - } + /* jshint maxlen: false*/ /** - * @ngdoc method - * @name $sce#parseAs + * @ngdoc service + * @name $sce + * @kind function * * @description - * Converts Angular {@link guide/expression expression} into a function. This is like {@link - * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it - * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, - * *result*)} * - * @param {string} type The kind of SCE context in which this result will be used. - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - sce.parseAs = function sceParseAs(type, expr) { - var parsed = $parse(expr); - if (parsed.literal && parsed.constant) { - return parsed; - } else { - return $parse(expr, function (value) { - return sce.getTrusted(type, value); - }); - } - }; - - /** - * @ngdoc method - * @name $sce#trustAs + * # Strict Contextual Escaping * - * @description - * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, - * returns an object that is trusted by angular for use in specified strict contextual - * escaping contexts (such as ng-bind-html, ng-include, any src attribute - * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) - * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual - * escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resource_url, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. - */ - - /** - * @ngdoc method - * @name $sce#trustAsHtml + * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain + * contexts to result in a value that is marked as safe to use for that context. One example of + * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer + * to these contexts as privileged or SCE contexts. * - * @description - * Shorthand method. `$sce.trustAsHtml(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * As of version 1.2, Angular ships with SCE enabled by default. * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml - * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsUrl + * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow + * one to execute arbitrary javascript by the use of the expression() syntax. Refer + * to learn more about them. + * You can ensure your document is in standards mode and not quirks mode by adding `` + * to the top of your HTML document. * - * @description - * Shorthand method. `$sce.trustAsUrl(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} + * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for + * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl - * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsResourceUrl + * Here's an example of a binding in a privileged context: * - * @description - * Shorthand method. `$sce.trustAsResourceUrl(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * ``` + * + *
          + * ``` * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the return - * value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#trustAsJs + * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE + * disabled, this application allows the user to render arbitrary HTML into the DIV. + * In a more realistic example, one may be rendering user comments, blog articles, etc. via + * bindings. (HTML is just one example of a context where rendering user controlled input creates + * security vulnerabilities.) * - * @description - * Shorthand method. `$sce.trustAsJs(value)` → - * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * For the case of HTML, you might use a library, either on the client side, or on the server side, + * to sanitize unsafe HTML before binding to the value and rendering it in the document. * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs - * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) - */ - - /** - * @ngdoc method - * @name $sce#getTrusted + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some + * properties/fields and forgot to update the binding to the sanitized value? * - * @description - * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, - * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the - * originally supplied value if the queried context type is a supertype of the created type. - * If this condition isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} - * call. - * @returns {*} The value the was originally provided to - * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. - * Otherwise, throws an exception. - */ - - /** - * @ngdoc method - * @name $sce#getTrustedHtml + * To be secure by default, you want to ensure that any such bindings are disallowed unless you can + * determine that something explicitly says it's safe to use a value for binding in that + * context. You can then audit your code (a simple grep would do) to ensure that this is only done + * for those values that you can easily tell are safe - because they were received from your server, + * sanitized by your library, etc. You can organize your codebase to help with this - perhaps + * allowing only the files in a specific directory to do this. Ensuring that the internal API + * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. * - * @description - * Shorthand method. `$sce.getTrustedHtml(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} + * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to + * obtain values that will be accepted by SCE / privileged contexts. * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedCss * - * @description - * Shorthand method. `$sce.getTrustedCss(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * ## How does it work? * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedUrl + * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted + * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link + * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the + * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. * - * @description - * Shorthand method. `$sce.getTrustedUrl(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link + * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly + * simplified): * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedResourceUrl + * ``` + * var ngBindHtmlDirective = ['$sce', function($sce) { + * return function(scope, element, attr) { + * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { + * element.html(value || ''); + * }); + * }; + * }]; + * ``` * - * @description - * Shorthand method. `$sce.getTrustedResourceUrl(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * ## Impact on loading templates * - * @param {*} value The value to pass to `$sceDelegate.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` - */ - - /** - * @ngdoc method - * @name $sce#getTrustedJs + * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as + * `templateUrl`'s specified by {@link guide/directive directives}. * - * @description - * Shorthand method. `$sce.getTrustedJs(value)` → - * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * By default, Angular only loads templates from the same domain and protocol as the application + * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or + * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist + * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. * - * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` - */ - - /** - * @ngdoc method - * @name $sce#parseAsHtml + * *Please note*: + * The browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. * - * @description - * Shorthand method. `$sce.parseAsHtml(expression string)` → - * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} + * ## This feels like too much overhead * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * It's important to remember that SCE only applies to interpolation expressions. * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name $sce#parseAsCss + * If your expressions are constant literals, they're automatically trusted and you don't need to + * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. + * `
          `) just works. * - * @description - * Shorthand method. `$sce.parseAsCss(value)` → - * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} + * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them + * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load + * templates in `ng-include` from your application's domain without having to even know about SCE. + * It blocks loading templates from other domains or loading templates over http from an https + * served document. You can change these by setting your own custom {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name $sce#parseAsUrl + * This significantly reduces the overhead. It is far easier to pay the small overhead and have an + * application that's secure and can be audited to verify that with much more ease than bolting + * security onto an application later. * - * @description - * Shorthand method. `$sce.parseAsUrl(value)` → - * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} + * + * ## What trusted context types are supported? * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * | Context | Notes | + * |---------------------|----------------| + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | + * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | + * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
          Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name $sce#parseAsResourceUrl + * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
          * - * @description - * Shorthand method. `$sce.parseAsResourceUrl(value)` → - * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} + * Each element in these arrays must be one of the following: * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * - **'self'** + * - The special **string**, `'self'`, can be used to match against all URLs of the **same + * domain** as the application document using the **same protocol**. + * - **String** (except the special value `'self'`) + * - The string is matched against the full *normalized / absolute URL* of the resource + * being tested (substring matches are not good enough.) + * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters + * match themselves. + * - `*`: matches zero or more occurrences of any character other than one of the following 6 + * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use + * in a whitelist. + * - `**`: matches zero or more occurrences of *any* character. As such, it's not + * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. + * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might + * not have been the intention.) Its usage at the very end of the path is ok. (e.g. + * http://foo.example.com/templates/**). + * - **RegExp** (*see caveat below*) + * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax + * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to + * accidentally introduce a bug when one updates a complex expression (imho, all regexes should + * have good test coverage.). For instance, the use of `.` in the regex is correct only in a + * small number of cases. A `.` character in the regex used when matching the scheme or a + * subdomain could be matched against a `:` or literal `.` that was likely not intended. It + * is highly recommended to use the string patterns and only fall back to regular expressions + * if they as a last resort. + * - The regular expression must be an instance of RegExp (i.e. not a string.) It is + * matched against the **entire** *normalized / absolute URL* of the resource being tested + * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags + * present on the RegExp (such as multiline, global, ignoreCase) are ignored. + * - If you are generating your JavaScript from some other templating engine (not + * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), + * remember to escape your regular expression (and be aware that you might need more than + * one level of escaping depending on your templating engine and the way you interpolated + * the value.) Do make use of your platform's escaping mechanism as it might be good + * enough before coding your own. e.g. Ruby has + * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) + * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). + * Javascript lacks a similar built in function for escaping. Take a look at Google + * Closure library's [goog.string.regExpEscape(s)]( + * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - /** - * @ngdoc method - * @name $sce#parseAsJs + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. * - * @description - * Shorthand method. `$sce.parseAsJs(value)` → - * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} + * ## Show me an example using SCE. * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * + * + *
          + *

          + * User comments
          + * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when + * $sanitize is available. If $sanitize isn't available, this results in an error instead of an + * exploit. + *
          + *
          + * {{userComment.name}}: + * + *
          + *
          + *
          + *
          + *
          * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - */ - - // Shorthand delegations. - var parse = sce.parseAs, - getTrusted = sce.getTrusted, - trustAs = sce.trustAs; - - forEach(SCE_CONTEXTS, function (enumValue, name) { - var lName = lowercase(name); - sce[camelCase("parse_as_" + lName)] = function (expr) { - return parse(enumValue, expr); - }; - sce[camelCase("get_trusted_" + lName)] = function (value) { - return getTrusted(enumValue, value); - }; - sce[camelCase("trust_as_" + lName)] = function (value) { - return trustAs(enumValue, value); - }; - }); - - return sce; - }]; -} - -/** - * !!! This is an undocumented "private" service !!! - * - * @name $sniffer - * @requires $window - * @requires $document - * - * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} transitions Does the browser support CSS transition events ? - * @property {boolean} animations Does the browser support CSS animation events ? + * + * angular.module('mySceApp', ['ngSanitize']) + * .controller('AppController', ['$http', '$templateCache', '$sce', + * function($http, $templateCache, $sce) { + * var self = this; + * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { + * self.userComments = userComments; + * }); + * self.explicitlyTrustedHtml = $sce.trustAsHtml( + * 'Hover over this text.'); + * }]); + * + * + * + * [ + * { "name": "Alice", + * "htmlComment": + * "Is anyone reading this?" + * }, + * { "name": "Bob", + * "htmlComment": "Yes! Am I the only other one?" + * } + * ] + * + * + * + * describe('SCE doc demo', function() { + * it('should sanitize untrusted values', function() { + * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) + * .toBe('Is anyone reading this?'); + * }); * - * @description - * This is very simple implementation of testing browser's features. - */ -function $SnifferProvider() { - this.$get = ['$window', '$document', function($window, $document) { - var eventSupport = {}, - android = - int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), - boxee = /Boxee/i.test(($window.navigator || {}).userAgent), - document = $document[0] || {}, - vendorPrefix, - vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, - bodyStyle = document.body && document.body.style, - transitions = false, - animations = false, - match; - - if (bodyStyle) { - for(var prop in bodyStyle) { - if(match = vendorRegex.exec(prop)) { - vendorPrefix = match[0]; - vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); - break; - } - } + * it('should NOT sanitize explicitly trusted values', function() { + * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( + * 'Hover over this text.'); + * }); + * }); + * + *
          + * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * for little coding overhead. It will be much harder to take an SCE disabled application and + * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE + * for cases where you have a lot of existing code that was written before SCE was introduced and + * you're migrating them a module at a time. + * + * That said, here's how you can completely disable SCE: + * + * ``` + * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { + * // Completely disable SCE. For demonstration purposes only! + * // Do not use in new projects. + * $sceProvider.enabled(false); + * }); + * ``` + * + */ + /* jshint maxlen: 100 */ - if(!vendorPrefix) { - vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; - } + function $SceProvider() { + var enabled = true; - transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); - animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); + /** + * @ngdoc method + * @name $sceProvider#enabled + * @kind function + * + * @param {boolean=} value If provided, then enables/disables SCE. + * @return {boolean} true if SCE is enabled, false otherwise. + * + * @description + * Enables/disables SCE and returns the current value. + */ + this.enabled = function (value) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; - if (android && (!transitions||!animations)) { - transitions = isString(document.body.style.webkitTransition); - animations = isString(document.body.style.webkitAnimation); - } - } + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * This function should return the a value that is safe to use in the context specified by + * contextEnum or throw and exception otherwise. + * + * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be + * opaque or wrapped in some holder object. That happens to be an implementation detail. For + * instance, an implementation could maintain a registry of all trusted objects by context. In + * such a case, trustAs() would return the same object that was passed in. getTrusted() would + * return the same object passed in if it was found in the registry under a compatible context or + * throw an exception otherwise. An implementation might only wrap values some of the time based + * on some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) + * will also succeed. + * + * Inheritance happens to capture this in a natural way. In some future, we + * may not use inheritance anymore. That is OK because no code outside of + * sce.js and sceSpecs.js would need to be aware of this detail. + */ - return { - // Android has history.pushState, but it does not update location correctly - // so let's not use the history API at all. - // http://code.google.com/p/android/issues/detail?id=17471 - // https://github.com/angular/angular.js/issues/904 - - // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has - // so let's not use the history API also - // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined - // jshint -W018 - history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), - // jshint +W018 - hasEvent: function(event) { - // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have - // it. In particular the event is not fired when backspace or delete key are pressed or - // when cut operation is performed. - if (event == 'input' && msie == 9) return false; - - if (isUndefined(eventSupport[event])) { - var divElm = document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } + this.$get = ['$document', '$parse', '$sceDelegate', function ($document, $parse, $sceDelegate) { + // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow + // the "expression(javascript expression)" syntax which is insecure. + if (enabled && $document[0].documentMode < 8) { + throw $sceMinErr('iequirks', + 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + + 'mode. You can fix this by adding the text to the top of your HTML ' + + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + } - return eventSupport[event]; - }, - csp: csp(), - vendorPrefix: vendorPrefix, - transitions : transitions, - animations : animations, - android: android - }; - }]; -} + var sce = shallowCopy(SCE_CONTEXTS); + + /** + * @ngdoc method + * @name $sce#isEnabled + * @kind function + * + * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * + * @description + * Returns a boolean indicating if SCE is enabled. + */ + sce.isEnabled = function () { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; -var $compileMinErr = minErr('$compile'); + if (!enabled) { + sce.trustAs = sce.getTrusted = function (type, value) { + return value; + }; + sce.valueOf = identity; + } -/** - * @ngdoc service - * @name $templateRequest - * - * @description - * The `$templateRequest` service downloads the provided template using `$http` and, upon success, - * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data - * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted - * by setting the 2nd parameter of the function to true). - * - * @param {string} tpl The HTTP request template URL - * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty - * - * @return {Promise} the HTTP Promise for the given. - * - * @property {number} totalPendingRequests total amount of pending template requests being downloaded. - */ -function $TemplateRequestProvider() { - this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) { - function handleRequestFn(tpl, ignoreRequestError) { - var self = handleRequestFn; - self.totalPendingRequests++; - - return $http.get(tpl, { cache : $templateCache }) - .then(function(response) { - var html = response.data; - if(!html || html.length === 0) { - return handleError(); - } + /** + * @ngdoc method + * @name $sce#parseAs + * + * @description + * Converts Angular {@link guide/expression expression} into a function. This is like {@link + * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it + * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, + * *result*)} + * + * @param {string} type The kind of SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return $parse(expr, function (value) { + return sce.getTrusted(type, value); + }); + } + }; - self.totalPendingRequests--; - $templateCache.put(tpl, html); - return html; - }, handleError); + /** + * @ngdoc method + * @name $sce#trustAs + * + * @description + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, + * returns an object that is trusted by angular for use in specified strict contextual + * escaping contexts (such as ng-bind-html, ng-include, any src attribute + * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) + * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual + * escaping. + * + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resource_url, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + + /** + * @ngdoc method + * @name $sce#trustAsHtml + * + * @description + * Shorthand method. `$sce.trustAsHtml(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml + * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsUrl + * + * @description + * Shorthand method. `$sce.trustAsUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl + * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsResourceUrl + * + * @description + * Shorthand method. `$sce.trustAsResourceUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the return + * value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsJs + * + * @description + * Shorthand method. `$sce.trustAsJs(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs + * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#getTrusted + * + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, + * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the + * originally supplied value if the queried context type is a supertype of the created type. + * If this condition isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} + * call. + * @returns {*} The value the was originally provided to + * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. + * Otherwise, throws an exception. + */ + + /** + * @ngdoc method + * @name $sce#getTrustedHtml + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedCss + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedUrl + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedResourceUrl + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedJs + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ + + /** + * @ngdoc method + * @name $sce#parseAsHtml + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsCss + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsUrl + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsResourceUrl + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsJs + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; + + forEach(SCE_CONTEXTS, function (enumValue, name) { + var lName = lowercase(name); + sce[camelCase("parse_as_" + lName)] = function (expr) { + return parse(enumValue, expr); + }; + sce[camelCase("get_trusted_" + lName)] = function (value) { + return getTrusted(enumValue, value); + }; + sce[camelCase("trust_as_" + lName)] = function (value) { + return trustAs(enumValue, value); + }; + }); - function handleError() { - self.totalPendingRequests--; - if (!ignoreRequestError) { - throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl); - } - return $q.reject(); - } + return sce; + }]; } - handleRequestFn.totalPendingRequests = 0; - - return handleRequestFn; - }]; -} - -function $$TestabilityProvider() { - this.$get = ['$rootScope', '$browser', '$location', - function($rootScope, $browser, $location) { - /** - * @name $testability + * !!! This is an undocumented "private" service !!! * - * @description - * The private $$testability service provides a collection of methods for use when debugging - * or by automated test and debugging tools. - */ - var testability = {}; - - /** - * @name $$testability#findBindings + * @name $sniffer + * @requires $window + * @requires $document * - * @description - * Returns an array of elements that are bound (via ng-bind or {{}}) - * to expressions matching the input. + * @property {boolean} history Does the browser support html5 history api ? + * @property {boolean} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? * - * @param {Element} element The element root to search from. - * @param {string} expression The binding expression to match. - * @param {boolean} opt_exactMatch If true, only returns exact matches - * for the expression. Filters and whitespace are ignored. + * @description + * This is very simple implementation of testing browser's features. */ - testability.findBindings = function(element, expression, opt_exactMatch) { - var bindings = element.getElementsByClassName('ng-binding'); - var matches = []; - forEach(bindings, function(binding) { - var dataBinding = angular.element(binding).data('$binding'); - if (dataBinding) { - forEach(dataBinding, function(bindingName) { - if (opt_exactMatch) { - var matcher = new RegExp('(^|\\s)' + expression + '(\\s|\\||$)'); - if (matcher.test(bindingName)) { - matches.push(binding); - } - } else { - if (bindingName.indexOf(expression) != -1) { - matches.push(binding); - } + function $SnifferProvider() { + this.$get = ['$window', '$document', function ($window, $document) { + var eventSupport = {}, + android = + int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + boxee = /Boxee/i.test(($window.navigator || {}).userAgent), + document = $document[0] || {}, + vendorPrefix, + vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false, + match; + + if (bodyStyle) { + for (var prop in bodyStyle) { + if (match = vendorRegex.exec(prop)) { + vendorPrefix = match[0]; + vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); + break; + } + } + + if (!vendorPrefix) { + vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; + } + + transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); + animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); + + if (android && (!transitions || !animations)) { + transitions = isString(document.body.style.webkitTransition); + animations = isString(document.body.style.webkitAnimation); + } } - }); - } - }); - return matches; - }; - /** - * @name $$testability#findModels - * - * @description - * Returns an array of elements that are two-way found via ng-model to - * expressions matching the input. - * - * @param {Element} element The element root to search from. - * @param {string} expression The model expression to match. - * @param {boolean} opt_exactMatch If true, only returns exact matches - * for the expression. - */ - testability.findModels = function(element, expression, opt_exactMatch) { - var prefixes = ['ng-', 'data-ng-', 'ng\\:']; - for (var p = 0; p < prefixes.length; ++p) { - var attributeEquals = opt_exactMatch ? '=' : '*='; - var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; - var elements = element.querySelectorAll(selector); - if (elements.length) { - return elements; - } - } - }; - /** - * @name $$testability#getLocation - * - * @description - * Shortcut for getting the location in a browser agnostic way. Returns - * the path, search, and hash. (e.g. /path?a=b#hash) - */ - testability.getLocation = function() { - return $location.url(); - }; + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 + + // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has + // so let's not use the history API also + // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined + // jshint -W018 + history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), + // jshint +W018 + hasEvent: function (event) { + // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have + // it. In particular the event is not fired when backspace or delete key are pressed or + // when cut operation is performed. + if (event == 'input' && msie == 9) return false; + + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; + } + + return eventSupport[event]; + }, + csp: csp(), + vendorPrefix: vendorPrefix, + transitions: transitions, + animations: animations, + android: android + }; + }]; + } + + var $compileMinErr = minErr('$compile'); /** - * @name $$testability#setLocation + * @ngdoc service + * @name $templateRequest * * @description - * Shortcut for navigating to a location without doing a full page reload. + * The `$templateRequest` service downloads the provided template using `$http` and, upon success, + * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data + * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted + * by setting the 2nd parameter of the function to true). * - * @param {string} url The location url (path, search and hash, - * e.g. /path?a=b#hash) to go to. - */ - testability.setLocation = function(url) { - if (url !== $location.url()) { - $location.url(url); - $rootScope.$digest(); - } - }; - - /** - * @name $$testability#whenStable + * @param {string} tpl The HTTP request template URL + * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty * - * @description - * Calls the callback when $timeout and $http requests are completed. + * @return {Promise} the HTTP Promise for the given. * - * @param {function} callback + * @property {number} totalPendingRequests total amount of pending template requests being downloaded. */ - testability.whenStable = function(callback) { - $browser.notifyWhenNoOutstandingRequests(callback); - }; - - return testability; - }]; -} + function $TemplateRequestProvider() { + this.$get = ['$templateCache', '$http', '$q', function ($templateCache, $http, $q) { + function handleRequestFn(tpl, ignoreRequestError) { + var self = handleRequestFn; + self.totalPendingRequests++; + + return $http.get(tpl, {cache: $templateCache}) + .then(function (response) { + var html = response.data; + if (!html || html.length === 0) { + return handleError(); + } + + self.totalPendingRequests--; + $templateCache.put(tpl, html); + return html; + }, handleError); + + function handleError() { + self.totalPendingRequests--; + if (!ignoreRequestError) { + throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl); + } + return $q.reject(); + } + } -function $TimeoutProvider() { - this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', - function($rootScope, $browser, $q, $$q, $exceptionHandler) { - var deferreds = {}; + handleRequestFn.totalPendingRequests = 0; + + return handleRequestFn; + }]; + } + + function $$TestabilityProvider() { + this.$get = ['$rootScope', '$browser', '$location', + function ($rootScope, $browser, $location) { + + /** + * @name $testability + * + * @description + * The private $$testability service provides a collection of methods for use when debugging + * or by automated test and debugging tools. + */ + var testability = {}; + + /** + * @name $$testability#findBindings + * + * @description + * Returns an array of elements that are bound (via ng-bind or {{}}) + * to expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The binding expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. Filters and whitespace are ignored. + */ + testability.findBindings = function (element, expression, opt_exactMatch) { + var bindings = element.getElementsByClassName('ng-binding'); + var matches = []; + forEach(bindings, function (binding) { + var dataBinding = angular.element(binding).data('$binding'); + if (dataBinding) { + forEach(dataBinding, function (bindingName) { + if (opt_exactMatch) { + var matcher = new RegExp('(^|\\s)' + expression + '(\\s|\\||$)'); + if (matcher.test(bindingName)) { + matches.push(binding); + } + } else { + if (bindingName.indexOf(expression) != -1) { + matches.push(binding); + } + } + }); + } + }); + return matches; + }; + /** + * @name $$testability#findModels + * + * @description + * Returns an array of elements that are two-way found via ng-model to + * expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The model expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. + */ + testability.findModels = function (element, expression, opt_exactMatch) { + var prefixes = ['ng-', 'data-ng-', 'ng\\:']; + for (var p = 0; p < prefixes.length; ++p) { + var attributeEquals = opt_exactMatch ? '=' : '*='; + var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; + var elements = element.querySelectorAll(selector); + if (elements.length) { + return elements; + } + } + }; - /** - * @ngdoc service - * @name $timeout - * - * @description - * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch - * block and delegates any exceptions to - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * The return value of registering a timeout function is a promise, which will be resolved when - * the timeout is reached and the timeout function is executed. - * - * To cancel a timeout request, call `$timeout.cancel(promise)`. - * - * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to - * synchronously flush the queue of deferred functions. - * - * @param {function()} fn A function, whose execution should be delayed. - * @param {number=} [delay=0] Delay in milliseconds. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this - * promise will be resolved with is the return value of the `fn` function. - * - */ - function timeout(fn, delay, invokeApply) { - var skipApply = (isDefined(invokeApply) && !invokeApply), - deferred = (skipApply ? $$q : $q).defer(), - promise = deferred.promise, - timeoutId; - - timeoutId = $browser.defer(function() { - try { - deferred.resolve(fn()); - } catch(e) { - deferred.reject(e); - $exceptionHandler(e); - } - finally { - delete deferreds[promise.$$timeoutId]; - } + /** + * @name $$testability#getLocation + * + * @description + * Shortcut for getting the location in a browser agnostic way. Returns + * the path, search, and hash. (e.g. /path?a=b#hash) + */ + testability.getLocation = function () { + return $location.url(); + }; - if (!skipApply) $rootScope.$apply(); - }, delay); + /** + * @name $$testability#setLocation + * + * @description + * Shortcut for navigating to a location without doing a full page reload. + * + * @param {string} url The location url (path, search and hash, + * e.g. /path?a=b#hash) to go to. + */ + testability.setLocation = function (url) { + if (url !== $location.url()) { + $location.url(url); + $rootScope.$digest(); + } + }; - promise.$$timeoutId = timeoutId; - deferreds[timeoutId] = deferred; + /** + * @name $$testability#whenStable + * + * @description + * Calls the callback when $timeout and $http requests are completed. + * + * @param {function} callback + */ + testability.whenStable = function (callback) { + $browser.notifyWhenNoOutstandingRequests(callback); + }; - return promise; - } + return testability; + }]; + } + + function $TimeoutProvider() { + this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', + function ($rootScope, $browser, $q, $$q, $exceptionHandler) { + var deferreds = {}; + + + /** + * @ngdoc service + * @name $timeout + * + * @description + * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch + * block and delegates any exceptions to + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * The return value of registering a timeout function is a promise, which will be resolved when + * the timeout is reached and the timeout function is executed. + * + * To cancel a timeout request, call `$timeout.cancel(promise)`. + * + * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to + * synchronously flush the queue of deferred functions. + * + * @param {function()} fn A function, whose execution should be delayed. + * @param {number=} [delay=0] Delay in milliseconds. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this + * promise will be resolved with is the return value of the `fn` function. + * + */ + function timeout(fn, delay, invokeApply) { + var skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise, + timeoutId; + + timeoutId = $browser.defer(function () { + try { + deferred.resolve(fn()); + } catch (e) { + deferred.reject(e); + $exceptionHandler(e); + } + finally { + delete deferreds[promise.$$timeoutId]; + } + + if (!skipApply) $rootScope.$apply(); + }, delay); + + promise.$$timeoutId = timeoutId; + deferreds[timeoutId] = deferred; + + return promise; + } - /** - * @ngdoc method - * @name $timeout#cancel - * - * @description - * Cancels a task associated with the `promise`. As a result of this, the promise will be - * resolved with a rejection. - * - * @param {Promise=} promise Promise returned by the `$timeout` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ - timeout.cancel = function(promise) { - if (promise && promise.$$timeoutId in deferreds) { - deferreds[promise.$$timeoutId].reject('canceled'); - delete deferreds[promise.$$timeoutId]; - return $browser.defer.cancel(promise.$$timeoutId); - } - return false; - }; + /** + * @ngdoc method + * @name $timeout#cancel + * + * @description + * Cancels a task associated with the `promise`. As a result of this, the promise will be + * resolved with a rejection. + * + * @param {Promise=} promise Promise returned by the `$timeout` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + timeout.cancel = function (promise) { + if (promise && promise.$$timeoutId in deferreds) { + deferreds[promise.$$timeoutId].reject('canceled'); + delete deferreds[promise.$$timeoutId]; + return $browser.defer.cancel(promise.$$timeoutId); + } + return false; + }; - return timeout; - }]; -} + return timeout; + }]; + } // NOTE: The usage of window and document instead of $window and $document here is // deliberate. This service depends on the specific behavior of anchor nodes created by the @@ -15987,170 +16106,170 @@ function $TimeoutProvider() { // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. -var urlParsingNode = document.createElement("a"); -var originUrl = urlResolve(window.location.href, true); + var urlParsingNode = document.createElement("a"); + var originUrl = urlResolve(window.location.href, true); -/** - * - * Implementation Notes for non-IE browsers - * ---------------------------------------- - * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, - * results both in the normalizing and parsing of the URL. Normalizing means that a relative - * URL will be resolved into an absolute URL in the context of the application document. - * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related - * properties are all populated to reflect the normalized URL. This approach has wide - * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * - * Implementation Notes for IE - * --------------------------- - * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other - * browsers. However, the parsed components will not be set if the URL assigned did not specify - * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We - * work around that by performing the parsing in a 2nd step by taking a previously normalized - * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the - * properties such as protocol, hostname, port, etc. - * - * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one - * uses the inner HTML approach to assign the URL as part of an HTML snippet - - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. - * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. - * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that - * method and IE < 8 is unsupported. - * - * References: - * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * http://url.spec.whatwg.org/#urlutils - * https://github.com/angular/angular.js/pull/2902 - * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ - * - * @kind function - * @param {string} url The URL to be parsed. - * @description Normalizes and parses a URL. - * @returns {object} Returns the normalized URL as a dictionary. - * - * | member name | Description | - * |---------------|----------------| - * | href | A normalized version of the provided URL if it was not an absolute URL | - * | protocol | The protocol including the trailing colon | - * | host | The host and port (if the port is non-default) of the normalizedUrl | - * | search | The search params, minus the question mark | - * | hash | The hash string, minus the hash symbol - * | hostname | The hostname - * | port | The port, without ":" - * | pathname | The pathname, beginning with "/" - * - */ -function urlResolve(url, base) { - var href = url; - - if (msie) { - // Normalize before parse. Refer Implementation Notes on why this is - // done in two steps on IE. - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') - ? urlParsingNode.pathname - : '/' + urlParsingNode.pathname - }; -} + /** + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * URL will be resolved into an absolute URL in the context of the application document. + * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related + * properties are all populated to reflect the normalized URL. This approach has wide + * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other + * browsers. However, the parsed components will not be set if the URL assigned did not specify + * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We + * work around that by performing the parsing in a 2nd step by taking a previously normalized + * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the + * properties such as protocol, hostname, port, etc. + * + * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one + * uses the inner HTML approach to assign the URL as part of an HTML snippet - + * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. + * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. + * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that + * method and IE < 8 is unsupported. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @kind function + * @param {string} url The URL to be parsed. + * @description Normalizes and parses a URL. + * @returns {object} Returns the normalized URL as a dictionary. + * + * | member name | Description | + * |---------------|----------------| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | protocol | The protocol including the trailing colon | + * | host | The host and port (if the port is non-default) of the normalizedUrl | + * | search | The search params, minus the question mark | + * | hash | The hash string, minus the hash symbol + * | hostname | The hostname + * | port | The port, without ":" + * | pathname | The pathname, beginning with "/" + * + */ + function urlResolve(url, base) { + var href = url; + + if (msie) { + // Normalize before parse. Refer Implementation Notes on why this is + // done in two steps on IE. + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } -/** - * Parse a request URL and determine whether this is a same-origin request as the application document. - * - * @param {string|object} requestUrl The url of the request as a string that will be resolved - * or a parsed URL object. - * @returns {boolean} Whether the request is for the same origin as the application document. - */ -function urlIsSameOrigin(requestUrl) { - var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; - return (parsed.protocol === originUrl.protocol && - parsed.host === originUrl.host); -} + urlParsingNode.setAttribute('href', href); -/** - * @ngdoc service - * @name $window - * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overridden, removed or mocked for testing. - * - * Expressions, like the one defined for the `ngClick` directive in the example - * below, are evaluated with respect to the current scope. Therefore, there is - * no risk of inadvertently coding in a dependency on a global value in such an - * expression. - * - * @example - + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') + ? urlParsingNode.pathname + : '/' + urlParsingNode.pathname + }; + } + + /** + * Parse a request URL and determine whether this is a same-origin request as the application document. + * + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the request is for the same origin as the application document. + */ + function urlIsSameOrigin(requestUrl) { + var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); + } + + /** + * @ngdoc service + * @name $window + * + * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In angular we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. + * + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. + * + * @example + - -
          - - -
          + +
          + + +
          - it('should display the greeting in the input box', function() { + it('should display the greeting in the input box', function() { element(by.model('greeting')).sendKeys('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); -
          - */ -function $WindowProvider(){ - this.$get = valueFn(window); -} - -/* global currencyFilter: true, - dateFilter: true, - filterFilter: true, - jsonFilter: true, - limitToFilter: true, - lowercaseFilter: true, - numberFilter: true, - orderByFilter: true, - uppercaseFilter: true, - */ +
          + */ + function $WindowProvider() { + this.$get = valueFn(window); + } + + /* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ -/** - * @ngdoc provider - * @name $filterProvider - * @description - * - * Filters are just functions which transform input to an output. However filters need to be - * Dependency Injected. To achieve this a filter definition consists of a factory function which is - * annotated with dependencies and is responsible for creating a filter function. - * - * ```js - * // Filter registration - * function MyModule($provide, $filterProvider) { + /** + * @ngdoc provider + * @name $filterProvider + * @description + * + * Filters are just functions which transform input to an output. However filters need to be + * Dependency Injected. To achieve this a filter definition consists of a factory function which is + * annotated with dependencies and is responsible for creating a filter function. + * + * ```js + * // Filter registration + * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; @@ -16167,195 +16286,196 @@ function $WindowProvider(){ * }; * }); * } - * ``` - * - * The filter function is registered with the `$injector` under the filter name suffix with - * `Filter`. - * - * ```js - * it('should be the same instance', inject( - * function($filterProvider) { + * ``` + * + * The filter function is registered with the `$injector` under the filter name suffix with + * `Filter`. + * + * ```js + * it('should be the same instance', inject( + * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, - * function($filter, reverseFilter) { + * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); - * ``` - * - * - * For more information about how angular filters work, and how to create your own filters, see - * {@link guide/filter Filters} in the Angular Developer Guide. - */ + * ``` + * + * + * For more information about how angular filters work, and how to create your own filters, see + * {@link guide/filter Filters} in the Angular Developer Guide. + */ -/** - * @ngdoc service - * @name $filter - * @kind function - * @description - * Filters are used for formatting data displayed to the user. - * - * The general syntax in templates is as follows: - * - * {{ expression [| filter_name[:parameter_value] ... ] }} - * - * @param {String} name Name of the filter function to retrieve - * @return {Function} the filter function - * @example - + /** + * @ngdoc service + * @name $filter + * @kind function + * @description + * Filters are used for formatting data displayed to the user. + * + * The general syntax in templates is as follows: + * + * {{ expression [| filter_name[:parameter_value] ... ] }} + * + * @param {String} name Name of the filter function to retrieve + * @return {Function} the filter function + * @example + -
          -

          {{ originalText }}

          -

          {{ filteredText }}

          -
          +
          +

          {{ originalText }}

          +

          {{ filteredText }}

          +
          - angular.module('filterExample', []) - .controller('MainCtrl', function($scope, $filter) { + angular.module('filterExample', []) + .controller('MainCtrl', function($scope, $filter) { $scope.originalText = 'hello'; $scope.filteredText = $filter('uppercase')($scope.originalText); }); -
          - */ -$FilterProvider.$inject = ['$provide']; -function $FilterProvider($provide) { - var suffix = 'Filter'; - - /** - * @ngdoc method - * @name $filterProvider#register - * @param {string|Object} name Name of the filter function, or an object map of filters where - * the keys are the filter names and the values are the filter factories. - * @returns {Object} Registered filter instance, or if a map of filters was provided then a map - * of the registered filter instances. - */ - function register(name, factory) { - if(isObject(name)) { - var filters = {}; - forEach(name, function(filter, key) { - filters[key] = register(key, filter); - }); - return filters; - } else { - return $provide.factory(name + suffix, factory); - } - } - this.register = register; +
          + */ + $FilterProvider.$inject = ['$provide']; + function $FilterProvider($provide) { + var suffix = 'Filter'; - this.$get = ['$injector', function($injector) { - return function(name) { - return $injector.get(name + suffix); - }; - }]; - - //////////////////////////////////////// - - /* global - currencyFilter: false, - dateFilter: false, - filterFilter: false, - jsonFilter: false, - limitToFilter: false, - lowercaseFilter: false, - numberFilter: false, - orderByFilter: false, - uppercaseFilter: false, - */ - - register('currency', currencyFilter); - register('date', dateFilter); - register('filter', filterFilter); - register('json', jsonFilter); - register('limitTo', limitToFilter); - register('lowercase', lowercaseFilter); - register('number', numberFilter); - register('orderBy', orderByFilter); - register('uppercase', uppercaseFilter); -} + /** + * @ngdoc method + * @name $filterProvider#register + * @param {string|Object} name Name of the filter function, or an object map of filters where + * the keys are the filter names and the values are the filter factories. + * @returns {Object} Registered filter instance, or if a map of filters was provided then a map + * of the registered filter instances. + */ + function register(name, factory) { + if (isObject(name)) { + var filters = {}; + forEach(name, function (filter, key) { + filters[key] = register(key, filter); + }); + return filters; + } else { + return $provide.factory(name + suffix, factory); + } + } -/** - * @ngdoc filter - * @name filter - * @kind function - * - * @description - * Selects a subset of items from `array` and returns it as a new array. - * - * @param {Array} array The source array. - * @param {string|Object|function()} expression The predicate to be used for selecting items from - * `array`. - * - * Can be one of: - * - * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against - * the contents of the `array`. All strings or objects with string properties in `array` that contain this string - * will be returned. The predicate can be negated by prefixing the string with `!`. - * - * - `Object`: A pattern object can be used to filter specific properties on objects contained - * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items - * which have property `name` containing "M" and property `phone` containing "1". A special - * property name `$` can be used (as in `{$:"text"}`) to accept a match against any - * property of the object. That's equivalent to the simple substring match with a `string` - * as described above. The predicate can be negated by prefixing the string with `!`. - * For Example `{name: "!M"}` predicate will return an array of items which have property `name` - * not containing "M". - * - * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The - * function is called for each element of `array`. The final result is an array of those - * elements that the predicate returned true for. - * - * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in - * determining if the expected value (from the filter expression) and actual value (from - * the object in the array) should be considered a match. - * - * Can be one of: - * - * - `function(actual, expected)`: - * The function will be given the object value and the predicate value to compare and - * should return true if the item should be included in filtered result. - * - * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. - * this is essentially strict comparison of expected and actual. - * - * - `false|undefined`: A short hand for a function which will look for a substring match in case - * insensitive way. - * - * @example - + this.register = register; + + this.$get = ['$injector', function ($injector) { + return function (name) { + return $injector.get(name + suffix); + }; + }]; + + //////////////////////////////////////// + + /* global + currencyFilter: false, + dateFilter: false, + filterFilter: false, + jsonFilter: false, + limitToFilter: false, + lowercaseFilter: false, + numberFilter: false, + orderByFilter: false, + uppercaseFilter: false, + */ + + register('currency', currencyFilter); + register('date', dateFilter); + register('filter', filterFilter); + register('json', jsonFilter); + register('limitTo', limitToFilter); + register('lowercase', lowercaseFilter); + register('number', numberFilter); + register('orderBy', orderByFilter); + register('uppercase', uppercaseFilter); + } + + /** + * @ngdoc filter + * @name filter + * @kind function + * + * @description + * Selects a subset of items from `array` and returns it as a new array. + * + * @param {Array} array The source array. + * @param {string|Object|function()} expression The predicate to be used for selecting items from + * `array`. + * + * Can be one of: + * + * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against + * the contents of the `array`. All strings or objects with string properties in `array` that contain this string + * will be returned. The predicate can be negated by prefixing the string with `!`. + * + * - `Object`: A pattern object can be used to filter specific properties on objects contained + * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items + * which have property `name` containing "M" and property `phone` containing "1". A special + * property name `$` can be used (as in `{$:"text"}`) to accept a match against any + * property of the object. That's equivalent to the simple substring match with a `string` + * as described above. The predicate can be negated by prefixing the string with `!`. + * For Example `{name: "!M"}` predicate will return an array of items which have property `name` + * not containing "M". + * + * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The + * function is called for each element of `array`. The final result is an array of those + * elements that the predicate returned true for. + * + * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in + * determining if the expected value (from the filter expression) and actual value (from + * the object in the array) should be considered a match. + * + * Can be one of: + * + * - `function(actual, expected)`: + * The function will be given the object value and the predicate value to compare and + * should return true if the item should be included in filtered result. + * + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. + * this is essentially strict comparison of expected and actual. + * + * - `false|undefined`: A short hand for a function which will look for a substring match in case + * insensitive way. + * + * @example + -
          - - Search: - - - - - - -
          NamePhone
          {{friend.name}}{{friend.phone}}
          -
          - Any:
          - Name only
          - Phone only
          - Equality
          - - - - - - -
          NamePhone
          {{friendObj.name}}{{friendObj.phone}}
          +
          + + Search: + + + + + + +
          NamePhone
          {{friend.name}}{{friend.phone}}
          +
          + Any:
          + Name only
          + Phone only
          + Equality
          + + + + + + +
          NamePhone
          {{friendObj.name}}{{friendObj.phone}}
          - var expectFriendNames = function(expectedNames, key) { + var expectFriendNames = function(expectedNames, key) { element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { arr.forEach(function(wd, i) { expect(wd.getText()).toMatch(expectedNames[i]); @@ -16363,7 +16483,7 @@ function $FilterProvider($provide) { }); }; - it('should search across all fields when filtering with a string', function() { + it('should search across all fields when filtering with a string', function() { var searchText = element(by.model('searchText')); searchText.clear(); searchText.sendKeys('m'); @@ -16374,13 +16494,13 @@ function $FilterProvider($provide) { expectFriendNames(['John', 'Julie'], 'friend'); }); - it('should search in specific fields when filtering with a predicate object', function() { + it('should search in specific fields when filtering with a predicate object', function() { var searchAny = element(by.model('search.$')); searchAny.clear(); searchAny.sendKeys('i'); expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); }); - it('should use a equal comparison when comparator is true', function() { + it('should use a equal comparison when comparator is true', function() { var searchName = element(by.model('search.name')); var strict = element(by.model('strict')); searchName.clear(); @@ -16389,152 +16509,152 @@ function $FilterProvider($provide) { expectFriendNames(['Julie'], 'friendObj'); }); -
          - */ -function filterFilter() { - return function(array, expression, comparator) { - if (!isArray(array)) return array; - - var comparatorType = typeof(comparator), - predicates = []; +
          + */ + function filterFilter() { + return function (array, expression, comparator) { + if (!isArray(array)) return array; - predicates.check = function(value, index) { - for (var j = 0; j < predicates.length; j++) { - if(!predicates[j](value, index)) { - return false; - } - } - return true; - }; + var comparatorType = typeof(comparator), + predicates = []; - if (comparatorType !== 'function') { - if (comparatorType === 'boolean' && comparator) { - comparator = function(obj, text) { - return angular.equals(obj, text); - }; - } else { - comparator = function(obj, text) { - if (obj && text && typeof obj === 'object' && typeof text === 'object') { - for (var objKey in obj) { - if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && - comparator(obj[objKey], text[objKey])) { + predicates.check = function (value, index) { + for (var j = 0; j < predicates.length; j++) { + if (!predicates[j](value, index)) { + return false; + } + } return true; - } + }; + + if (comparatorType !== 'function') { + if (comparatorType === 'boolean' && comparator) { + comparator = function (obj, text) { + return angular.equals(obj, text); + }; + } else { + comparator = function (obj, text) { + if (obj && text && typeof obj === 'object' && typeof text === 'object') { + for (var objKey in obj) { + if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && + comparator(obj[objKey], text[objKey])) { + return true; + } + } + return false; + } + text = ('' + text).toLowerCase(); + return ('' + obj).toLowerCase().indexOf(text) > -1; + }; + } } - return false; - } - text = (''+text).toLowerCase(); - return (''+obj).toLowerCase().indexOf(text) > -1; - }; - } - } - var search = function(obj, text){ - if (typeof text === 'string' && text.charAt(0) === '!') { - return !search(obj, text.substr(1)); - } - switch (typeof obj) { - case 'boolean': - case 'number': - case 'string': - return comparator(obj, text); - case 'object': - switch (typeof text) { - case 'object': - return comparator(obj, text); - default: - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; + var search = function (obj, text) { + if (typeof text === 'string' && text.charAt(0) === '!') { + return !search(obj, text.substr(1)); } - } - break; - } - return false; - case 'array': - for ( var i = 0; i < obj.length; i++) { - if (search(obj[i], text)) { - return true; + switch (typeof obj) { + case 'boolean': + case 'number': + case 'string': + return comparator(obj, text); + case 'object': + switch (typeof text) { + case 'object': + return comparator(obj, text); + default: + for (var objKey in obj) { + if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { + return true; + } + } + break; + } + return false; + case 'array': + for (var i = 0; i < obj.length; i++) { + if (search(obj[i], text)) { + return true; + } + } + return false; + default: + return false; + } + }; + switch (typeof expression) { + case 'boolean': + case 'number': + case 'string': + // Set up expression object and fall through + expression = {$: expression}; + // jshint -W086 + case 'object': + // jshint +W086 + for (var key in expression) { + (function (path) { + if (typeof expression[path] === 'undefined') return; + predicates.push(function (value) { + return search(path == '$' ? value : (value && value[path]), expression[path]); + }); + })(key); + } + break; + case 'function': + predicates.push(expression); + break; + default: + return array; } - } - return false; - default: - return false; - } - }; - switch (typeof expression) { - case 'boolean': - case 'number': - case 'string': - // Set up expression object and fall through - expression = {$:expression}; - // jshint -W086 - case 'object': - // jshint +W086 - for (var key in expression) { - (function(path) { - if (typeof expression[path] === 'undefined') return; - predicates.push(function(value) { - return search(path == '$' ? value : (value && value[path]), expression[path]); - }); - })(key); - } - break; - case 'function': - predicates.push(expression); - break; - default: - return array; - } - var filtered = []; - for ( var j = 0; j < array.length; j++) { - var value = array[j]; - if (predicates.check(value, j)) { - filtered.push(value); - } + var filtered = []; + for (var j = 0; j < array.length; j++) { + var value = array[j]; + if (predicates.check(value, j)) { + filtered.push(value); + } + } + return filtered; + }; } - return filtered; - }; -} -/** - * @ngdoc filter - * @name currency - * @kind function - * - * @description - * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default - * symbol for current locale is used. - * - * @param {number} amount Input to filter. - * @param {string=} symbol Currency symbol or identifier to be displayed. - * @param {number=} fractionSize Number of decimal places to round the amount to. - * @returns {string} Formatted number. - * - * - * @example - + /** + * @ngdoc filter + * @name currency + * @kind function + * + * @description + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default + * symbol for current locale is used. + * + * @param {number} amount Input to filter. + * @param {string=} symbol Currency symbol or identifier to be displayed. + * @param {number=} fractionSize Number of decimal places to round the amount to. + * @returns {string} Formatted number. + * + * + * @example + - -
          -
          - default currency symbol ($): {{amount | currency}}
          - custom currency identifier (USD$): {{amount | currency:"USD$"}} - no fractions (0): {{amount | currency:"USD$":0}} -
          + +
          +
          + default currency symbol ($): {{amount | currency}}
          + custom currency identifier (USD$): {{amount | currency:"USD$"}} + no fractions (0): {{amount | currency:"USD$":0}} +
          - it('should init with 1234.56', function() { + it('should init with 1234.56', function() { expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); }); - it('should update', function() { + it('should update', function() { if (browser.params.browser == 'safari') { // Safari does not understand the minus key. See // https://github.com/angular/protractor/issues/481 @@ -16547,69 +16667,69 @@ function filterFilter() { expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)'); }); -
          - */ -currencyFilter.$inject = ['$locale']; -function currencyFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(amount, currencySymbol, fractionSize){ - if (isUndefined(currencySymbol)) { - currencySymbol = formats.CURRENCY_SYM; - } +
          + */ + currencyFilter.$inject = ['$locale']; + function currencyFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function (amount, currencySymbol, fractionSize) { + if (isUndefined(currencySymbol)) { + currencySymbol = formats.CURRENCY_SYM; + } - if (isUndefined(fractionSize)) { - // TODO: read the default value from the locale file - fractionSize = 2; - } + if (isUndefined(fractionSize)) { + // TODO: read the default value from the locale file + fractionSize = 2; + } - // if null or undefined pass it through - return (amount == null) - ? amount - : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). - replace(/\u00A4/g, currencySymbol); - }; -} + // if null or undefined pass it through + return (amount == null) + ? amount + : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). + replace(/\u00A4/g, currencySymbol); + }; + } -/** - * @ngdoc filter - * @name number - * @kind function - * - * @description - * Formats a number as text. - * - * If the input is not a number an empty string is returned. - * - * @param {number|string} number Number to format. - * @param {(number|string)=} fractionSize Number of decimal places to round the number to. - * If this is not provided then the fraction size is computed from the current locale's number - * formatting pattern. In the case of the default locale, it will be 3. - * @returns {string} Number rounded to decimalPlaces and places a “,†after each third digit. - * - * @example - + /** + * @ngdoc filter + * @name number + * @kind function + * + * @description + * Formats a number as text. + * + * If the input is not a number an empty string is returned. + * + * @param {number|string} number Number to format. + * @param {(number|string)=} fractionSize Number of decimal places to round the number to. + * If this is not provided then the fraction size is computed from the current locale's number + * formatting pattern. In the case of the default locale, it will be 3. + * @returns {string} Number rounded to decimalPlaces and places a “,†after each third digit. + * + * @example + - -
          - Enter number:
          - Default formatting: {{val | number}}
          - No fractions: {{val | number:0}}
          - Negative number: {{-val | number:4}} -
          + +
          + Enter number:
          + Default formatting: {{val | number}}
          + No fractions: {{val | number:0}}
          + Negative number: {{-val | number:4}} +
          - it('should format numbers', function() { + it('should format numbers', function() { expect(element(by.id('number-default')).getText()).toBe('1,234.568'); expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); - it('should update', function() { + it('should update', function() { element(by.model('val')).clear(); element(by.model('val')).sendKeys('3374.333'); expect(element(by.id('number-default')).getText()).toBe('3,374.333'); @@ -16617,289 +16737,290 @@ function currencyFilter($locale) { expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); }); -
          - */ +
          + */ + + numberFilter.$inject = ['$locale']; + function numberFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function (number, fractionSize) { -numberFilter.$inject = ['$locale']; -function numberFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(number, fractionSize) { - - // if null or undefined pass it through - return (number == null) - ? number - : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, - fractionSize); - }; -} - -var DECIMAL_SEP = '.'; -function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (!isFinite(number) || isObject(number)) return ''; - - var isNegative = number < 0; - number = Math.abs(number); - var numStr = number + '', - formatedText = '', - parts = []; - - var hasExponent = false; - if (numStr.indexOf('e') !== -1) { - var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); - if (match && match[2] == '-' && match[3] > fractionSize + 1) { - numStr = '0'; - number = 0; - } else { - formatedText = numStr; - hasExponent = true; + // if null or undefined pass it through + return (number == null) + ? number + : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, + fractionSize); + }; } - } - if (!hasExponent) { - var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + var DECIMAL_SEP = '.'; + + function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { + if (!isFinite(number) || isObject(number)) return ''; + + var isNegative = number < 0; + number = Math.abs(number); + var numStr = number + '', + formatedText = '', + parts = []; + + var hasExponent = false; + if (numStr.indexOf('e') !== -1) { + var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); + if (match && match[2] == '-' && match[3] > fractionSize + 1) { + numStr = '0'; + number = 0; + } else { + formatedText = numStr; + hasExponent = true; + } + } + + if (!hasExponent) { + var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + + // determine fractionSize if it is not specified + if (isUndefined(fractionSize)) { + fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); + } + + // safely round numbers in JS without hitting imprecisions of floating-point arithmetics + // inspired by: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round + number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); + + if (number === 0) { + isNegative = false; + } + + var fraction = ('' + number).split(DECIMAL_SEP); + var whole = fraction[0]; + fraction = fraction[1] || ''; + + var i, pos = 0, + lgroup = pattern.lgSize, + group = pattern.gSize; + + if (whole.length >= (lgroup + group)) { + pos = whole.length - lgroup; + for (i = 0; i < pos; i++) { + if ((pos - i) % group === 0 && i !== 0) { + formatedText += groupSep; + } + formatedText += whole.charAt(i); + } + } + + for (i = pos; i < whole.length; i++) { + if ((whole.length - i) % lgroup === 0 && i !== 0) { + formatedText += groupSep; + } + formatedText += whole.charAt(i); + } + + // format fraction part. + while (fraction.length < fractionSize) { + fraction += '0'; + } + + if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); + } else { + + if (fractionSize > 0 && number > -1 && number < 1) { + formatedText = number.toFixed(fractionSize); + } + } + + parts.push(isNegative ? pattern.negPre : pattern.posPre); + parts.push(formatedText); + parts.push(isNegative ? pattern.negSuf : pattern.posSuf); + return parts.join(''); + } - // determine fractionSize if it is not specified - if (isUndefined(fractionSize)) { - fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); + function padNumber(num, digits, trim) { + var neg = ''; + if (num < 0) { + neg = '-'; + num = -num; + } + num = '' + num; + while (num.length < digits) num = '0' + num; + if (trim) + num = num.substr(num.length - digits); + return neg + num; + } + + + function dateGetter(name, size, offset, trim) { + offset = offset || 0; + return function (date) { + var value = date['get' + name](); + if (offset > 0 || value > -offset) + value += offset; + if (value === 0 && offset == -12) value = 12; + return padNumber(value, size, trim); + }; } - // safely round numbers in JS without hitting imprecisions of floating-point arithmetics - // inspired by: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round - number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); + function dateStrGetter(name, shortForm) { + return function (date, formats) { + var value = date['get' + name](); + var get = uppercase(shortForm ? ('SHORT' + name) : name); - if (number === 0) { - isNegative = false; + return formats[get][value]; + }; } - var fraction = ('' + number).split(DECIMAL_SEP); - var whole = fraction[0]; - fraction = fraction[1] || ''; + function timeZoneGetter(date) { + var zone = -1 * date.getTimezoneOffset(); + var paddedZone = (zone >= 0) ? "+" : ""; - var i, pos = 0, - lgroup = pattern.lgSize, - group = pattern.gSize; + paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + + padNumber(Math.abs(zone % 60), 2); - if (whole.length >= (lgroup + group)) { - pos = whole.length - lgroup; - for (i = 0; i < pos; i++) { - if ((pos - i)%group === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } + return paddedZone; } - for (i = pos; i < whole.length; i++) { - if ((whole.length - i)%lgroup === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); + function getFirstThursdayOfYear(year) { + // 0 = index of January + var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); + // 4 = index of Thursday (+1 to account for 1st = 5) + // 11 = index of *next* Thursday (+1 account for 1st = 12) + return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); } - // format fraction part. - while(fraction.length < fractionSize) { - fraction += '0'; + function getThursdayThisWeek(datetime) { + return new Date(datetime.getFullYear(), datetime.getMonth(), + // 4 = index of Thursday + datetime.getDate() + (4 - datetime.getDay())); } - if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); - } else { + function weekGetter(size) { + return function (date) { + var firstThurs = getFirstThursdayOfYear(date.getFullYear()), + thisThurs = getThursdayThisWeek(date); + + var diff = +thisThurs - +firstThurs, + result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week - if (fractionSize > 0 && number > -1 && number < 1) { - formatedText = number.toFixed(fractionSize); + return padNumber(result, size); + }; } - } - - parts.push(isNegative ? pattern.negPre : pattern.posPre); - parts.push(formatedText); - parts.push(isNegative ? pattern.negSuf : pattern.posSuf); - return parts.join(''); -} - -function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; - } - num = '' + num; - while(num.length < digits) num = '0' + num; - if (trim) - num = num.substr(num.length - digits); - return neg + num; -} - - -function dateGetter(name, size, offset, trim) { - offset = offset || 0; - return function(date) { - var value = date['get' + name](); - if (offset > 0 || value > -offset) - value += offset; - if (value === 0 && offset == -12 ) value = 12; - return padNumber(value, size, trim); - }; -} - -function dateStrGetter(name, shortForm) { - return function(date, formats) { - var value = date['get' + name](); - var get = uppercase(shortForm ? ('SHORT' + name) : name); - - return formats[get][value]; - }; -} - -function timeZoneGetter(date) { - var zone = -1 * date.getTimezoneOffset(); - var paddedZone = (zone >= 0) ? "+" : ""; - - paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + - padNumber(Math.abs(zone % 60), 2); - - return paddedZone; -} - -function getFirstThursdayOfYear(year) { - // 0 = index of January - var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); - // 4 = index of Thursday (+1 to account for 1st = 5) - // 11 = index of *next* Thursday (+1 account for 1st = 12) - return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); -} - -function getThursdayThisWeek(datetime) { - return new Date(datetime.getFullYear(), datetime.getMonth(), - // 4 = index of Thursday - datetime.getDate() + (4 - datetime.getDay())); -} - -function weekGetter(size) { - return function(date) { - var firstThurs = getFirstThursdayOfYear(date.getFullYear()), - thisThurs = getThursdayThisWeek(date); - - var diff = +thisThurs - +firstThurs, - result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week - - return padNumber(result, size); - }; -} - -function ampmGetter(date, formats) { - return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; -} - -var DATE_FORMATS = { - yyyy: dateGetter('FullYear', 4), - yy: dateGetter('FullYear', 2, 0, true), - y: dateGetter('FullYear', 1), - MMMM: dateStrGetter('Month'), - MMM: dateStrGetter('Month', true), - MM: dateGetter('Month', 2, 1), - M: dateGetter('Month', 1, 1), - dd: dateGetter('Date', 2), - d: dateGetter('Date', 1), - HH: dateGetter('Hours', 2), - H: dateGetter('Hours', 1), - hh: dateGetter('Hours', 2, -12), - h: dateGetter('Hours', 1, -12), - mm: dateGetter('Minutes', 2), - m: dateGetter('Minutes', 1), - ss: dateGetter('Seconds', 2), - s: dateGetter('Seconds', 1), - // while ISO 8601 requires fractions to be prefixed with `.` or `,` - // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions - sss: dateGetter('Milliseconds', 3), - EEEE: dateStrGetter('Day'), - EEE: dateStrGetter('Day', true), - a: ampmGetter, - Z: timeZoneGetter, - ww: weekGetter(2), - w: weekGetter(1) -}; - -var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/, - NUMBER_STRING = /^\-?\d+$/; -/** - * @ngdoc filter - * @name date - * @kind function - * - * @description - * Formats `date` to a string based on the requested `format`. - * - * `format` string can be composed of the following elements: - * - * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) - * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) - * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) - * * `'MMMM'`: Month in year (January-December) - * * `'MMM'`: Month in year (Jan-Dec) - * * `'MM'`: Month in year, padded (01-12) - * * `'M'`: Month in year (1-12) - * * `'dd'`: Day in month, padded (01-31) - * * `'d'`: Day in month (1-31) - * * `'EEEE'`: Day in Week,(Sunday-Saturday) - * * `'EEE'`: Day in Week, (Sun-Sat) - * * `'HH'`: Hour in day, padded (00-23) - * * `'H'`: Hour in day (0-23) - * * `'hh'`: Hour in AM/PM, padded (01-12) - * * `'h'`: Hour in AM/PM, (1-12) - * * `'mm'`: Minute in hour, padded (00-59) - * * `'m'`: Minute in hour (0-59) - * * `'ss'`: Second in minute, padded (00-59) - * * `'s'`: Second in minute (0-59) - * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) - * * `'a'`: AM/PM marker - * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) - * * `'ww'`: ISO-8601 week of year (00-53) - * * `'w'`: ISO-8601 week of year (0-53) - * - * `format` string can also be one of the following predefined - * {@link guide/i18n localizable formats}: - * - * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale - * (e.g. Sep 3, 2010 12:05:08 PM) - * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) - * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale - * (e.g. Friday, September 3, 2010) - * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) - * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) - * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) - * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) - * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) - * - * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. - * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence - * (e.g. `"h 'o''clock'"`). - * - * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or - * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its - * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is - * specified in the string input, the time is considered to be in the local timezone. - * @param {string=} format Formatting rules (see Description). If not specified, - * `mediumDate` is used. - * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported. - * If not specified, the timezone of the browser will be used. - * @returns {string} Formatted string or the input if input is not recognized as date/millis. - * - * @example - + function ampmGetter(date, formats) { + return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; + } + + var DATE_FORMATS = { + yyyy: dateGetter('FullYear', 4), + yy: dateGetter('FullYear', 2, 0, true), + y: dateGetter('FullYear', 1), + MMMM: dateStrGetter('Month'), + MMM: dateStrGetter('Month', true), + MM: dateGetter('Month', 2, 1), + M: dateGetter('Month', 1, 1), + dd: dateGetter('Date', 2), + d: dateGetter('Date', 1), + HH: dateGetter('Hours', 2), + H: dateGetter('Hours', 1), + hh: dateGetter('Hours', 2, -12), + h: dateGetter('Hours', 1, -12), + mm: dateGetter('Minutes', 2), + m: dateGetter('Minutes', 1), + ss: dateGetter('Seconds', 2), + s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), + EEEE: dateStrGetter('Day'), + EEE: dateStrGetter('Day', true), + a: ampmGetter, + Z: timeZoneGetter, + ww: weekGetter(2), + w: weekGetter(1) + }; + + var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/, + NUMBER_STRING = /^\-?\d+$/; + + /** + * @ngdoc filter + * @name date + * @kind function + * + * @description + * Formats `date` to a string based on the requested `format`. + * + * `format` string can be composed of the following elements: + * + * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) + * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) + * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) + * * `'MMMM'`: Month in year (January-December) + * * `'MMM'`: Month in year (Jan-Dec) + * * `'MM'`: Month in year, padded (01-12) + * * `'M'`: Month in year (1-12) + * * `'dd'`: Day in month, padded (01-31) + * * `'d'`: Day in month (1-31) + * * `'EEEE'`: Day in Week,(Sunday-Saturday) + * * `'EEE'`: Day in Week, (Sun-Sat) + * * `'HH'`: Hour in day, padded (00-23) + * * `'H'`: Hour in day (0-23) + * * `'hh'`: Hour in AM/PM, padded (01-12) + * * `'h'`: Hour in AM/PM, (1-12) + * * `'mm'`: Minute in hour, padded (00-59) + * * `'m'`: Minute in hour (0-59) + * * `'ss'`: Second in minute, padded (00-59) + * * `'s'`: Second in minute (0-59) + * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) + * * `'a'`: AM/PM marker + * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) + * * `'ww'`: ISO-8601 week of year (00-53) + * * `'w'`: ISO-8601 week of year (0-53) + * + * `format` string can also be one of the following predefined + * {@link guide/i18n localizable formats}: + * + * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale + * (e.g. Sep 3, 2010 12:05:08 PM) + * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) + * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale + * (e.g. Friday, September 3, 2010) + * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) + * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) + * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) + * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) + * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) + * + * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. + * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence + * (e.g. `"h 'o''clock'"`). + * + * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or + * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its + * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is + * specified in the string input, the time is considered to be in the local timezone. + * @param {string=} format Formatting rules (see Description). If not specified, + * `mediumDate` is used. + * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported. + * If not specified, the timezone of the browser will be used. + * @returns {string} Formatted string or the input if input is not recognized as date/millis. + * + * @example + - {{1288323623006 | date:'medium'}}: - {{1288323623006 | date:'medium'}}
          - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: - {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
          - {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: - {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
          - {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: - {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
          + {{1288323623006 | date:'medium'}}: + {{1288323623006 | date:'medium'}}
          + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
          + {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: + {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
          + {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: + {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
          - it('should format date', function() { + it('should format date', function() { expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). @@ -16910,165 +17031,165 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); }); -
          - */ -dateFilter.$inject = ['$locale']; -function dateFilter($locale) { - - - var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - // 1 2 3 4 5 6 7 8 9 10 11 - function jsonStringToDate(string) { - var match; - if (match = string.match(R_ISO8601_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0, - dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, - timeSetter = match[8] ? date.setUTCHours : date.setHours; - - if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); - } - dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); - var h = int(match[4]||0) - tzHour; - var m = int(match[5]||0) - tzMin; - var s = int(match[6]||0); - var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); - timeSetter.call(date, h, m, s, ms); - return date; - } - return string; - } +
          + */ + dateFilter.$inject = ['$locale']; + function dateFilter($locale) { + + + var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { + var match; + if (match = string.match(R_ISO8601_STR)) { + var date = new Date(0), + tzHour = 0, + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + + if (match[9]) { + tzHour = int(match[9] + match[10]); + tzMin = int(match[9] + match[11]); + } + dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); + var h = int(match[4] || 0) - tzHour; + var m = int(match[5] || 0) - tzMin; + var s = int(match[6] || 0); + var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); + timeSetter.call(date, h, m, s, ms); + return date; + } + return string; + } - return function(date, format, timezone) { - var text = '', - parts = [], - fn, match; + return function (date, format, timezone) { + var text = '', + parts = [], + fn, match; - format = format || 'mediumDate'; - format = $locale.DATETIME_FORMATS[format] || format; - if (isString(date)) { - date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); - } + format = format || 'mediumDate'; + format = $locale.DATETIME_FORMATS[format] || format; + if (isString(date)) { + date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); + } - if (isNumber(date)) { - date = new Date(date); - } + if (isNumber(date)) { + date = new Date(date); + } - if (!isDate(date)) { - return date; - } + if (!isDate(date)) { + return date; + } - while(format) { - match = DATE_FORMATS_SPLIT.exec(format); - if (match) { - parts = concat(parts, match, 1); - format = parts.pop(); - } else { - parts.push(format); - format = null; - } - } + while (format) { + match = DATE_FORMATS_SPLIT.exec(format); + if (match) { + parts = concat(parts, match, 1); + format = parts.pop(); + } else { + parts.push(format); + format = null; + } + } - if (timezone && timezone === 'UTC') { - date = new Date(date.getTime()); - date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); - } - forEach(parts, function(value){ - fn = DATE_FORMATS[value]; - text += fn ? fn(date, $locale.DATETIME_FORMATS) - : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); - }); + if (timezone && timezone === 'UTC') { + date = new Date(date.getTime()); + date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); + } + forEach(parts, function (value) { + fn = DATE_FORMATS[value]; + text += fn ? fn(date, $locale.DATETIME_FORMATS) + : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); + }); - return text; - }; -} + return text; + }; + } -/** - * @ngdoc filter - * @name json - * @kind function - * - * @description - * Allows you to convert a JavaScript object into JSON string. - * - * This filter is mostly useful for debugging. When using the double curly {{value}} notation - * the binding is automatically converted to JSON. - * - * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. - * @returns {string} JSON string. - * - * - * @example - + /** + * @ngdoc filter + * @name json + * @kind function + * + * @description + * Allows you to convert a JavaScript object into JSON string. + * + * This filter is mostly useful for debugging. When using the double curly {{value}} notation + * the binding is automatically converted to JSON. + * + * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. + * @returns {string} JSON string. + * + * + * @example + -
          {{ {'name':'value'} | json }}
          +
          {{ {'name':'value'} | json }}
          - it('should jsonify filtered objects', function() { + it('should jsonify filtered objects', function() { expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); }); -
          - * - */ -function jsonFilter() { - return function(object) { - return toJson(object, true); - }; -} +
          + * + */ + function jsonFilter() { + return function (object) { + return toJson(object, true); + }; + } -/** - * @ngdoc filter - * @name lowercase - * @kind function - * @description - * Converts string to lowercase. - * @see angular.lowercase - */ -var lowercaseFilter = valueFn(lowercase); + /** + * @ngdoc filter + * @name lowercase + * @kind function + * @description + * Converts string to lowercase. + * @see angular.lowercase + */ + var lowercaseFilter = valueFn(lowercase); -/** - * @ngdoc filter - * @name uppercase - * @kind function - * @description - * Converts string to uppercase. - * @see angular.uppercase - */ -var uppercaseFilter = valueFn(uppercase); + /** + * @ngdoc filter + * @name uppercase + * @kind function + * @description + * Converts string to uppercase. + * @see angular.uppercase + */ + var uppercaseFilter = valueFn(uppercase); -/** - * @ngdoc filter - * @name limitTo - * @kind function - * - * @description - * Creates a new array or string containing only a specified number of elements. The elements - * are taken from either the beginning or the end of the source array, string or number, as specified by - * the value and sign (positive or negative) of `limit`. If a number is used as input, it is - * converted to a string. - * - * @param {Array|string|number} input Source array, string or number to be limited. - * @param {string|number} limit The length of the returned array or string. If the `limit` number - * is positive, `limit` number of items from the beginning of the source array/string are copied. - * If the number is negative, `limit` number of items from the end of the source array/string - * are copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array - * had less than `limit` elements. - * - * @example - + /** + * @ngdoc filter + * @name limitTo + * @kind function + * + * @description + * Creates a new array or string containing only a specified number of elements. The elements + * are taken from either the beginning or the end of the source array, string or number, as specified by + * the value and sign (positive or negative) of `limit`. If a number is used as input, it is + * converted to a string. + * + * @param {Array|string|number} input Source array, string or number to be limited. + * @param {string|number} limit The length of the returned array or string. If the `limit` number + * is positive, `limit` number of items from the beginning of the source array/string are copied. + * If the number is negative, `limit` number of items from the end of the source array/string + * are copied. The `limit` will be trimmed if it exceeds `array.length` + * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array + * had less than `limit` elements. + * + * @example + - -
          - Limit {{numbers}} to: -

          Output numbers: {{ numbers | limitTo:numLimit }}

          - Limit {{letters}} to: -

          Output letters: {{ letters | limitTo:letterLimit }}

          - Limit {{longNumber}} to: -

          Output long number: {{ longNumber | limitTo:longNumberLimit }}

          -
          + +
          + Limit {{numbers}} to: +

          Output numbers: {{ numbers | limitTo:numLimit }}

          + Limit {{letters}} to: +

          Output letters: {{ letters | limitTo:letterLimit }}

          + Limit {{longNumber}} to: +

          Output long number: {{ longNumber | limitTo:longNumberLimit }}

          +
          - var numLimitInput = element(by.model('numLimit')); - var letterLimitInput = element(by.model('letterLimit')); - var longNumberLimitInput = element(by.model('longNumberLimit')); - var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); - var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); - var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); - - it('should limit the number array to first three items', function() { + var numLimitInput = element(by.model('numLimit')); + var letterLimitInput = element(by.model('letterLimit')); + var longNumberLimitInput = element(by.model('longNumberLimit')); + var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); + var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); + + it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(longNumberLimitInput.getAttribute('value')).toBe('3'); @@ -17103,8 +17224,8 @@ var uppercaseFilter = valueFn(uppercase); expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); }); - // There is a bug in safari and protractor that doesn't like the minus key - // it('should update the output when -3 is entered', function() { + // There is a bug in safari and protractor that doesn't like the minus key + // it('should update the output when -3 is entered', function() { // numLimitInput.clear(); // numLimitInput.sendKeys('-3'); // letterLimitInput.clear(); @@ -17116,7 +17237,7 @@ var uppercaseFilter = valueFn(uppercase); // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); // }); - it('should not exceed the maximum size of input array', function() { + it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); @@ -17128,93 +17249,93 @@ var uppercaseFilter = valueFn(uppercase); expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); }); -
          -*/ -function limitToFilter(){ - return function(input, limit) { - if (isNumber(input)) input = input.toString(); - if (!isArray(input) && !isString(input)) return input; - - if (Math.abs(Number(limit)) === Infinity) { - limit = Number(limit); - } else { - limit = int(limit); - } +
          + */ + function limitToFilter() { + return function (input, limit) { + if (isNumber(input)) input = input.toString(); + if (!isArray(input) && !isString(input)) return input; - if (isString(input)) { - //NaN check on limit - if (limit) { - return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); - } else { - return ""; - } - } + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = int(limit); + } - var out = [], - i, n; - - // if abs(limit) exceeds maximum length, trim it - if (limit > input.length) - limit = input.length; - else if (limit < -input.length) - limit = -input.length; - - if (limit > 0) { - i = 0; - n = limit; - } else { - i = input.length + limit; - n = input.length; - } + if (isString(input)) { + //NaN check on limit + if (limit) { + return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); + } else { + return ""; + } + } - for (; i input.length) + limit = input.length; + else if (limit < -input.length) + limit = -input.length; -/** - * @ngdoc filter - * @name orderBy - * @kind function - * - * @description - * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically - * for strings and numerically for numbers. Note: if you notice numbers are not being sorted - * correctly, make sure they are actually being saved as numbers and not strings. - * - * @param {Array} array The array to sort. - * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be - * used by the comparator to determine the order of elements. - * - * Can be one of: - * - * - `function`: Getter function. The result of this function will be sorted using the - * `<`, `=`, `>` operator. - * - `string`: An Angular expression. The result of this expression is used to compare elements - * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by - * 3 first characters of a property called `name`). The result of a constant expression - * is interpreted as a property name to be used in comparisons (for example `"special name"` - * to sort object by the value of their `special name` property). An expression can be - * optionally prefixed with `+` or `-` to control ascending or descending sort order - * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array - * element itself is used to compare where sorting. - * - `Array`: An array of function or string predicates. The first predicate in the array - * is used for sorting, but when two items are equivalent, the next predicate is used. - * - * If the predicate is missing or empty then it defaults to `'+'`. - * - * @param {boolean=} reverse Reverse the order of the array. - * @returns {Array} Sorted copy of the source array. - * - * @example - + if (limit > 0) { + i = 0; + n = limit; + } else { + i = input.length + limit; + n = input.length; + } + + for (; i < n; i++) { + out.push(input[i]); + } + + return out; + }; + } + + /** + * @ngdoc filter + * @name orderBy + * @kind function + * + * @description + * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically + * for strings and numerically for numbers. Note: if you notice numbers are not being sorted + * correctly, make sure they are actually being saved as numbers and not strings. + * + * @param {Array} array The array to sort. + * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be + * used by the comparator to determine the order of elements. + * + * Can be one of: + * + * - `function`: Getter function. The result of this function will be sorted using the + * `<`, `=`, `>` operator. + * - `string`: An Angular expression. The result of this expression is used to compare elements + * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by + * 3 first characters of a property called `name`). The result of a constant expression + * is interpreted as a property name to be used in comparisons (for example `"special name"` + * to sort object by the value of their `special name` property). An expression can be + * optionally prefixed with `+` or `-` to control ascending or descending sort order + * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array + * element itself is used to compare where sorting. + * - `Array`: An array of function or string predicates. The first predicate in the array + * is used for sorting, but when two items are equivalent, the next predicate is used. + * + * If the predicate is missing or empty then it defaults to `'+'`. + * + * @param {boolean=} reverse Reverse the order of the array. + * @returns {Array} Sorted copy of the source array. + * + * @example + - -
          -
          Sorting predicate = {{predicate}}; reverse = {{reverse}}
          -
          - [ unsorted ] - - - - - - - - - - - -
          Name - (^)Phone NumberAge
          {{friend.name}}{{friend.phone}}{{friend.age}}
          -
          + +
          +
          Sorting predicate = {{predicate}}; reverse = {{reverse}}
          +
          + [ unsorted ] + + + + + + + + + + + +
          Name + (^)Phone NumberAge
          {{friend.name}}{{friend.phone}}{{friend.age}}
          +
          -
          - * - * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the - * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the - * desired parameters. - * - * Example: - * - * @example - - -
          - - - - - - - - - - - -
          Name - (^)Phone NumberAge
          {{friend.name}}{{friend.phone}}{{friend.age}}
          -
          -
          - - - angular.module('orderByExample', []) - .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { +
          + * + * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the + * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the + * desired parameters. + * + * Example: + * + * @example + + +
          + + + + + + + + + + + +
          Name + (^)Phone NumberAge
          {{friend.name}}{{friend.phone}}{{friend.age}}
          +
          +
          + + + angular.module('orderByExample', []) + .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { var orderBy = $filter('orderBy'); $scope.friends = [ { name: 'John', phone: '555-1212', age: 10 }, @@ -17287,174 +17408,182 @@ function limitToFilter(){ }; $scope.order('-age',false); }]); - -
          - */ -orderByFilter.$inject = ['$parse']; -function orderByFilter($parse){ - return function(array, sortPredicate, reverseOrder) { - if (!(isArrayLike(array))) return array; - sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; - if (sortPredicate.length === 0) { sortPredicate = ['+']; } - sortPredicate = sortPredicate.map(function(predicate){ - var descending = false, get = predicate || identity; - if (isString(predicate)) { - if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { - descending = predicate.charAt(0) == '-'; - predicate = predicate.substring(1); - } - if ( predicate === '' ) { - // Effectively no predicate was passed so we compare identity - return reverseComparator(function(a,b) { - return compare(a, b); - }, descending); - } - get = $parse(predicate); - if (get.constant) { - var key = get(); - return reverseComparator(function(a,b) { - return compare(a[key], b[key]); - }, descending); - } - } - return reverseComparator(function(a,b){ - return compare(get(a),get(b)); - }, descending); - }); - var arrayCopy = []; - for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } - return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); - - function comparator(o1, o2){ - for ( var i = 0; i < sortPredicate.length; i++) { - var comp = sortPredicate[i](o1, o2); - if (comp !== 0) return comp; - } - return 0; - } - function reverseComparator(comp, descending) { - return descending - ? function(a,b){return comp(b,a);} - : comp; +
          + + */ + orderByFilter.$inject = ['$parse']; + function orderByFilter($parse) { + return function (array, sortPredicate, reverseOrder) { + if (!(isArrayLike(array))) return array; + sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate]; + if (sortPredicate.length === 0) { + sortPredicate = ['+']; + } + sortPredicate = sortPredicate.map(function (predicate) { + var descending = false, get = predicate || identity; + if (isString(predicate)) { + if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { + descending = predicate.charAt(0) == '-'; + predicate = predicate.substring(1); + } + if (predicate === '') { + // Effectively no predicate was passed so we compare identity + return reverseComparator(function (a, b) { + return compare(a, b); + }, descending); + } + get = $parse(predicate); + if (get.constant) { + var key = get(); + return reverseComparator(function (a, b) { + return compare(a[key], b[key]); + }, descending); + } + } + return reverseComparator(function (a, b) { + return compare(get(a), get(b)); + }, descending); + }); + var arrayCopy = []; + for (var i = 0; i < array.length; i++) { + arrayCopy.push(array[i]); + } + return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); + + function comparator(o1, o2) { + for (var i = 0; i < sortPredicate.length; i++) { + var comp = sortPredicate[i](o1, o2); + if (comp !== 0) return comp; + } + return 0; + } + + function reverseComparator(comp, descending) { + return descending + ? function (a, b) { + return comp(b, a); + } + : comp; + } + + function compare(v1, v2) { + var t1 = typeof v1; + var t2 = typeof v2; + if (t1 == t2) { + if (isDate(v1) && isDate(v2)) { + v1 = v1.valueOf(); + v2 = v2.valueOf(); + } + if (t1 == "string") { + v1 = v1.toLowerCase(); + v2 = v2.toLowerCase(); + } + if (v1 === v2) return 0; + return v1 < v2 ? -1 : 1; + } else { + return t1 < t2 ? -1 : 1; + } + } + }; } - function compare(v1, v2){ - var t1 = typeof v1; - var t2 = typeof v2; - if (t1 == t2) { - if (isDate(v1) && isDate(v2)) { - v1 = v1.valueOf(); - v2 = v2.valueOf(); - } - if (t1 == "string") { - v1 = v1.toLowerCase(); - v2 = v2.toLowerCase(); + + function ngDirective(directive) { + if (isFunction(directive)) { + directive = { + link: directive + }; } - if (v1 === v2) return 0; - return v1 < v2 ? -1 : 1; - } else { - return t1 < t2 ? -1 : 1; - } + directive.restrict = directive.restrict || 'AC'; + return valueFn(directive); } - }; -} - -function ngDirective(directive) { - if (isFunction(directive)) { - directive = { - link: directive - }; - } - directive.restrict = directive.restrict || 'AC'; - return valueFn(directive); -} -/** - * @ngdoc directive - * @name a - * @restrict E - * - * @description - * Modifies the default behavior of the html A tag so that the default action is prevented when - * the href attribute is empty. - * - * This change permits the easy creation of action links with the `ngClick` directive - * without changing the location or causing page reloads, e.g.: - * `Add Item` - */ -var htmlAnchorDirective = valueFn({ - restrict: 'E', - compile: function(element, attr) { - if (!attr.href && !attr.xlinkHref && !attr.name) { - return function(scope, element) { - // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. - var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? - 'xlink:href' : 'href'; - element.on('click', function(event){ - // if we have no href url, then don't navigate anywhere. - if (!element.attr(href)) { - event.preventDefault(); - } - }); - }; - } - } -}); + /** + * @ngdoc directive + * @name a + * @restrict E + * + * @description + * Modifies the default behavior of the html A tag so that the default action is prevented when + * the href attribute is empty. + * + * This change permits the easy creation of action links with the `ngClick` directive + * without changing the location or causing page reloads, e.g.: + * `Add Item` + */ + var htmlAnchorDirective = valueFn({ + restrict: 'E', + compile: function (element, attr) { + if (!attr.href && !attr.xlinkHref && !attr.name) { + return function (scope, element) { + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. + var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? + 'xlink:href' : 'href'; + element.on('click', function (event) { + // if we have no href url, then don't navigate anywhere. + if (!element.attr(href)) { + event.preventDefault(); + } + }); + }; + } + } + }); -/** - * @ngdoc directive - * @name ngHref - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in an href attribute will - * make the link go to the wrong URL if the user clicks it before - * Angular has a chance to replace the `{{hash}}` markup with its - * value. Until Angular replaces the markup the link will be broken - * and will most likely return a 404 error. - * - * The `ngHref` directive solves this problem. - * - * The wrong way to write it: - * ```html - * link1 - * ``` - * - * The correct way to write it: - * ```html - * link1 - * ``` - * - * @element A - * @param {template} ngHref any string which can contain `{{}}` markup. - * - * @example - * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes - * in links and their different behaviors: - - -
          - link 1 (link, don't reload)
          - link 2 (link, don't reload)
          - link 3 (link, reload!)
          - anchor (link, don't reload)
          - anchor (no link)
          - link (link, change location) -
          - - it('should execute ng-click but not reload when href without value', function() { + /** + * @ngdoc directive + * @name ngHref + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in an href attribute will + * make the link go to the wrong URL if the user clicks it before + * Angular has a chance to replace the `{{hash}}` markup with its + * value. Until Angular replaces the markup the link will be broken + * and will most likely return a 404 error. + * + * The `ngHref` directive solves this problem. + * + * The wrong way to write it: + * ```html + * link1 + * ``` + * + * The correct way to write it: + * ```html + * link1 + * ``` + * + * @element A + * @param {template} ngHref any string which can contain `{{}}` markup. + * + * @example + * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes + * in links and their different behaviors: + + +
          + link 1 (link, don't reload)
          + link 2 (link, don't reload)
          + link 3 (link, reload!)
          + anchor (link, don't reload)
          + anchor (no link)
          + link (link, change location) +
          + + it('should execute ng-click but not reload when href without value', function() { element(by.id('link-1')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('1'); expect(element(by.id('link-1')).getAttribute('href')).toBe(''); }); - it('should execute ng-click but not reload when href empty string', function() { + it('should execute ng-click but not reload when href empty string', function() { element(by.id('link-2')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('2'); expect(element(by.id('link-2')).getAttribute('href')).toBe(''); }); - it('should execute ng-click and change url when ng-href specified', function() { + it('should execute ng-click and change url when ng-href specified', function() { expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); element(by.id('link-3')).click(); @@ -17469,19 +17598,19 @@ var htmlAnchorDirective = valueFn({ }, 5000, 'page should navigate to /123'); }); - xit('should execute ng-click but not reload when href empty string and name specified', function() { + xit('should execute ng-click but not reload when href empty string and name specified', function() { element(by.id('link-4')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('4'); expect(element(by.id('link-4')).getAttribute('href')).toBe(''); }); - it('should execute ng-click but not reload when no href but name specified', function() { + it('should execute ng-click but not reload when no href but name specified', function() { element(by.id('link-5')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('5'); expect(element(by.id('link-5')).getAttribute('href')).toBe(null); }); - it('should only change url when only ng-href', function() { + it('should only change url when only ng-href', function() { element(by.model('value')).clear(); element(by.model('value')).sendKeys('6'); expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); @@ -17496,750 +17625,750 @@ var htmlAnchorDirective = valueFn({ }); }, 5000, 'page should navigate to /6'); }); - -
          - */ +
          +
          + */ -/** - * @ngdoc directive - * @name ngSrc - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in a `src` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrc` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrc any string which can contain `{{}}` markup. - */ + /** + * @ngdoc directive + * @name ngSrc + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in a `src` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrc` directive solves this problem. + * + * The buggy way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element IMG + * @param {template} ngSrc any string which can contain `{{}}` markup. + */ -/** - * @ngdoc directive - * @name ngSrcset - * @restrict A - * @priority 99 - * - * @description - * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't - * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside - * `{{hash}}`. The `ngSrcset` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrcset any string which can contain `{{}}` markup. - */ + /** + * @ngdoc directive + * @name ngSrcset + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. + * + * The buggy way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ -/** - * @ngdoc directive - * @name ngDisabled - * @restrict A - * @priority 100 - * - * @description - * - * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: - * ```html - *
          - * - *
          - * ``` - * - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as disabled. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngDisabled` directive solves this problem for the `disabled` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * - * @example - - - Click me to toggle:
          - -
          - - it('should toggle button', function() { + /** + * @ngdoc directive + * @name ngDisabled + * @restrict A + * @priority 100 + * + * @description + * + * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: + * ```html + *
          + * + *
          + * ``` + * + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as disabled. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngDisabled` directive solves this problem for the `disabled` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * + * @example + + + Click me to toggle:
          + +
          + + it('should toggle button', function() { expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); - -
          - * - * @element INPUT - * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, - * then special attribute "disabled" will be set on the element - */ +
          +
          + * + * @element INPUT + * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, + * then special attribute "disabled" will be set on the element + */ -/** - * @ngdoc directive - * @name ngChecked - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as checked. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngChecked` directive solves this problem for the `checked` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example - - - Check me to check both:
          - -
          - - it('should check both checkBoxes', function() { + /** + * @ngdoc directive + * @name ngChecked + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as checked. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngChecked` directive solves this problem for the `checked` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me to check both:
          + +
          + + it('should check both checkBoxes', function() { expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); element(by.model('master')).click(); expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); - -
          - * - * @element INPUT - * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, - * then special attribute "checked" will be set on the element - */ +
          +
          + * + * @element INPUT + * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, + * then special attribute "checked" will be set on the element + */ -/** - * @ngdoc directive - * @name ngReadonly - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as readonly. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngReadonly` directive solves this problem for the `readonly` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example - - - Check me to make text readonly:
          - -
          - - it('should toggle readonly attr', function() { + /** + * @ngdoc directive + * @name ngReadonly + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as readonly. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngReadonly` directive solves this problem for the `readonly` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me to make text readonly:
          + +
          + + it('should toggle readonly attr', function() { expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); }); - -
          - * - * @element INPUT - * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, - * then special attribute "readonly" will be set on the element - */ +
          +
          + * + * @element INPUT + * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, + * then special attribute "readonly" will be set on the element + */ -/** - * @ngdoc directive - * @name ngSelected - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as selected. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngSelected` directive solves this problem for the `selected` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * - * @example - - - Check me to select:
          - -
          - - it('should select Greetings!', function() { + /** + * @ngdoc directive + * @name ngSelected + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as selected. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngSelected` directive solves this problem for the `selected` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * + * @example + + + Check me to select:
          + +
          + + it('should select Greetings!', function() { expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); element(by.model('selected')).click(); expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); }); - -
          - * - * @element OPTION - * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, - * then special attribute "selected" will be set on the element - */ +
          +
          + * + * @element OPTION + * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, + * then special attribute "selected" will be set on the element + */ -/** - * @ngdoc directive - * @name ngOpen - * @restrict A - * @priority 100 - * - * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as open. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngOpen` directive solves this problem for the `open` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. - * @example + /** + * @ngdoc directive + * @name ngOpen + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as open. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngOpen` directive solves this problem for the `open` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example - - Check me check multiple:
          -
          - Show/Hide me -
          -
          - - it('should toggle open', function() { + + Check me check multiple:
          +
          + Show/Hide me +
          +
          + + it('should toggle open', function() { expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); element(by.model('open')).click(); expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); }); - +
          - * - * @element DETAILS - * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, - * then special attribute "open" will be set on the element - */ + * + * @element DETAILS + * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, + * then special attribute "open" will be set on the element + */ -var ngAttributeAliasDirectives = {}; + var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated -forEach(BOOLEAN_ATTR, function(propName, attrName) { - // binding to multiple is not supported - if (propName == "multiple") return; - - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - restrict: 'A', - priority: 100, - link: function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); - }); - } - }; - }; -}); - -// aliased input attrs are evaluated -forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { - ngAttributeAliasDirectives[ngAttr] = function() { - return { - priority: 100, - link: function(scope, element, attr) { - //special case ngPattern when a literal regular expression value - //is used as the expression (this way we don't have to watch anything). - if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") { - var match = attr.ngPattern.match(REGEX_STRING_REGEXP); - if (match) { - attr.$set("ngPattern", new RegExp(match[1], match[2])); - return; - } - } + forEach(BOOLEAN_ATTR, function (propName, attrName) { + // binding to multiple is not supported + if (propName == "multiple") return; - scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { - attr.$set(ngAttr, value); - }); - } - }; - }; -}); + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = function () { + return { + restrict: 'A', + priority: 100, + link: function (scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); + } + }; + }; + }); -// ng-src, ng-srcset, ng-href are interpolated -forEach(['src', 'srcset', 'href'], function(attrName) { - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 99, // it needs to run after the attributes are interpolated - link: function(scope, element, attr) { - var propName = attrName, - name = attrName; - - if (attrName === 'href' && - toString.call(element.prop('href')) === '[object SVGAnimatedString]') { - name = 'xlinkHref'; - attr.$attr[name] = 'xlink:href'; - propName = null; - } +// aliased input attrs are evaluated + forEach(ALIASED_ATTR, function (htmlAttr, ngAttr) { + ngAttributeAliasDirectives[ngAttr] = function () { + return { + priority: 100, + link: function (scope, element, attr) { + //special case ngPattern when a literal regular expression value + //is used as the expression (this way we don't have to watch anything). + if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") { + var match = attr.ngPattern.match(REGEX_STRING_REGEXP); + if (match) { + attr.$set("ngPattern", new RegExp(match[1], match[2])); + return; + } + } - attr.$observe(normalized, function(value) { - if (!value) { - if (attrName === 'href') { - attr.$set(name, null); - } - return; - } + scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { + attr.$set(ngAttr, value); + }); + } + }; + }; + }); - attr.$set(name, value); +// ng-src, ng-srcset, ng-href are interpolated + forEach(['src', 'srcset', 'href'], function (attrName) { + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = function () { + return { + priority: 99, // it needs to run after the attributes are interpolated + link: function (scope, element, attr) { + var propName = attrName, + name = attrName; + + if (attrName === 'href' && + toString.call(element.prop('href')) === '[object SVGAnimatedString]') { + name = 'xlinkHref'; + attr.$attr[name] = 'xlink:href'; + propName = null; + } - // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist - // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need - // to set the property as well to achieve the desired effect. - // we use attr[attrName] value since $set can sanitize the url. - if (msie && propName) element.prop(propName, attr[name]); - }); - } - }; - }; -}); + attr.$observe(normalized, function (value) { + if (!value) { + if (attrName === 'href') { + attr.$set(name, null); + } + return; + } + + attr.$set(name, value); + + // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist + // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need + // to set the property as well to achieve the desired effect. + // we use attr[attrName] value since $set can sanitize the url. + if (msie && propName) element.prop(propName, attr[name]); + }); + } + }; + }; + }); -/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true - */ -var nullFormCtrl = { - $addControl: noop, - $$renameControl: nullFormRenameControl, - $removeControl: noop, - $setValidity: noop, - $setDirty: noop, - $setPristine: noop, - $setSubmitted: noop -}, -SUBMITTED_CLASS = 'ng-submitted'; - -function nullFormRenameControl(control, name) { - control.$name = name; -} + /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true + */ + var nullFormCtrl = { + $addControl: noop, + $$renameControl: nullFormRenameControl, + $removeControl: noop, + $setValidity: noop, + $setDirty: noop, + $setPristine: noop, + $setSubmitted: noop + }, + SUBMITTED_CLASS = 'ng-submitted'; -/** - * @ngdoc type - * @name form.FormController - * - * @property {boolean} $pristine True if user has not interacted with the form yet. - * @property {boolean} $dirty True if user has already interacted with the form. - * @property {boolean} $valid True if all of the containing forms and controls are valid. - * @property {boolean} $invalid True if at least one containing control or form is invalid. - * @property {boolean} $submitted True if user has submitted the form even if its invalid. - * - * @property {Object} $error Is an object hash, containing references to controls or - * forms with failing validators, where: - * - * - keys are validation tokens (error names), - * - values are arrays of controls or forms that have a failing validator for given error name. - * - * Built-in validation tokens: - * - * - `email` - * - `max` - * - `maxlength` - * - `min` - * - `minlength` - * - `number` - * - `pattern` - * - `required` - * - `url` - * - * @description - * `FormController` keeps track of all its controls and nested forms as well as the state of them, - * such as being valid/invalid or dirty/pristine. - * - * Each {@link ng.directive:form form} directive creates an instance - * of `FormController`. - * - */ + function nullFormRenameControl(control, name) { + control.$name = name; + } + + /** + * @ngdoc type + * @name form.FormController + * + * @property {boolean} $pristine True if user has not interacted with the form yet. + * @property {boolean} $dirty True if user has already interacted with the form. + * @property {boolean} $valid True if all of the containing forms and controls are valid. + * @property {boolean} $invalid True if at least one containing control or form is invalid. + * @property {boolean} $submitted True if user has submitted the form even if its invalid. + * + * @property {Object} $error Is an object hash, containing references to controls or + * forms with failing validators, where: + * + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that have a failing validator for given error name. + * + * Built-in validation tokens: + * + * - `email` + * - `max` + * - `maxlength` + * - `min` + * - `minlength` + * - `number` + * - `pattern` + * - `required` + * - `url` + * + * @description + * `FormController` keeps track of all its controls and nested forms as well as the state of them, + * such as being valid/invalid or dirty/pristine. + * + * Each {@link ng.directive:form form} directive creates an instance + * of `FormController`. + * + */ //asks for $scope to fool the BC controller module -FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; -function FormController(element, attrs, $scope, $animate, $interpolate) { - var form = this, - controls = []; - - var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; - - // init state - form.$error = {}; - form.$$success = {}; - form.$pending = undefined; - form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope); - form.$dirty = false; - form.$pristine = true; - form.$valid = true; - form.$invalid = false; - form.$submitted = false; - - parentForm.$addControl(form); - - /** - * @ngdoc method - * @name form.FormController#$rollbackViewValue - * - * @description - * Rollback all form controls pending updates to the `$modelValue`. - * - * Updates may be pending by a debounced event or because the input is waiting for a some future - * event defined in `ng-model-options`. This method is typically needed by the reset button of - * a form that uses `ng-model-options` to pend updates. - */ - form.$rollbackViewValue = function() { - forEach(controls, function(control) { - control.$rollbackViewValue(); - }); - }; + FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; + function FormController(element, attrs, $scope, $animate, $interpolate) { + var form = this, + controls = []; + + var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; + + // init state + form.$error = {}; + form.$$success = {}; + form.$pending = undefined; + form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope); + form.$dirty = false; + form.$pristine = true; + form.$valid = true; + form.$invalid = false; + form.$submitted = false; + + parentForm.$addControl(form); - /** - * @ngdoc method - * @name form.FormController#$commitViewValue - * - * @description - * Commit all form controls pending updates to the `$modelValue`. - * - * Updates may be pending by a debounced event or because the input is waiting for a some future - * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` - * usually handles calling this in response to input events. - */ - form.$commitViewValue = function() { - forEach(controls, function(control) { - control.$commitViewValue(); - }); - }; + /** + * @ngdoc method + * @name form.FormController#$rollbackViewValue + * + * @description + * Rollback all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is typically needed by the reset button of + * a form that uses `ng-model-options` to pend updates. + */ + form.$rollbackViewValue = function () { + forEach(controls, function (control) { + control.$rollbackViewValue(); + }); + }; - /** - * @ngdoc method - * @name form.FormController#$addControl - * - * @description - * Register a control with the form. - * - * Input elements using ngModelController do this automatically when they are linked. - */ - form.$addControl = function(control) { - // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored - // and not added to the scope. Now we throw an error. - assertNotHasOwnProperty(control.$name, 'input'); - controls.push(control); - - if (control.$name) { - form[control.$name] = control; - } - }; + /** + * @ngdoc method + * @name form.FormController#$commitViewValue + * + * @description + * Commit all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + form.$commitViewValue = function () { + forEach(controls, function (control) { + control.$commitViewValue(); + }); + }; - // Private API: rename a form control - form.$$renameControl = function(control, newName) { - var oldName = control.$name; + /** + * @ngdoc method + * @name form.FormController#$addControl + * + * @description + * Register a control with the form. + * + * Input elements using ngModelController do this automatically when they are linked. + */ + form.$addControl = function (control) { + // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored + // and not added to the scope. Now we throw an error. + assertNotHasOwnProperty(control.$name, 'input'); + controls.push(control); + + if (control.$name) { + form[control.$name] = control; + } + }; - if (form[oldName] === control) { - delete form[oldName]; - } - form[newName] = control; - control.$name = newName; - }; + // Private API: rename a form control + form.$$renameControl = function (control, newName) { + var oldName = control.$name; - /** - * @ngdoc method - * @name form.FormController#$removeControl - * - * @description - * Deregister a control from the form. - * - * Input elements using ngModelController do this automatically when they are destroyed. - */ - form.$removeControl = function(control) { - if (control.$name && form[control.$name] === control) { - delete form[control.$name]; - } - forEach(form.$pending, function(value, name) { - form.$setValidity(name, null, control); - }); - forEach(form.$error, function(value, name) { - form.$setValidity(name, null, control); - }); + if (form[oldName] === control) { + delete form[oldName]; + } + form[newName] = control; + control.$name = newName; + }; - arrayRemove(controls, control); - }; + /** + * @ngdoc method + * @name form.FormController#$removeControl + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + */ + form.$removeControl = function (control) { + if (control.$name && form[control.$name] === control) { + delete form[control.$name]; + } + forEach(form.$pending, function (value, name) { + form.$setValidity(name, null, control); + }); + forEach(form.$error, function (value, name) { + form.$setValidity(name, null, control); + }); + arrayRemove(controls, control); + }; - /** - * @ngdoc method - * @name form.FormController#$setValidity - * - * @description - * Sets the validity of a form control. - * - * This method will also propagate to parent forms. - */ - addSetValidityMethod({ - ctrl: this, - $element: element, - set: function(object, property, control) { - var list = object[property]; - if (!list) { - object[property] = [control]; - } else { - var index = list.indexOf(control); - if (index === -1) { - list.push(control); - } - } - }, - unset: function(object, property, control) { - var list = object[property]; - if (!list) { - return; - } - arrayRemove(list, control); - if (list.length === 0) { - delete object[property]; - } - }, - parentForm: parentForm, - $animate: $animate - }); - /** - * @ngdoc method - * @name form.FormController#$setDirty - * - * @description - * Sets the form to a dirty state. - * - * This method can be called to add the 'ng-dirty' class and set the form to a dirty - * state (ng-dirty class). This method will also propagate to parent forms. - */ - form.$setDirty = function() { - $animate.removeClass(element, PRISTINE_CLASS); - $animate.addClass(element, DIRTY_CLASS); - form.$dirty = true; - form.$pristine = false; - parentForm.$setDirty(); - }; - - /** - * @ngdoc method - * @name form.FormController#$setPristine - * - * @description - * Sets the form to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the form to its pristine - * state (ng-pristine class). This method will also propagate to all the controls contained - * in this form. - * - * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after - * saving or resetting it. - */ - form.$setPristine = function () { - $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); - form.$dirty = false; - form.$pristine = true; - form.$submitted = false; - forEach(controls, function(control) { - control.$setPristine(); - }); - }; + /** + * @ngdoc method + * @name form.FormController#$setValidity + * + * @description + * Sets the validity of a form control. + * + * This method will also propagate to parent forms. + */ + addSetValidityMethod({ + ctrl: this, + $element: element, + set: function (object, property, control) { + var list = object[property]; + if (!list) { + object[property] = [control]; + } else { + var index = list.indexOf(control); + if (index === -1) { + list.push(control); + } + } + }, + unset: function (object, property, control) { + var list = object[property]; + if (!list) { + return; + } + arrayRemove(list, control); + if (list.length === 0) { + delete object[property]; + } + }, + parentForm: parentForm, + $animate: $animate + }); - /** - * @ngdoc method - * @name form.FormController#$setUntouched - * - * @description - * Sets the form to its untouched state. - * - * This method can be called to remove the 'ng-touched' class and set the form controls to their - * untouched state (ng-untouched class). - * - * Setting a form controls back to their untouched state is often useful when setting the form - * back to its pristine state. - */ - form.$setUntouched = function () { - forEach(controls, function(control) { - control.$setUntouched(); - }); - }; + /** + * @ngdoc method + * @name form.FormController#$setDirty + * + * @description + * Sets the form to a dirty state. + * + * This method can be called to add the 'ng-dirty' class and set the form to a dirty + * state (ng-dirty class). This method will also propagate to parent forms. + */ + form.$setDirty = function () { + $animate.removeClass(element, PRISTINE_CLASS); + $animate.addClass(element, DIRTY_CLASS); + form.$dirty = true; + form.$pristine = false; + parentForm.$setDirty(); + }; - /** - * @ngdoc method - * @name form.FormController#$setSubmitted - * - * @description - * Sets the form to its submitted state. - */ - form.$setSubmitted = function () { - $animate.addClass(element, SUBMITTED_CLASS); - form.$submitted = true; - parentForm.$setSubmitted(); - }; -} + /** + * @ngdoc method + * @name form.FormController#$setPristine + * + * @description + * Sets the form to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the form to its pristine + * state (ng-pristine class). This method will also propagate to all the controls contained + * in this form. + * + * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after + * saving or resetting it. + */ + form.$setPristine = function () { + $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); + form.$dirty = false; + form.$pristine = true; + form.$submitted = false; + forEach(controls, function (control) { + control.$setPristine(); + }); + }; -/** - * @ngdoc directive - * @name ngForm - * @restrict EAC - * - * @description - * Nestable alias of {@link ng.directive:form `form`} directive. HTML - * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a - * sub-group of controls needs to be determined. - * - * Note: the purpose of `ngForm` is to group controls, - * but not to be a replacement for the `
          ` tag with all of its capabilities - * (e.g. posting to the server, ...). - * - * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into - * related scope, under this name. - * - */ + /** + * @ngdoc method + * @name form.FormController#$setUntouched + * + * @description + * Sets the form to its untouched state. + * + * This method can be called to remove the 'ng-touched' class and set the form controls to their + * untouched state (ng-untouched class). + * + * Setting a form controls back to their untouched state is often useful when setting the form + * back to its pristine state. + */ + form.$setUntouched = function () { + forEach(controls, function (control) { + control.$setUntouched(); + }); + }; - /** - * @ngdoc directive - * @name form - * @restrict E - * - * @description - * Directive that instantiates - * {@link form.FormController FormController}. - * - * If the `name` attribute is specified, the form controller is published onto the current scope under - * this name. - * - * # Alias: {@link ng.directive:ngForm `ngForm`} - * - * In Angular forms can be nested. This means that the outer form is valid when all of the child - * forms are valid as well. However, browsers do not allow nesting of `` elements, so - * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to - * `` but can be nested. This allows you to have nested forms, which is very useful when - * using Angular validation directives in forms that are dynamically generated using the - * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` - * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an - * `ngForm` directive and nest these in an outer `form` element. - * - * - * # CSS classes - * - `ng-valid` is set if the form is valid. - * - `ng-invalid` is set if the form is invalid. - * - `ng-pristine` is set if the form is pristine. - * - `ng-dirty` is set if the form is dirty. - * - `ng-submitted` is set if the form was submitted. - * - * Keep in mind that ngAnimate can detect each of these classes when added and removed. - * - * - * # Submitting a form and preventing the default action - * - * Since the role of forms in client-side Angular applications is different than in classical - * roundtrip apps, it is desirable for the browser not to translate the form submission into a full - * page reload that sends the data to the server. Instead some javascript logic should be triggered - * to handle the form submission in an application-specific way. - * - * For this reason, Angular prevents the default action (form submission to the server) unless the - * `` element has an `action` attribute specified. - * - * You can use one of the following two ways to specify what javascript method should be called when - * a form is submitted: - * - * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element - * - {@link ng.directive:ngClick ngClick} directive on the first - * button or input field of type submit (input[type=submit]) - * - * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} - * or {@link ng.directive:ngClick ngClick} directives. - * This is because of the following form submission rules in the HTML specification: - * - * - If a form has only one input field then hitting enter in this field triggers form submit - * (`ngSubmit`) - * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter - * doesn't trigger submit - * - if a form has one or more input fields and one or more buttons or input[type=submit] then - * hitting enter in any of the input fields will trigger the click handler on the *first* button or - * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) - * - * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is - * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` - * to have access to the updated model. - * - * ## Animation Hooks - * - * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. - * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any - * other validations that are performed within the form. Animations in ngForm are similar to how - * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well - * as JS animations. - * - * The following example shows a simple way to utilize CSS transitions to style a form element - * that has been rendered as invalid after it has been validated: - * - *
          - * //be sure to include ngAnimate as a module to hook into more
          - * //advanced animations
          - * .my-form {
          +        /**
          +         * @ngdoc method
          +         * @name form.FormController#$setSubmitted
          +         *
          +         * @description
          +         * Sets the form to its submitted state.
          +         */
          +        form.$setSubmitted = function () {
          +            $animate.addClass(element, SUBMITTED_CLASS);
          +            form.$submitted = true;
          +            parentForm.$setSubmitted();
          +        };
          +    }
          +
          +    /**
          +     * @ngdoc directive
          +     * @name ngForm
          +     * @restrict EAC
          +     *
          +     * @description
          +     * Nestable alias of {@link ng.directive:form `form`} directive. HTML
          +     * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
          +     * sub-group of controls needs to be determined.
          +     *
          +     * Note: the purpose of `ngForm` is to group controls,
          +     * but not to be a replacement for the `` tag with all of its capabilities
          +     * (e.g. posting to the server, ...).
          +     *
          +     * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
          +     *                       related scope, under this name.
          +     *
          +     */
          +
          +    /**
          +     * @ngdoc directive
          +     * @name form
          +     * @restrict E
          +     *
          +     * @description
          +     * Directive that instantiates
          +     * {@link form.FormController FormController}.
          +     *
          +     * If the `name` attribute is specified, the form controller is published onto the current scope under
          +     * this name.
          +     *
          +     * # Alias: {@link ng.directive:ngForm `ngForm`}
          +     *
          +     * In Angular forms can be nested. This means that the outer form is valid when all of the child
          +     * forms are valid as well. However, browsers do not allow nesting of `` elements, so
          +     * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
          +     * `` but can be nested.  This allows you to have nested forms, which is very useful when
          +     * using Angular validation directives in forms that are dynamically generated using the
          +     * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
          +     * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
          +     * `ngForm` directive and nest these in an outer `form` element.
          +     *
          +     *
          +     * # CSS classes
          +     *  - `ng-valid` is set if the form is valid.
          +     *  - `ng-invalid` is set if the form is invalid.
          +     *  - `ng-pristine` is set if the form is pristine.
          +     *  - `ng-dirty` is set if the form is dirty.
          +     *  - `ng-submitted` is set if the form was submitted.
          +     *
          +     * Keep in mind that ngAnimate can detect each of these classes when added and removed.
          +     *
          +     *
          +     * # Submitting a form and preventing the default action
          +     *
          +     * Since the role of forms in client-side Angular applications is different than in classical
          +     * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
          +     * page reload that sends the data to the server. Instead some javascript logic should be triggered
          +     * to handle the form submission in an application-specific way.
          +     *
          +     * For this reason, Angular prevents the default action (form submission to the server) unless the
          +     * `` element has an `action` attribute specified.
          +     *
          +     * You can use one of the following two ways to specify what javascript method should be called when
          +     * a form is submitted:
          +     *
          +     * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
          +     * - {@link ng.directive:ngClick ngClick} directive on the first
          +     *  button or input field of type submit (input[type=submit])
          +     *
          +     * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
          +     * or {@link ng.directive:ngClick ngClick} directives.
          +     * This is because of the following form submission rules in the HTML specification:
          +     *
          +     * - If a form has only one input field then hitting enter in this field triggers form submit
          +     * (`ngSubmit`)
          +     * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
          +     * doesn't trigger submit
          +     * - if a form has one or more input fields and one or more buttons or input[type=submit] then
          +     * hitting enter in any of the input fields will trigger the click handler on the *first* button or
          +     * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
          +     *
          +     * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
          +     * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
          +     * to have access to the updated model.
          +     *
          +     * ## Animation Hooks
          +     *
          +     * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
          +     * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
          +     * other validations that are performed within the form. Animations in ngForm are similar to how
          +     * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
          +     * as JS animations.
          +     *
          +     * The following example shows a simple way to utilize CSS transitions to style a form element
          +     * that has been rendered as invalid after it has been validated:
          +     *
          +     * 
          +     * //be sure to include ngAnimate as a module to hook into more
          +     * //advanced animations
          +     * .my-form {
            *   transition:0.5s linear all;
            *   background: white;
            * }
          - * .my-form.ng-invalid {
          +     * .my-form.ng-invalid {
            *   background: red;
            *   color:white;
            * }
          - * 
          - * - * @example - - - - - - userType: - Required!
          - userType = {{userType}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          - -
          - - it('should initialize to model', function() { + +
          + userType: + Required!
          + userType = {{userType}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + it('should initialize to model', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); @@ -18247,7 +18376,7 @@ function FormController(element, attrs, $scope, $animate, $interpolate) { expect(valid.getText()).toContain('true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); var userInput = element(by.model('userType')); @@ -18258,174 +18387,174 @@ function FormController(element, attrs, $scope, $animate, $interpolate) { expect(userType.getText()).toEqual('userType ='); expect(valid.getText()).toContain('false'); }); - -
          - * - * @param {string=} name Name of the form. If specified, the form controller will be published into - * related scope, under this name. - */ -var formDirectiveFactory = function(isNgForm) { - return ['$timeout', function($timeout) { - var formDirective = { - name: 'form', - restrict: isNgForm ? 'EAC' : 'E', - controller: FormController, - compile: function ngFormCompile(formElement) { - // Setup initial state of the control - formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); - - return { - pre: function ngFormPreLink(scope, formElement, attr, controller) { - // if `action` attr is not present on the form, prevent the default action (submission) - if (!('action' in attr)) { - // we can't use jq events because if a form is destroyed during submission the default - // action is not prevented. see #1238 - // - // IE 9 is not affected because it doesn't fire a submit event and try to do a full - // page reload if the form was destroyed by submission of the form via a click handler - // on a button in the form. Looks like an IE9 specific bug. - var handleFormSubmission = function(event) { - scope.$apply(function() { - controller.$commitViewValue(); - controller.$setSubmitted(); - }); - - event.preventDefault - ? event.preventDefault() - : event.returnValue = false; // IE - }; - - addEventListenerFn(formElement[0], 'submit', handleFormSubmission); + + + * + * @param {string=} name Name of the form. If specified, the form controller will be published into + * related scope, under this name. + */ + var formDirectiveFactory = function (isNgForm) { + return ['$timeout', function ($timeout) { + var formDirective = { + name: 'form', + restrict: isNgForm ? 'EAC' : 'E', + controller: FormController, + compile: function ngFormCompile(formElement) { + // Setup initial state of the control + formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); + + return { + pre: function ngFormPreLink(scope, formElement, attr, controller) { + // if `action` attr is not present on the form, prevent the default action (submission) + if (!('action' in attr)) { + // we can't use jq events because if a form is destroyed during submission the default + // action is not prevented. see #1238 + // + // IE 9 is not affected because it doesn't fire a submit event and try to do a full + // page reload if the form was destroyed by submission of the form via a click handler + // on a button in the form. Looks like an IE9 specific bug. + var handleFormSubmission = function (event) { + scope.$apply(function () { + controller.$commitViewValue(); + controller.$setSubmitted(); + }); + + event.preventDefault + ? event.preventDefault() + : event.returnValue = false; // IE + }; + + addEventListenerFn(formElement[0], 'submit', handleFormSubmission); + + // unregister the preventDefault listener so that we don't not leak memory but in a + // way that will achieve the prevention of the default action. + formElement.on('$destroy', function () { + $timeout(function () { + removeEventListenerFn(formElement[0], 'submit', handleFormSubmission); + }, 0, false); + }); + } + + var parentFormCtrl = controller.$$parentForm, + alias = controller.$name; + + if (alias) { + setter(scope, alias, controller, alias); + attr.$observe(attr.name ? 'name' : 'ngForm', function (newValue) { + if (alias === newValue) return; + setter(scope, alias, undefined, alias); + alias = newValue; + setter(scope, alias, controller, alias); + parentFormCtrl.$$renameControl(controller, alias); + }); + } + formElement.on('$destroy', function () { + parentFormCtrl.$removeControl(controller); + if (alias) { + setter(scope, alias, undefined, alias); + } + extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + }); + } + }; + } + }; - // unregister the preventDefault listener so that we don't not leak memory but in a - // way that will achieve the prevention of the default action. - formElement.on('$destroy', function() { - $timeout(function() { - removeEventListenerFn(formElement[0], 'submit', handleFormSubmission); - }, 0, false); - }); - } + return formDirective; + }]; + }; - var parentFormCtrl = controller.$$parentForm, - alias = controller.$name; + var formDirective = formDirectiveFactory(); + var ngFormDirective = formDirectiveFactory(true); - if (alias) { - setter(scope, alias, controller, alias); - attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) { - if (alias === newValue) return; - setter(scope, alias, undefined, alias); - alias = newValue; - setter(scope, alias, controller, alias); - parentFormCtrl.$$renameControl(controller, alias); - }); - } - formElement.on('$destroy', function() { - parentFormCtrl.$removeControl(controller); - if (alias) { - setter(scope, alias, undefined, alias); - } - extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards - }); - } - }; - } - }; + /* global VALID_CLASS: true, + INVALID_CLASS: true, + PRISTINE_CLASS: true, + DIRTY_CLASS: true, + UNTOUCHED_CLASS: true, + TOUCHED_CLASS: true, + */ - return formDirective; - }]; -}; +// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 + var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/; + var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; + var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; + var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; + var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; + var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; + var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/; + var MONTH_REGEXP = /^(\d{4})-(\d\d)$/; + var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; + var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; -var formDirective = formDirectiveFactory(); -var ngFormDirective = formDirectiveFactory(true); + var $ngModelMinErr = new minErr('ngModel'); -/* global VALID_CLASS: true, - INVALID_CLASS: true, - PRISTINE_CLASS: true, - DIRTY_CLASS: true, - UNTOUCHED_CLASS: true, - TOUCHED_CLASS: true, -*/ + var inputType = { -// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 -var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/; -var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; -var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; -var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; -var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; -var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; -var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/; -var MONTH_REGEXP = /^(\d{4})-(\d\d)$/; -var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; -var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; - -var $ngModelMinErr = new minErr('ngModel'); - -var inputType = { - - /** - * @ngdoc input - * @name input[text] - * - * @description - * Standard HTML text input with angular data binding, inherited by most of the `input` elements. - * - * *NOTE* Not every feature offered is available for all input types. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Adds `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. - * This parameter is ignored for input[type=password] controls, which will never trim the - * input. - * - * @example - - + /** + * @ngdoc input + * @name input[text] + * + * @description + * Standard HTML text input with angular data binding, inherited by most of the `input` elements. + * + * *NOTE* Not every feature offered is available for all input types. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Adds `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + * This parameter is ignored for input[type=password] controls, which will never trim the + * input. + * + * @example + +
          - Single word: - - Required! - - Single word only! - - text = {{text}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var text = element(by.binding('text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + Single word: + + Required! + + Single word only! + + text = {{text}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          + +
          + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); - it('should initialize to model', function() { + it('should initialize to model', function() { expect(text.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); @@ -18433,77 +18562,77 @@ var inputType = { expect(valid.getText()).toContain('false'); }); - it('should be invalid if multi word', function() { + it('should be invalid if multi word', function() { input.clear(); input.sendKeys('hello world'); expect(valid.getText()).toContain('false'); }); - -
          - */ - 'text': textInputType, +
          +
          + */ + 'text': textInputType, - /** - * @ngdoc input - * @name input[date] - * - * @description - * Input with date validation and transformation. In browsers that do not yet support - * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 - * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many - * modern browsers do not yet support this input type, it is important to provide cues to users on the - * expected input format via a placeholder or label. The model must always be a Date object. - * - * The timezone to be used to read/write the `Date` instance in the model can be defined using - * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a - * valid ISO date string (yyyy-MM-dd). - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be - * a valid ISO date string (yyyy-MM-dd). - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
          - Pick a date in 2013: - - - Required! - - Not a valid date! - value = {{value | date: "yyyy-MM-dd"}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value | date: "yyyy-MM-dd"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); - - // currently protractor/webdriver does not support - // sending keys to all known HTML5 input controls - // for various browsers (see https://github.com/angular/protractor/issues/562). - function setInput(val) { + +
          + Pick a date in 2013: + + + Required! + + Not a valid date! + value = {{value | date: "yyyy-MM-dd"}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + var value = element(by.binding('value | date: "yyyy-MM-dd"')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (see https://github.com/angular/protractor/issues/562). + function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + @@ -18511,87 +18640,87 @@ var inputType = { browser.executeScript(scr); } - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('2013-10-22'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { setInput('2015-01-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
          - */ - 'date': createDateInputType('date', DATE_REGEXP, - createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), - 'yyyy-MM-dd'), - - /** - * @ngdoc input - * @name input[dateTimeLocal] - * - * @description - * Input with datetime validation and transformation. In browsers that do not yet support - * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. The model must be a Date object. - * - * The timezone to be used to read/write the `Date` instance in the model can be defined using - * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a - * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be - * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
          - Pick a date between in 2013: - - - Required! - - Not a valid date! - value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); - - // currently protractor/webdriver does not support - // sending keys to all known HTML5 input controls - // for various browsers (https://github.com/angular/protractor/issues/562). - function setInput(val) { + +
          + Pick a date between in 2013: + + + Required! + + Not a valid date! + value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + @@ -18599,88 +18728,88 @@ var inputType = { browser.executeScript(scr); } - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('2010-12-28T14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { setInput('2015-01-01T23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
          - */ - 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, - createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), - 'yyyy-MM-ddTHH:mm:ss.sss'), - - /** - * @ngdoc input - * @name input[time] - * - * @description - * Input with time validation and transformation. In browsers that do not yet support - * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a - * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. - * - * The timezone to be used to read/write the `Date` instance in the model can be defined using - * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a - * valid ISO time format (HH:mm:ss). - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a - * valid ISO time format (HH:mm:ss). - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
          - Pick a between 8am and 5pm: - - - Required! - - Not a valid date! - value = {{value | date: "HH:mm:ss"}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value | date: "HH:mm:ss"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); - - // currently protractor/webdriver does not support - // sending keys to all known HTML5 input controls - // for various browsers (https://github.com/angular/protractor/issues/562). - function setInput(val) { + +
          + Pick a between 8am and 5pm: + + + Required! + + Not a valid date! + value = {{value | date: "HH:mm:ss"}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + var value = element(by.binding('value | date: "HH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + @@ -18688,87 +18817,87 @@ var inputType = { browser.executeScript(scr); } - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { setInput('23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
          - */ - 'time': createDateInputType('time', TIME_REGEXP, - createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), - 'HH:mm:ss.sss'), - - /** - * @ngdoc input - * @name input[week] - * - * @description - * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support - * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object. - * - * The timezone to be used to read/write the `Date` instance in the model can be defined using - * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a - * valid ISO week format (yyyy-W##). - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be - * a valid ISO week format (yyyy-W##). - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
          - Pick a date between in 2013: - - - Required! - - Not a valid date! - value = {{value | date: "yyyy-Www"}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value | date: "yyyy-Www"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); - - // currently protractor/webdriver does not support - // sending keys to all known HTML5 input controls - // for various browsers (https://github.com/angular/protractor/issues/562). - function setInput(val) { + +
          + Pick a date between in 2013: + + + Required! + + Not a valid date! + value = {{value | date: "yyyy-Www"}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + var value = element(by.binding('value | date: "yyyy-Www"')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + @@ -18776,86 +18905,86 @@ var inputType = { browser.executeScript(scr); } - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('2013-W01'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { setInput('2015-W01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
          - */ - 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), - - /** - * @ngdoc input - * @name input[month] - * - * @description - * Input with month validation and transformation. In browsers that do not yet support - * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 - * month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is - * not set to the first of the month, the first of that model's month is assumed. - * - * The timezone to be used to read/write the `Date` instance in the model can be defined using - * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be - * a valid ISO month format (yyyy-MM). - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must - * be a valid ISO month format (yyyy-MM). - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
          - Pick a month int 2013: - - - Required! - - Not a valid month! - value = {{value | date: "yyyy-MM"}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value | date: "yyyy-MM"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); - - // currently protractor/webdriver does not support - // sending keys to all known HTML5 input controls - // for various browsers (https://github.com/angular/protractor/issues/562). - function setInput(val) { + +
          + Pick a month int 2013: + + + Required! + + Not a valid month! + value = {{value | date: "yyyy-MM"}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          +
          +
          + + var value = element(by.binding('value | date: "yyyy-MM"')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + @@ -18863,165 +18992,165 @@ var inputType = { browser.executeScript(scr); } - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('2013-10'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { setInput('2015-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); - -
          - */ - 'month': createDateInputType('month', MONTH_REGEXP, - createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), - 'yyyy-MM'), - - /** - * @ngdoc input - * @name input[number] - * - * @description - * Text input with number validation and transformation. Sets the `number` validation - * error if not a valid number. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - + + + */ + 'month': createDateInputType('month', MONTH_REGEXP, + createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), + 'yyyy-MM'), + + /** + * @ngdoc input + * @name input[number] + * + * @description + * Text input with number validation and transformation. Sets the `number` validation + * error if not a valid number. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + +
          - Number: - - Required! - - Not valid number! - value = {{value}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          -
          -
          - - var value = element(by.binding('value')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); + Number: + + Required! + + Not valid number! + value = {{value}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          + +
          + + var value = element(by.binding('value')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); - it('should initialize to model', function() { + it('should initialize to model', function() { expect(value.getText()).toContain('12'); expect(valid.getText()).toContain('true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); - it('should be invalid if over max', function() { + it('should be invalid if over max', function() { input.clear(); input.sendKeys('123'); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); - -
          - */ - 'number': numberInputType, + + + */ + 'number': numberInputType, - /** - * @ngdoc input - * @name input[url] - * - * @description - * Text input with URL validation. Sets the `url` validation error key if the content is not a - * valid URL. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - + /** + * @ngdoc input + * @name input[url] + * + * @description + * Text input with URL validation. Sets the `url` validation error key if the content is not a + * valid URL. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + +
          - URL: - - Required! - - Not valid url! - text = {{text}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          - myForm.$error.url = {{!!myForm.$error.url}}
          -
          -
          - - var text = element(by.binding('text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + URL: + + Required! + + Not valid url! + text = {{text}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          + myForm.$error.url = {{!!myForm.$error.url}}
          + +
          + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); - it('should initialize to model', function() { + it('should initialize to model', function() { expect(text.getText()).toContain('http://google.com'); expect(valid.getText()).toContain('true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); @@ -19029,115 +19158,115 @@ var inputType = { expect(valid.getText()).toContain('false'); }); - it('should be invalid if not url', function() { + it('should be invalid if not url', function() { input.clear(); input.sendKeys('box'); expect(valid.getText()).toContain('false'); }); - -
          - */ - 'url': urlInputType, +
          +
          + */ + 'url': urlInputType, - /** - * @ngdoc input - * @name input[email] - * - * @description - * Text input with email validation. Sets the `email` validation error key if not a valid email - * address. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - + /** + * @ngdoc input + * @name input[email] + * + * @description + * Text input with email validation. Sets the `email` validation error key if not a valid email + * address. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + -
          - Email: - - Required! - - Not valid email! - text = {{text}}
          - myForm.input.$valid = {{myForm.input.$valid}}
          - myForm.input.$error = {{myForm.input.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          - myForm.$error.email = {{!!myForm.$error.email}}
          -
          +
          + Email: + + Required! + + Not valid email! + text = {{text}}
          + myForm.input.$valid = {{myForm.input.$valid}}
          + myForm.input.$error = {{myForm.input.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          + myForm.$error.email = {{!!myForm.$error.email}}
          +
          - - var text = element(by.binding('text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); - it('should initialize to model', function() { + it('should initialize to model', function() { expect(text.getText()).toContain('me@example.com'); expect(valid.getText()).toContain('true'); }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); - it('should be invalid if not email', function() { + it('should be invalid if not email', function() { input.clear(); input.sendKeys('xxx'); expect(valid.getText()).toContain('false'); }); - -
          - */ - 'email': emailInputType, +
          +
          + */ + 'email': emailInputType, - /** - * @ngdoc input - * @name input[radio] - * - * @description - * HTML radio button. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string} value The value to which the expression should be set when selected. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * @param {string} ngValue Angular expression which sets the value to which the expression should - * be set when selected. - * - * @example - - + /** + * @ngdoc input + * @name input[radio] + * + * @description + * HTML radio button. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} value The value to which the expression should be set when selected. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {string} ngValue Angular expression which sets the value to which the expression should + * be set when selected. + * + * @example + +
          - Red
          - Green
          - Blue
          - color = {{color | json}}
          -
          - Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. -
          - - it('should change state', function() { + Red
          + Green
          + Blue
          + color = {{color | json}}
          + + Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. +
          + + it('should change state', function() { var color = element(by.binding('color')); expect(color.getText()).toContain('blue'); @@ -19163,46 +19292,46 @@ var inputType = { expect(color.getText()).toContain('red'); }); - -
          - */ - 'radio': radioInputType, +
          +
          + */ + 'radio': radioInputType, - /** - * @ngdoc input - * @name input[checkbox] - * - * @description - * HTML checkbox. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {expression=} ngTrueValue The value to which the expression should be set when selected. - * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - + /** + * @ngdoc input + * @name input[checkbox] + * + * @description + * HTML checkbox. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {expression=} ngTrueValue The value to which the expression should be set when selected. + * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + +
          - Value1:
          - Value2:
          - value1 = {{value1}}
          - value2 = {{value2}}
          -
          -
          - - it('should change state', function() { + Value1:
          + Value2:
          + value1 = {{value1}}
          + value2 = {{value2}}
          + +
          + + it('should change state', function() { var value1 = element(by.binding('value1')); var value2 = element(by.binding('value2')); @@ -19215,551 +19344,551 @@ var inputType = { expect(value1.getText()).toContain('false'); expect(value2.getText()).toContain('NO'); }); - -
          - */ - 'checkbox': checkboxInputType, - - 'hidden': noop, - 'button': noop, - 'submit': noop, - 'reset': noop, - 'file': noop -}; - -function testFlags(validity, flags) { - var i, flag; - if (flags) { - for (i=0; i +
          + */ + 'checkbox': checkboxInputType, -function stringBasedInputType(ctrl) { - ctrl.$formatters.push(function(value) { - return ctrl.$isEmpty(value) ? value : value.toString(); - }); -} - -function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { - baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - stringBasedInputType(ctrl); -} - -function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { - var validity = element.prop(VALIDITY_STATE_PROPERTY); - var placeholder = element[0].placeholder, noevent = {}; - var type = lowercase(element[0].type); - - // In composition mode, users are still inputing intermediate text buffer, - // hold the listener until composition is done. - // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent - if (!$sniffer.android) { - var composing = false; - - element.on('compositionstart', function(data) { - composing = true; - }); + 'hidden': noop, + 'button': noop, + 'submit': noop, + 'reset': noop, + 'file': noop + }; - element.on('compositionend', function() { - composing = false; - listener(); - }); - } - - var listener = function(ev) { - if (composing) return; - var value = element.val(), - event = ev && ev.type; - - // IE (11 and under) seem to emit an 'input' event if the placeholder value changes. - // We don't want to dirty the value when this happens, so we abort here. Unfortunately, - // IE also sends input events for other non-input-related things, (such as focusing on a - // form control), so this change is not entirely enough to solve this. - if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) { - placeholder = element[0].placeholder; - return; + function testFlags(validity, flags) { + var i, flag; + if (flags) { + for (i = 0; i < flags.length; ++i) { + flag = flags[i]; + if (validity[flag]) { + return true; + } + } + } + return false; } - // By default we will trim the value - // If the attribute ng-trim exists we will avoid trimming - // If input type is 'password', the value is never trimmed - if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { - value = trim(value); + function stringBasedInputType(ctrl) { + ctrl.$formatters.push(function (value) { + return ctrl.$isEmpty(value) ? value : value.toString(); + }); } - // If a control is suffering from bad input (due to native validators), browsers discard its - // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the - // control's value is the same empty value twice in a row. - if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { - ctrl.$setViewValue(value, event); + function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); } - }; - - // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the - // input event on backspace, delete or cut - if ($sniffer.hasEvent('input')) { - element.on('input', listener); - } else { - var timeout; - - var deferListener = function(ev) { - if (!timeout) { - timeout = $browser.defer(function() { - listener(ev); - timeout = null; - }); - } - }; - element.on('keydown', function(event) { - var key = event.keyCode; + function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { + var validity = element.prop(VALIDITY_STATE_PROPERTY); + var placeholder = element[0].placeholder, noevent = {}; + var type = lowercase(element[0].type); - // ignore - // command modifiers arrows - if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; + // In composition mode, users are still inputing intermediate text buffer, + // hold the listener until composition is done. + // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent + if (!$sniffer.android) { + var composing = false; - deferListener(event); - }); + element.on('compositionstart', function (data) { + composing = true; + }); - // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it - if ($sniffer.hasEvent('paste')) { - element.on('paste cut', deferListener); + element.on('compositionend', function () { + composing = false; + listener(); + }); + } + + var listener = function (ev) { + if (composing) return; + var value = element.val(), + event = ev && ev.type; + + // IE (11 and under) seem to emit an 'input' event if the placeholder value changes. + // We don't want to dirty the value when this happens, so we abort here. Unfortunately, + // IE also sends input events for other non-input-related things, (such as focusing on a + // form control), so this change is not entirely enough to solve this. + if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) { + placeholder = element[0].placeholder; + return; + } + + // By default we will trim the value + // If the attribute ng-trim exists we will avoid trimming + // If input type is 'password', the value is never trimmed + if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { + value = trim(value); + } + + // If a control is suffering from bad input (due to native validators), browsers discard its + // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the + // control's value is the same empty value twice in a row. + if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { + ctrl.$setViewValue(value, event); + } + }; + + // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the + // input event on backspace, delete or cut + if ($sniffer.hasEvent('input')) { + element.on('input', listener); + } else { + var timeout; + + var deferListener = function (ev) { + if (!timeout) { + timeout = $browser.defer(function () { + listener(ev); + timeout = null; + }); + } + }; + + element.on('keydown', function (event) { + var key = event.keyCode; + + // ignore + // command modifiers arrows + if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; + + deferListener(event); + }); + + // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it + if ($sniffer.hasEvent('paste')) { + element.on('paste cut', deferListener); + } + } + + // if user paste into input using mouse on older browser + // or form autocomplete on newer browser, we need "change" event to catch it + element.on('change', listener); + + ctrl.$render = function () { + element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue); + }; } - } - - // if user paste into input using mouse on older browser - // or form autocomplete on newer browser, we need "change" event to catch it - element.on('change', listener); - - ctrl.$render = function() { - element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue); - }; -} - -function weekParser(isoWeek, existingDate) { - if (isDate(isoWeek)) { - return isoWeek; - } - - if (isString(isoWeek)) { - WEEK_REGEXP.lastIndex = 0; - var parts = WEEK_REGEXP.exec(isoWeek); - if (parts) { - var year = +parts[1], - week = +parts[2], - hours = 0, - minutes = 0, - seconds = 0, - milliseconds = 0, - firstThurs = getFirstThursdayOfYear(year), - addDays = (week - 1) * 7; - - if (existingDate) { - hours = existingDate.getHours(); - minutes = existingDate.getMinutes(); - seconds = existingDate.getSeconds(); - milliseconds = existingDate.getMilliseconds(); - } - return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); + function weekParser(isoWeek, existingDate) { + if (isDate(isoWeek)) { + return isoWeek; + } + + if (isString(isoWeek)) { + WEEK_REGEXP.lastIndex = 0; + var parts = WEEK_REGEXP.exec(isoWeek); + if (parts) { + var year = +parts[1], + week = +parts[2], + hours = 0, + minutes = 0, + seconds = 0, + milliseconds = 0, + firstThurs = getFirstThursdayOfYear(year), + addDays = (week - 1) * 7; + + if (existingDate) { + hours = existingDate.getHours(); + minutes = existingDate.getMinutes(); + seconds = existingDate.getSeconds(); + milliseconds = existingDate.getMilliseconds(); + } + + return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); + } + } + + return NaN; + } + + function createDateParser(regexp, mapping) { + return function (iso, date) { + var parts, map; + + if (isDate(iso)) { + return iso; + } + + if (isString(iso)) { + // When a date is JSON'ified to wraps itself inside of an extra + // set of double quotes. This makes the date parsing code unable + // to match the date string and parse it as a date. + if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') { + iso = iso.substring(1, iso.length - 1); + } + if (ISO_DATE_REGEXP.test(iso)) { + return new Date(iso); + } + regexp.lastIndex = 0; + parts = regexp.exec(iso); + + if (parts) { + parts.shift(); + if (date) { + map = { + yyyy: date.getFullYear(), + MM: date.getMonth() + 1, + dd: date.getDate(), + HH: date.getHours(), + mm: date.getMinutes(), + ss: date.getSeconds(), + sss: date.getMilliseconds() / 1000 + }; + } else { + map = {yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0}; + } + + forEach(parts, function (part, index) { + if (index < mapping.length) { + map[mapping[index]] = +part; + } + }); + return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); + } + } + + return NaN; + }; } - } - return NaN; -} + function createDateInputType(type, regexp, parseDate, format) { + return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { + badInputChecker(scope, element, attr, ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + var timezone = ctrl && ctrl.$options && ctrl.$options.timezone; + var previousDate; + + ctrl.$$parserName = type; + ctrl.$parsers.push(function (value) { + if (ctrl.$isEmpty(value)) return null; + if (regexp.test(value)) { + // Note: We cannot read ctrl.$modelValue, as there might be a different + // parser/formatter in the processing chain so that the model + // contains some different data format! + var parsedDate = parseDate(value, previousDate); + if (timezone === 'UTC') { + parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset()); + } + return parsedDate; + } + return undefined; + }); + + ctrl.$formatters.push(function (value) { + if (!ctrl.$isEmpty(value)) { + if (!isDate(value)) { + throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); + } + previousDate = value; + if (previousDate && timezone === 'UTC') { + var timezoneOffset = 60000 * previousDate.getTimezoneOffset(); + previousDate = new Date(previousDate.getTime() + timezoneOffset); + } + return $filter('date')(value, format, timezone); + } else { + previousDate = null; + } + return ''; + }); + + if (isDefined(attr.min) || attr.ngMin) { + var minVal; + ctrl.$validators.min = function (value) { + return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal; + }; + attr.$observe('min', function (val) { + minVal = parseObservedDateValue(val); + ctrl.$validate(); + }); + } -function createDateParser(regexp, mapping) { - return function(iso, date) { - var parts, map; + if (isDefined(attr.max) || attr.ngMax) { + var maxVal; + ctrl.$validators.max = function (value) { + return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; + }; + attr.$observe('max', function (val) { + maxVal = parseObservedDateValue(val); + ctrl.$validate(); + }); + } + // Override the standard $isEmpty to detect invalid dates as well + ctrl.$isEmpty = function (value) { + // Invalid Date: getTime() returns NaN + return !value || (value.getTime && value.getTime() !== value.getTime()); + }; - if (isDate(iso)) { - return iso; + function parseObservedDateValue(val) { + return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined; + } + }; } - if (isString(iso)) { - // When a date is JSON'ified to wraps itself inside of an extra - // set of double quotes. This makes the date parsing code unable - // to match the date string and parse it as a date. - if (iso.charAt(0) == '"' && iso.charAt(iso.length-1) == '"') { - iso = iso.substring(1, iso.length-1); - } - if (ISO_DATE_REGEXP.test(iso)) { - return new Date(iso); - } - regexp.lastIndex = 0; - parts = regexp.exec(iso); - - if (parts) { - parts.shift(); - if (date) { - map = { - yyyy: date.getFullYear(), - MM: date.getMonth() + 1, - dd: date.getDate(), - HH: date.getHours(), - mm: date.getMinutes(), - ss: date.getSeconds(), - sss: date.getMilliseconds() / 1000 - }; - } else { - map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; + function badInputChecker(scope, element, attr, ctrl) { + var node = element[0]; + var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); + if (nativeValidation) { + ctrl.$parsers.push(function (value) { + var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; + // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430): + // - also sets validity.badInput (should only be validity.typeMismatch). + // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email) + // - can ignore this case as we can still read out the erroneous email... + return validity.badInput && !validity.typeMismatch ? undefined : value; + }); } + } - forEach(parts, function(part, index) { - if (index < mapping.length) { - map[mapping[index]] = +part; - } + function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { + badInputChecker(scope, element, attr, ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + + ctrl.$$parserName = 'number'; + ctrl.$parsers.push(function (value) { + if (ctrl.$isEmpty(value)) return null; + if (NUMBER_REGEXP.test(value)) return parseFloat(value); + return undefined; }); - return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); - } - } - return NaN; - }; -} - -function createDateInputType(type, regexp, parseDate, format) { - return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { - badInputChecker(scope, element, attr, ctrl); - baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - var timezone = ctrl && ctrl.$options && ctrl.$options.timezone; - var previousDate; - - ctrl.$$parserName = type; - ctrl.$parsers.push(function(value) { - if (ctrl.$isEmpty(value)) return null; - if (regexp.test(value)) { - // Note: We cannot read ctrl.$modelValue, as there might be a different - // parser/formatter in the processing chain so that the model - // contains some different data format! - var parsedDate = parseDate(value, previousDate); - if (timezone === 'UTC') { - parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset()); - } - return parsedDate; - } - return undefined; - }); + ctrl.$formatters.push(function (value) { + if (!ctrl.$isEmpty(value)) { + if (!isNumber(value)) { + throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); + } + value = value.toString(); + } + return value; + }); - ctrl.$formatters.push(function(value) { - if (!ctrl.$isEmpty(value)) { - if (!isDate(value)) { - throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); - } - previousDate = value; - if (previousDate && timezone === 'UTC') { - var timezoneOffset = 60000 * previousDate.getTimezoneOffset(); - previousDate = new Date(previousDate.getTime() + timezoneOffset); + if (attr.min || attr.ngMin) { + var minVal; + ctrl.$validators.min = function (value) { + return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; + }; + + attr.$observe('min', function (val) { + if (isDefined(val) && !isNumber(val)) { + val = parseFloat(val, 10); + } + minVal = isNumber(val) && !isNaN(val) ? val : undefined; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + }); } - return $filter('date')(value, format, timezone); - } else { - previousDate = null; - } - return ''; - }); - if (isDefined(attr.min) || attr.ngMin) { - var minVal; - ctrl.$validators.min = function(value) { - return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal; - }; - attr.$observe('min', function(val) { - minVal = parseObservedDateValue(val); - ctrl.$validate(); - }); - } + if (attr.max || attr.ngMax) { + var maxVal; + ctrl.$validators.max = function (value) { + return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; + }; - if (isDefined(attr.max) || attr.ngMax) { - var maxVal; - ctrl.$validators.max = function(value) { - return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; - }; - attr.$observe('max', function(val) { - maxVal = parseObservedDateValue(val); - ctrl.$validate(); - }); + attr.$observe('max', function (val) { + if (isDefined(val) && !isNumber(val)) { + val = parseFloat(val, 10); + } + maxVal = isNumber(val) && !isNaN(val) ? val : undefined; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + }); + } } - // Override the standard $isEmpty to detect invalid dates as well - ctrl.$isEmpty = function(value) { - // Invalid Date: getTime() returns NaN - return !value || (value.getTime && value.getTime() !== value.getTime()); - }; - function parseObservedDateValue(val) { - return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined; - } - }; -} - -function badInputChecker(scope, element, attr, ctrl) { - var node = element[0]; - var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); - if (nativeValidation) { - ctrl.$parsers.push(function(value) { - var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; - // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430): - // - also sets validity.badInput (should only be validity.typeMismatch). - // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email) - // - can ignore this case as we can still read out the erroneous email... - return validity.badInput && !validity.typeMismatch ? undefined : value; - }); - } -} - -function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { - badInputChecker(scope, element, attr, ctrl); - baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - - ctrl.$$parserName = 'number'; - ctrl.$parsers.push(function(value) { - if (ctrl.$isEmpty(value)) return null; - if (NUMBER_REGEXP.test(value)) return parseFloat(value); - return undefined; - }); + function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); - ctrl.$formatters.push(function(value) { - if (!ctrl.$isEmpty(value)) { - if (!isNumber(value)) { - throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); - } - value = value.toString(); + ctrl.$$parserName = 'url'; + ctrl.$validators.url = function (value) { + return ctrl.$isEmpty(value) || URL_REGEXP.test(value); + }; } - return value; - }); - if (attr.min || attr.ngMin) { - var minVal; - ctrl.$validators.min = function(value) { - return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; - }; + function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); - attr.$observe('min', function(val) { - if (isDefined(val) && !isNumber(val)) { - val = parseFloat(val, 10); - } - minVal = isNumber(val) && !isNaN(val) ? val : undefined; - // TODO(matsko): implement validateLater to reduce number of validations - ctrl.$validate(); - }); - } + ctrl.$$parserName = 'email'; + ctrl.$validators.email = function (value) { + return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); + }; + } - if (attr.max || attr.ngMax) { - var maxVal; - ctrl.$validators.max = function(value) { - return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; - }; + function radioInputType(scope, element, attr, ctrl) { + // make the name unique, if not defined + if (isUndefined(attr.name)) { + element.attr('name', nextUid()); + } - attr.$observe('max', function(val) { - if (isDefined(val) && !isNumber(val)) { - val = parseFloat(val, 10); - } - maxVal = isNumber(val) && !isNaN(val) ? val : undefined; - // TODO(matsko): implement validateLater to reduce number of validations - ctrl.$validate(); - }); - } -} - -function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { - // Note: no badInputChecker here by purpose as `url` is only a validation - // in browsers, i.e. we can always read out input.value even if it is not valid! - baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - stringBasedInputType(ctrl); - - ctrl.$$parserName = 'url'; - ctrl.$validators.url = function(value) { - return ctrl.$isEmpty(value) || URL_REGEXP.test(value); - }; -} - -function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { - // Note: no badInputChecker here by purpose as `url` is only a validation - // in browsers, i.e. we can always read out input.value even if it is not valid! - baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - stringBasedInputType(ctrl); - - ctrl.$$parserName = 'email'; - ctrl.$validators.email = function(value) { - return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); - }; -} - -function radioInputType(scope, element, attr, ctrl) { - // make the name unique, if not defined - if (isUndefined(attr.name)) { - element.attr('name', nextUid()); - } - - var listener = function(ev) { - if (element[0].checked) { - ctrl.$setViewValue(attr.value, ev && ev.type); - } - }; + var listener = function (ev) { + if (element[0].checked) { + ctrl.$setViewValue(attr.value, ev && ev.type); + } + }; - element.on('click', listener); + element.on('click', listener); - ctrl.$render = function() { - var value = attr.value; - element[0].checked = (value == ctrl.$viewValue); - }; + ctrl.$render = function () { + var value = attr.value; + element[0].checked = (value == ctrl.$viewValue); + }; - attr.$observe('value', ctrl.$render); -} + attr.$observe('value', ctrl.$render); + } -function parseConstantExpr($parse, context, name, expression, fallback) { - var parseFn; - if (isDefined(expression)) { - parseFn = $parse(expression); - if (!parseFn.constant) { - throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' + - '`{1}`.', name, expression); + function parseConstantExpr($parse, context, name, expression, fallback) { + var parseFn; + if (isDefined(expression)) { + parseFn = $parse(expression); + if (!parseFn.constant) { + throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' + + '`{1}`.', name, expression); + } + return parseFn(context); + } + return fallback; } - return parseFn(context); - } - return fallback; -} -function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { - var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); - var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); + function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { + var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); + var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); - var listener = function(ev) { - ctrl.$setViewValue(element[0].checked, ev && ev.type); - }; + var listener = function (ev) { + ctrl.$setViewValue(element[0].checked, ev && ev.type); + }; - element.on('click', listener); + element.on('click', listener); - ctrl.$render = function() { - element[0].checked = ctrl.$viewValue; - }; + ctrl.$render = function () { + element[0].checked = ctrl.$viewValue; + }; - // Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue - ctrl.$isEmpty = function(value) { - return value !== trueValue; - }; + // Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue + ctrl.$isEmpty = function (value) { + return value !== trueValue; + }; - ctrl.$formatters.push(function(value) { - return equals(value, trueValue); - }); + ctrl.$formatters.push(function (value) { + return equals(value, trueValue); + }); - ctrl.$parsers.push(function(value) { - return value ? trueValue : falseValue; - }); -} + ctrl.$parsers.push(function (value) { + return value ? trueValue : falseValue; + }); + } -/** - * @ngdoc directive - * @name textarea - * @restrict E - * - * @description - * HTML textarea element control with angular data-binding. The data-binding and validation - * properties of this element are exactly the same as those of the - * {@link ng.directive:input input element}. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. - */ + /** + * @ngdoc directive + * @name textarea + * @restrict E + * + * @description + * HTML textarea element control with angular data-binding. The data-binding and validation + * properties of this element are exactly the same as those of the + * {@link ng.directive:input input element}. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + */ -/** - * @ngdoc directive - * @name input - * @restrict E - * - * @description - * HTML input element control with angular data-binding. Input control follows HTML5 input types - * and polyfills the HTML5 validation behavior for older browsers. - * - * *NOTE* Not every feature offered is available for all input types. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {boolean=} ngRequired Sets `required` attribute if set to true - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. - * This parameter is ignored for input[type=password] controls, which will never trim the - * input. - * - * @example - - - -
          -
          - User name: - - Required!
          - Last name: - - Too short! - - Too long!
          -
          -
          - user = {{user}}
          - myForm.userName.$valid = {{myForm.userName.$valid}}
          - myForm.userName.$error = {{myForm.userName.$error}}
          - myForm.lastName.$valid = {{myForm.lastName.$valid}}
          - myForm.lastName.$error = {{myForm.lastName.$error}}
          - myForm.$valid = {{myForm.$valid}}
          - myForm.$error.required = {{!!myForm.$error.required}}
          - myForm.$error.minlength = {{!!myForm.$error.minlength}}
          - myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
          -
          -
          - - var user = element(by.exactBinding('user')); - var userNameValid = element(by.binding('myForm.userName.$valid')); - var lastNameValid = element(by.binding('myForm.lastName.$valid')); - var lastNameError = element(by.binding('myForm.lastName.$error')); - var formValid = element(by.binding('myForm.$valid')); - var userNameInput = element(by.model('user.name')); - var userLastInput = element(by.model('user.last')); - - it('should initialize to model', function() { + +
          +
          + User name: + + Required!
          + Last name: + + Too short! + + Too long!
          +
          +
          + user = {{user}}
          + myForm.userName.$valid = {{myForm.userName.$valid}}
          + myForm.userName.$error = {{myForm.userName.$error}}
          + myForm.lastName.$valid = {{myForm.lastName.$valid}}
          + myForm.lastName.$error = {{myForm.lastName.$error}}
          + myForm.$valid = {{myForm.$valid}}
          + myForm.$error.required = {{!!myForm.$error.required}}
          + myForm.$error.minlength = {{!!myForm.$error.minlength}}
          + myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
          +
          +
          + + var user = element(by.exactBinding('user')); + var userNameValid = element(by.binding('myForm.userName.$valid')); + var lastNameValid = element(by.binding('myForm.lastName.$valid')); + var lastNameError = element(by.binding('myForm.lastName.$error')); + var formValid = element(by.binding('myForm.$valid')); + var userNameInput = element(by.model('user.name')); + var userLastInput = element(by.model('user.last')); + + it('should initialize to model', function() { expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); expect(userNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); - it('should be invalid if empty when required', function() { + it('should be invalid if empty when required', function() { userNameInput.clear(); userNameInput.sendKeys(''); @@ -19768,7 +19897,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt expect(formValid.getText()).toContain('false'); }); - it('should be valid if empty when min length is set', function() { + it('should be valid if empty when min length is set', function() { userLastInput.clear(); userLastInput.sendKeys(''); @@ -19777,7 +19906,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt expect(formValid.getText()).toContain('true'); }); - it('should be invalid if less than required min length', function() { + it('should be invalid if less than required min length', function() { userLastInput.clear(); userLastInput.sendKeys('xx'); @@ -19787,7 +19916,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt expect(formValid.getText()).toContain('false'); }); - it('should be invalid if longer than max length', function() { + it('should be invalid if longer than max length', function() { userLastInput.clear(); userLastInput.sendKeys('some ridiculously long name'); @@ -19796,89 +19925,89 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt expect(lastNameError.getText()).toContain('maxlength'); expect(formValid.getText()).toContain('false'); }); - -
          - */ -var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', - function($browser, $sniffer, $filter, $parse) { - return { - restrict: 'E', - require: ['?ngModel'], - link: { - pre: function(scope, element, attr, ctrls) { - if (ctrls[0]) { - (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, - $browser, $filter, $parse); - } - } - } - }; -}]; + + + */ + var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', + function ($browser, $sniffer, $filter, $parse) { + return { + restrict: 'E', + require: ['?ngModel'], + link: { + pre: function (scope, element, attr, ctrls) { + if (ctrls[0]) { + (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, + $browser, $filter, $parse); + } + } + } + }; + }]; -var VALID_CLASS = 'ng-valid', - INVALID_CLASS = 'ng-invalid', - PRISTINE_CLASS = 'ng-pristine', - DIRTY_CLASS = 'ng-dirty', - UNTOUCHED_CLASS = 'ng-untouched', - TOUCHED_CLASS = 'ng-touched', - PENDING_CLASS = 'ng-pending'; + var VALID_CLASS = 'ng-valid', + INVALID_CLASS = 'ng-invalid', + PRISTINE_CLASS = 'ng-pristine', + DIRTY_CLASS = 'ng-dirty', + UNTOUCHED_CLASS = 'ng-untouched', + TOUCHED_CLASS = 'ng-touched', + PENDING_CLASS = 'ng-pending'; -/** - * @ngdoc type - * @name ngModel.NgModelController - * - * @property {string} $viewValue Actual string value in the view. - * @property {*} $modelValue The value in the model, that the control is bound to. - * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever - the control reads value from the DOM. Each function is called, in turn, passing the value - through to the next. The last return value is used to populate the model. - Used to sanitize / convert the value as well as validation. For validation, - the parsers should update the validity state using - {@link ngModel.NgModelController#$setValidity $setValidity()}, - and return `undefined` for invalid values. + /** + * @ngdoc type + * @name ngModel.NgModelController + * + * @property {string} $viewValue Actual string value in the view. + * @property {*} $modelValue The value in the model, that the control is bound to. + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + the control reads value from the DOM. Each function is called, in turn, passing the value + through to the next. The last return value is used to populate the model. + Used to sanitize / convert the value as well as validation. For validation, + the parsers should update the validity state using + {@link ngModel.NgModelController#$setValidity $setValidity()}, + and return `undefined` for invalid values. - * - * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever - the model value changes. Each function is called, in turn, passing the value through to the - next. Used to format / convert values for display in the control and validation. - * ```js - * function formatter(value) { + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the model value changes. Each function is called, in turn, passing the value through to the + next. Used to format / convert values for display in the control and validation. + * ```js + * function formatter(value) { * if (value) { * return value.toUpperCase(); * } * } - * ngModel.$formatters.push(formatter); - * ``` - * - * @property {Object.} $validators A collection of validators that are applied - * whenever the model value changes. The key value within the object refers to the name of the - * validator while the function refers to the validation operation. The validation operation is - * provided with the model value as an argument and must return a true or false value depending - * on the response of that validation. - * - * ```js - * ngModel.$validators.validCharacters = function(modelValue, viewValue) { + * ngModel.$formatters.push(formatter); + * ``` + * + * @property {Object.} $validators A collection of validators that are applied + * whenever the model value changes. The key value within the object refers to the name of the + * validator while the function refers to the validation operation. The validation operation is + * provided with the model value as an argument and must return a true or false value depending + * on the response of that validation. + * + * ```js + * ngModel.$validators.validCharacters = function(modelValue, viewValue) { * var value = modelValue || viewValue; * return /[0-9]+/.test(value) && * /[a-z]+/.test(value) && * /[A-Z]+/.test(value) && * /\W+/.test(value); * }; - * ``` - * - * @property {Object.} $asyncValidators A collection of validations that are expected to - * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided - * is expected to return a promise when it is run during the model validation process. Once the promise - * is delivered then the validation status will be set to true when fulfilled and false when rejected. - * When the asynchronous validators are triggered, each of the validators will run in parallel and the model - * value will only be updated once all validators have been fulfilled. Also, keep in mind that all - * asynchronous validators will only run once all synchronous validators have passed. - * - * Please note that if $http is used then it is important that the server returns a success HTTP response code - * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. - * - * ```js - * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { + * ``` + * + * @property {Object.} $asyncValidators A collection of validations that are expected to + * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided + * is expected to return a promise when it is run during the model validation process. Once the promise + * is delivered then the validation status will be set to true when fulfilled and false when rejected. + * When the asynchronous validators are triggered, each of the validators will run in parallel and the model + * value will only be updated once all validators have been fulfilled. Also, keep in mind that all + * asynchronous validators will only run once all synchronous validators have passed. + * + * Please note that if $http is used then it is important that the server returns a success HTTP response code + * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. + * + * ```js + * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { * var value = modelValue || viewValue; * * // Lookup user by username @@ -19891,62 +20020,62 @@ var VALID_CLASS = 'ng-valid', * return true; * }); * }; - * ``` - * - * @param {string} name The name of the validator. - * @param {Function} validationFn The validation function that will be run. - * - * @property {Array.} $viewChangeListeners Array of functions to execute whenever the - * view value has changed. It is called with no arguments, and its return value is ignored. - * This can be used in place of additional $watches against the model value. - * - * @property {Object} $error An object hash with all failing validator ids as keys. - * @property {Object} $pending An object hash with all pending validator ids as keys. - * - * @property {boolean} $untouched True if control has not lost focus yet. - * @property {boolean} $touched True if control has lost focus. - * @property {boolean} $pristine True if user has not interacted with the control yet. - * @property {boolean} $dirty True if user has already interacted with the control. - * @property {boolean} $valid True if there is no error. - * @property {boolean} $invalid True if at least one error on the control. - * - * @description - * - * `NgModelController` provides API for the `ng-model` directive. The controller contains - * services for data-binding, validation, CSS updates, and value formatting and parsing. It - * purposefully does not contain any logic which deals with DOM rendering or listening to - * DOM events. Such DOM related logic should be provided by other directives which make use of - * `NgModelController` for data-binding. - * - * ## Custom Control Example - * This example shows how to use `NgModelController` with a custom control to achieve - * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) - * collaborate together to achieve the desired result. - * - * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element - * contents be edited in place by the user. This will not work on older browsers. - * - * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} - * module to automatically remove "bad" content like inline event listener (e.g. ``). - * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks - * that content using the `$sce` service. - * - * - - [contenteditable] { + * ``` + * + * @param {string} name The name of the validator. + * @param {Function} validationFn The validation function that will be run. + * + * @property {Array.} $viewChangeListeners Array of functions to execute whenever the + * view value has changed. It is called with no arguments, and its return value is ignored. + * This can be used in place of additional $watches against the model value. + * + * @property {Object} $error An object hash with all failing validator ids as keys. + * @property {Object} $pending An object hash with all pending validator ids as keys. + * + * @property {boolean} $untouched True if control has not lost focus yet. + * @property {boolean} $touched True if control has lost focus. + * @property {boolean} $pristine True if user has not interacted with the control yet. + * @property {boolean} $dirty True if user has already interacted with the control. + * @property {boolean} $valid True if there is no error. + * @property {boolean} $invalid True if at least one error on the control. + * + * @description + * + * `NgModelController` provides API for the `ng-model` directive. The controller contains + * services for data-binding, validation, CSS updates, and value formatting and parsing. It + * purposefully does not contain any logic which deals with DOM rendering or listening to + * DOM events. Such DOM related logic should be provided by other directives which make use of + * `NgModelController` for data-binding. + * + * ## Custom Control Example + * This example shows how to use `NgModelController` with a custom control to achieve + * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) + * collaborate together to achieve the desired result. + * + * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. This will not work on older browsers. + * + * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} + * module to automatically remove "bad" content like inline event listener (e.g. ``). + * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks + * that content using the `$sce` service. + * + * + + [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } - .ng-invalid { + .ng-invalid { border: 1px solid red; } - - - angular.module('customControl', ['ngSanitize']). - directive('contenteditable', ['$sce', function($sce) { + + + angular.module('customControl', ['ngSanitize']). + directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController @@ -19977,20 +20106,20 @@ var VALID_CLASS = 'ng-valid', } }; }]); - - -
          -
          Change me!
          - Required! -
          - -
          -
          - - it('should data-bind and become invalid', function() { + + +
          +
          Change me!
          + Required! +
          + +
          +
          + + it('should data-bind and become invalid', function() { if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { // SafariDriver can't handle contenteditable // and Firefox driver can't clear contenteditables very well @@ -20006,222 +20135,222 @@ var VALID_CLASS = 'ng-valid', expect(contentEditable.getText()).toEqual(''); expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); }); - - *
          - * - * - */ -var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', - function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) { - this.$viewValue = Number.NaN; - this.$modelValue = Number.NaN; - this.$validators = {}; - this.$asyncValidators = {}; - this.$parsers = []; - this.$formatters = []; - this.$viewChangeListeners = []; - this.$untouched = true; - this.$touched = false; - this.$pristine = true; - this.$dirty = false; - this.$valid = true; - this.$invalid = false; - this.$error = {}; // keep invalid keys here - this.$$success = {}; // keep valid keys here - this.$pending = undefined; // keep pending keys here - this.$name = $interpolate($attr.name || '', false)($scope); - - - var parsedNgModel = $parse($attr.ngModel), - pendingDebounce = null, - ctrl = this; - - var ngModelGet = function ngModelGet() { - var modelValue = parsedNgModel($scope); - if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) { - modelValue = modelValue(); - } - return modelValue; - }; +
          + *
          + * + * + */ + var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', + function ($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) { + this.$viewValue = Number.NaN; + this.$modelValue = Number.NaN; + this.$validators = {}; + this.$asyncValidators = {}; + this.$parsers = []; + this.$formatters = []; + this.$viewChangeListeners = []; + this.$untouched = true; + this.$touched = false; + this.$pristine = true; + this.$dirty = false; + this.$valid = true; + this.$invalid = false; + this.$error = {}; // keep invalid keys here + this.$$success = {}; // keep valid keys here + this.$pending = undefined; // keep pending keys here + this.$name = $interpolate($attr.name || '', false)($scope); + + + var parsedNgModel = $parse($attr.ngModel), + pendingDebounce = null, + ctrl = this; + + var ngModelGet = function ngModelGet() { + var modelValue = parsedNgModel($scope); + if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) { + modelValue = modelValue(); + } + return modelValue; + }; - var ngModelSet = function ngModelSet(newValue) { - var getterSetter; - if (ctrl.$options && ctrl.$options.getterSetter && - isFunction(getterSetter = parsedNgModel($scope))) { + var ngModelSet = function ngModelSet(newValue) { + var getterSetter; + if (ctrl.$options && ctrl.$options.getterSetter && + isFunction(getterSetter = parsedNgModel($scope))) { - getterSetter(ctrl.$modelValue); - } else { - parsedNgModel.assign($scope, ctrl.$modelValue); - } - }; + getterSetter(ctrl.$modelValue); + } else { + parsedNgModel.assign($scope, ctrl.$modelValue); + } + }; - this.$$setOptions = function(options) { - ctrl.$options = options; + this.$$setOptions = function (options) { + ctrl.$options = options; - if (!parsedNgModel.assign && (!options || !options.getterSetter)) { - throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}", - $attr.ngModel, startingTag($element)); - } - }; + if (!parsedNgModel.assign && (!options || !options.getterSetter)) { + throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}", + $attr.ngModel, startingTag($element)); + } + }; - /** - * @ngdoc method - * @name ngModel.NgModelController#$render - * - * @description - * Called when the view needs to be updated. It is expected that the user of the ng-model - * directive will implement this method. - * - * The `$render()` method is invoked in the following situations: - * - * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last - * committed value then `$render()` is called to update the input control. - * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and - * the `$viewValue` are different to last time. - * - * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of - * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue` - * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be - * invoked if you only change a property on the objects. - */ - this.$render = noop; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$isEmpty - * - * @description - * This is called when we need to determine if the value of the input is empty. - * - * For instance, the required directive does this to work out if the input has data or not. - * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. - * - * You can override this for input directives whose concept of being empty is different to the - * default. The `checkboxInputType` directive does this because in its case a value of `false` - * implies empty. - * - * @param {*} value Model value to check. - * @returns {boolean} True if `value` is empty. - */ - this.$isEmpty = function(value) { - return isUndefined(value) || value === '' || value === null || value !== value; - }; - - var parentForm = $element.inheritedData('$formController') || nullFormCtrl, - currentValidationRunId = 0; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setValidity - * - * @description - * Change the validity state, and notifies the form. - * - * This method can be called within $parsers/$formatters. However, if possible, please use the - * `ngModel.$validators` pipeline which is designed to call this method automatically. - * - * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]` and `$pending[validationErrorKey]` - * so that it is available for data-binding. - * The `validationErrorKey` should be in camelCase and will get converted into dash-case - * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` - * class and can be bound to as `{{someForm.someControl.$error.myError}}` . - * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), - * or skipped (null). - */ - addSetValidityMethod({ - ctrl: this, - $element: $element, - set: function(object, property) { - object[property] = true; - }, - unset: function(object, property) { - delete object[property]; - }, - parentForm: parentForm, - $animate: $animate - }); + /** + * @ngdoc method + * @name ngModel.NgModelController#$render + * + * @description + * Called when the view needs to be updated. It is expected that the user of the ng-model + * directive will implement this method. + * + * The `$render()` method is invoked in the following situations: + * + * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last + * committed value then `$render()` is called to update the input control. + * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and + * the `$viewValue` are different to last time. + * + * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of + * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue` + * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be + * invoked if you only change a property on the objects. + */ + this.$render = noop; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$isEmpty + * + * @description + * This is called when we need to determine if the value of the input is empty. + * + * For instance, the required directive does this to work out if the input has data or not. + * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. + * + * You can override this for input directives whose concept of being empty is different to the + * default. The `checkboxInputType` directive does this because in its case a value of `false` + * implies empty. + * + * @param {*} value Model value to check. + * @returns {boolean} True if `value` is empty. + */ + this.$isEmpty = function (value) { + return isUndefined(value) || value === '' || value === null || value !== value; + }; - /** - * @ngdoc method - * @name ngModel.NgModelController#$setPristine - * - * @description - * Sets the control to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the control to its pristine - * state (ng-pristine class). A model is considered to be pristine when the model has not been changed - * from when first compiled within then form. - */ - this.$setPristine = function () { - ctrl.$dirty = false; - ctrl.$pristine = true; - $animate.removeClass($element, DIRTY_CLASS); - $animate.addClass($element, PRISTINE_CLASS); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setUntouched - * - * @description - * Sets the control to its untouched state. - * - * This method can be called to remove the 'ng-touched' class and set the control to its - * untouched state (ng-untouched class). Upon compilation, a model is set as untouched - * by default, however this function can be used to restore that state if the model has - * already been touched by the user. - */ - this.$setUntouched = function() { - ctrl.$touched = false; - ctrl.$untouched = true; - $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setTouched - * - * @description - * Sets the control to its touched state. - * - * This method can be called to remove the 'ng-untouched' class and set the control to its - * touched state (ng-touched class). A model is considered to be touched when the user has - * first interacted (focussed) on the model input element and then shifted focus away (blurred) - * from the input element. - */ - this.$setTouched = function() { - ctrl.$touched = true; - ctrl.$untouched = false; - $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$rollbackViewValue - * - * @description - * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, - * which may be caused by a pending debounced event or because the input is waiting for a some - * future event. - * - * If you have an input that uses `ng-model-options` to set up debounced events or events such - * as blur you can have a situation where there is a period when the `$viewValue` - * is out of synch with the ngModel's `$modelValue`. - * - * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` - * programmatically before these debounced/future events have resolved/occurred, because Angular's - * dirty checking mechanism is not able to tell whether the model has actually changed or not. - * - * The `$rollbackViewValue()` method should be called before programmatically changing the model of an - * input which may have such events pending. This is important in order to make sure that the - * input field will be updated with the new model value and any pending operations are cancelled. - * - * - * - * angular.module('cancel-update-example', []) - * - * .controller('CancelUpdateController', ['$scope', function($scope) { + var parentForm = $element.inheritedData('$formController') || nullFormCtrl, + currentValidationRunId = 0; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setValidity + * + * @description + * Change the validity state, and notifies the form. + * + * This method can be called within $parsers/$formatters. However, if possible, please use the + * `ngModel.$validators` pipeline which is designed to call this method automatically. + * + * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign + * to `$error[validationErrorKey]` and `$pending[validationErrorKey]` + * so that it is available for data-binding. + * The `validationErrorKey` should be in camelCase and will get converted into dash-case + * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` + * class and can be bound to as `{{someForm.someControl.$error.myError}}` . + * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), + * or skipped (null). + */ + addSetValidityMethod({ + ctrl: this, + $element: $element, + set: function (object, property) { + object[property] = true; + }, + unset: function (object, property) { + delete object[property]; + }, + parentForm: parentForm, + $animate: $animate + }); + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setPristine + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the control to its pristine + * state (ng-pristine class). A model is considered to be pristine when the model has not been changed + * from when first compiled within then form. + */ + this.$setPristine = function () { + ctrl.$dirty = false; + ctrl.$pristine = true; + $animate.removeClass($element, DIRTY_CLASS); + $animate.addClass($element, PRISTINE_CLASS); + }; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setUntouched + * + * @description + * Sets the control to its untouched state. + * + * This method can be called to remove the 'ng-touched' class and set the control to its + * untouched state (ng-untouched class). Upon compilation, a model is set as untouched + * by default, however this function can be used to restore that state if the model has + * already been touched by the user. + */ + this.$setUntouched = function () { + ctrl.$touched = false; + ctrl.$untouched = true; + $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); + }; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setTouched + * + * @description + * Sets the control to its touched state. + * + * This method can be called to remove the 'ng-untouched' class and set the control to its + * touched state (ng-touched class). A model is considered to be touched when the user has + * first interacted (focussed) on the model input element and then shifted focus away (blurred) + * from the input element. + */ + this.$setTouched = function () { + ctrl.$touched = true; + ctrl.$untouched = false; + $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); + }; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$rollbackViewValue + * + * @description + * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, + * which may be caused by a pending debounced event or because the input is waiting for a some + * future event. + * + * If you have an input that uses `ng-model-options` to set up debounced events or events such + * as blur you can have a situation where there is a period when the `$viewValue` + * is out of synch with the ngModel's `$modelValue`. + * + * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` + * programmatically before these debounced/future events have resolved/occurred, because Angular's + * dirty checking mechanism is not able to tell whether the model has actually changed or not. + * + * The `$rollbackViewValue()` method should be called before programmatically changing the model of an + * input which may have such events pending. This is important in order to make sure that the + * input field will be updated with the new model value and any pending operations are cancelled. + * + * + * + * angular.module('cancel-update-example', []) + * + * .controller('CancelUpdateController', ['$scope', function($scope) { * $scope.resetWithCancel = function (e) { * if (e.keyCode == 27) { * $scope.myForm.myInput1.$rollbackViewValue(); @@ -20234,483 +20363,483 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ * } * }; * }]); - * - * - *
          - *

          Try typing something in each input. See that the model only updates when you - * blur off the input. - *

          - *

          Now see what happens if you start typing then press the Escape key

          - * - *
          - *

          With $rollbackViewValue()

          - *
          - * myValue: "{{ myValue }}" - * - *

          Without $rollbackViewValue()

          - *
          - * myValue: "{{ myValue }}" - *
          - *
          - *
          - *
          - */ - this.$rollbackViewValue = function() { - $timeout.cancel(pendingDebounce); - ctrl.$viewValue = ctrl.$$lastCommittedViewValue; - ctrl.$render(); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$validate - * - * @description - * Runs each of the registered validators (first synchronous validators and then asynchronous validators). - */ - this.$validate = function() { - // ignore $validate before model is initialized - if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { - return; - } - this.$$parseAndValidate(); - }; + *
          + * + *
          + *

          Try typing something in each input. See that the model only updates when you + * blur off the input. + *

          + *

          Now see what happens if you start typing then press the Escape key

          + * + *
          + *

          With $rollbackViewValue()

          + *
          + * myValue: "{{ myValue }}" + * + *

          Without $rollbackViewValue()

          + *
          + * myValue: "{{ myValue }}" + *
          + *
          + *
          + *
          + */ + this.$rollbackViewValue = function () { + $timeout.cancel(pendingDebounce); + ctrl.$viewValue = ctrl.$$lastCommittedViewValue; + ctrl.$render(); + }; - this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) { - currentValidationRunId++; - var localValidationRunId = currentValidationRunId; + /** + * @ngdoc method + * @name ngModel.NgModelController#$validate + * + * @description + * Runs each of the registered validators (first synchronous validators and then asynchronous validators). + */ + this.$validate = function () { + // ignore $validate before model is initialized + if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { + return; + } + this.$$parseAndValidate(); + }; - // check parser error - if (!processParseErrors(parseValid)) { - validationDone(false); - return; - } - if (!processSyncValidators()) { - validationDone(false); - return; - } - processAsyncValidators(); - - function processParseErrors(parseValid) { - var errorKey = ctrl.$$parserName || 'parse'; - if (parseValid === undefined) { - setValidity(errorKey, null); - } else { - setValidity(errorKey, parseValid); - if (!parseValid) { - forEach(ctrl.$validators, function(v, name) { - setValidity(name, null); - }); - forEach(ctrl.$asyncValidators, function(v, name) { - setValidity(name, null); - }); - return false; - } - } - return true; - } + this.$$runValidators = function (parseValid, modelValue, viewValue, doneCallback) { + currentValidationRunId++; + var localValidationRunId = currentValidationRunId; - function processSyncValidators() { - var syncValidatorsValid = true; - forEach(ctrl.$validators, function(validator, name) { - var result = validator(modelValue, viewValue); - syncValidatorsValid = syncValidatorsValid && result; - setValidity(name, result); - }); - if (!syncValidatorsValid) { - forEach(ctrl.$asyncValidators, function(v, name) { - setValidity(name, null); - }); - return false; - } - return true; - } + // check parser error + if (!processParseErrors(parseValid)) { + validationDone(false); + return; + } + if (!processSyncValidators()) { + validationDone(false); + return; + } + processAsyncValidators(); + + function processParseErrors(parseValid) { + var errorKey = ctrl.$$parserName || 'parse'; + if (parseValid === undefined) { + setValidity(errorKey, null); + } else { + setValidity(errorKey, parseValid); + if (!parseValid) { + forEach(ctrl.$validators, function (v, name) { + setValidity(name, null); + }); + forEach(ctrl.$asyncValidators, function (v, name) { + setValidity(name, null); + }); + return false; + } + } + return true; + } + + function processSyncValidators() { + var syncValidatorsValid = true; + forEach(ctrl.$validators, function (validator, name) { + var result = validator(modelValue, viewValue); + syncValidatorsValid = syncValidatorsValid && result; + setValidity(name, result); + }); + if (!syncValidatorsValid) { + forEach(ctrl.$asyncValidators, function (v, name) { + setValidity(name, null); + }); + return false; + } + return true; + } + + function processAsyncValidators() { + var validatorPromises = []; + var allValid = true; + forEach(ctrl.$asyncValidators, function (validator, name) { + var promise = validator(modelValue, viewValue); + if (!isPromiseLike(promise)) { + throw $ngModelMinErr("$asyncValidators", + "Expected asynchronous validator to return a promise but got '{0}' instead.", promise); + } + setValidity(name, undefined); + validatorPromises.push(promise.then(function () { + setValidity(name, true); + }, function (error) { + allValid = false; + setValidity(name, false); + })); + }); + if (!validatorPromises.length) { + validationDone(true); + } else { + $q.all(validatorPromises).then(function () { + validationDone(allValid); + }, noop); + } + } + + function setValidity(name, isValid) { + if (localValidationRunId === currentValidationRunId) { + ctrl.$setValidity(name, isValid); + } + } - function processAsyncValidators() { - var validatorPromises = []; - var allValid = true; - forEach(ctrl.$asyncValidators, function(validator, name) { - var promise = validator(modelValue, viewValue); - if (!isPromiseLike(promise)) { - throw $ngModelMinErr("$asyncValidators", - "Expected asynchronous validator to return a promise but got '{0}' instead.", promise); - } - setValidity(name, undefined); - validatorPromises.push(promise.then(function() { - setValidity(name, true); - }, function(error) { - allValid = false; - setValidity(name, false); - })); - }); - if (!validatorPromises.length) { - validationDone(true); - } else { - $q.all(validatorPromises).then(function() { - validationDone(allValid); - }, noop); - } - } + function validationDone(allValid) { + if (localValidationRunId === currentValidationRunId) { - function setValidity(name, isValid) { - if (localValidationRunId === currentValidationRunId) { - ctrl.$setValidity(name, isValid); - } - } + doneCallback(allValid); + } + } + }; - function validationDone(allValid) { - if (localValidationRunId === currentValidationRunId) { + /** + * @ngdoc method + * @name ngModel.NgModelController#$commitViewValue + * + * @description + * Commit a pending update to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + this.$commitViewValue = function () { + var viewValue = ctrl.$viewValue; + + $timeout.cancel(pendingDebounce); + + // If the view value has not changed then we should just exit, except in the case where there is + // a native validator on the element. In this case the validation state may have changed even though + // the viewValue has stayed empty. + if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) { + return; + } + ctrl.$$lastCommittedViewValue = viewValue; + + // change to dirty + if (ctrl.$pristine) { + ctrl.$dirty = true; + ctrl.$pristine = false; + $animate.removeClass($element, PRISTINE_CLASS); + $animate.addClass($element, DIRTY_CLASS); + parentForm.$setDirty(); + } + this.$$parseAndValidate(); + }; - doneCallback(allValid); - } - } - }; + this.$$parseAndValidate = function () { + var viewValue = ctrl.$$lastCommittedViewValue; + var modelValue = viewValue; + var parserValid = isUndefined(modelValue) ? undefined : true; + + if (parserValid) { + for (var i = 0; i < ctrl.$parsers.length; i++) { + modelValue = ctrl.$parsers[i](modelValue); + if (isUndefined(modelValue)) { + parserValid = false; + break; + } + } + } + if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { + // ctrl.$modelValue has not been touched yet... + ctrl.$modelValue = ngModelGet(); + } + var prevModelValue = ctrl.$modelValue; + var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; + if (allowInvalid) { + ctrl.$modelValue = modelValue; + writeToModelIfNeeded(); + } + ctrl.$$runValidators(parserValid, modelValue, viewValue, function (allValid) { + if (!allowInvalid) { + // Note: Don't check ctrl.$valid here, as we could have + // external validators (e.g. calculated on the server), + // that just call $setValidity and need the model value + // to calculate their validity. + ctrl.$modelValue = allValid ? modelValue : undefined; + writeToModelIfNeeded(); + } + }); - /** - * @ngdoc method - * @name ngModel.NgModelController#$commitViewValue - * - * @description - * Commit a pending update to the `$modelValue`. - * - * Updates may be pending by a debounced event or because the input is waiting for a some future - * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` - * usually handles calling this in response to input events. - */ - this.$commitViewValue = function() { - var viewValue = ctrl.$viewValue; - - $timeout.cancel(pendingDebounce); - - // If the view value has not changed then we should just exit, except in the case where there is - // a native validator on the element. In this case the validation state may have changed even though - // the viewValue has stayed empty. - if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) { - return; - } - ctrl.$$lastCommittedViewValue = viewValue; - - // change to dirty - if (ctrl.$pristine) { - ctrl.$dirty = true; - ctrl.$pristine = false; - $animate.removeClass($element, PRISTINE_CLASS); - $animate.addClass($element, DIRTY_CLASS); - parentForm.$setDirty(); - } - this.$$parseAndValidate(); - }; - - this.$$parseAndValidate = function() { - var viewValue = ctrl.$$lastCommittedViewValue; - var modelValue = viewValue; - var parserValid = isUndefined(modelValue) ? undefined : true; - - if (parserValid) { - for(var i = 0; i < ctrl.$parsers.length; i++) { - modelValue = ctrl.$parsers[i](modelValue); - if (isUndefined(modelValue)) { - parserValid = false; - break; - } - } - } - if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { - // ctrl.$modelValue has not been touched yet... - ctrl.$modelValue = ngModelGet(); - } - var prevModelValue = ctrl.$modelValue; - var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; - if (allowInvalid) { - ctrl.$modelValue = modelValue; - writeToModelIfNeeded(); - } - ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) { - if (!allowInvalid) { - // Note: Don't check ctrl.$valid here, as we could have - // external validators (e.g. calculated on the server), - // that just call $setValidity and need the model value - // to calculate their validity. - ctrl.$modelValue = allValid ? modelValue : undefined; - writeToModelIfNeeded(); - } - }); + function writeToModelIfNeeded() { + if (ctrl.$modelValue !== prevModelValue) { + ctrl.$$writeModelToScope(); + } + } + }; - function writeToModelIfNeeded() { - if (ctrl.$modelValue !== prevModelValue) { - ctrl.$$writeModelToScope(); - } - } - }; - - this.$$writeModelToScope = function() { - ngModelSet(ctrl.$modelValue); - forEach(ctrl.$viewChangeListeners, function(listener) { - try { - listener(); - } catch(e) { - $exceptionHandler(e); - } - }); - }; + this.$$writeModelToScope = function () { + ngModelSet(ctrl.$modelValue); + forEach(ctrl.$viewChangeListeners, function (listener) { + try { + listener(); + } catch (e) { + $exceptionHandler(e); + } + }); + }; - /** - * @ngdoc method - * @name ngModel.NgModelController#$setViewValue - * - * @description - * Update the view value. - * - * This method should be called when an input directive want to change the view value; typically, - * this is done from within a DOM event handler. - * - * For example {@link ng.directive:input input} calls it when the value of the input changes and - * {@link ng.directive:select select} calls it when an option is selected. - * - * If the new `value` is an object (rather than a string or a number), we should make a copy of the - * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep - * watch of objects, it only looks for a change of identity. If you only change the property of - * the object then ngModel will not realise that the object has changed and will not invoke the - * `$parsers` and `$validators` pipelines. - * - * For this reason, you should not change properties of the copy once it has been passed to - * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly. - * - * When this method is called, the new `value` will be staged for committing through the `$parsers` - * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged - * value sent directly for processing, finally to be applied to `$modelValue` and then the - * **expression** specified in the `ng-model` attribute. - * - * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. - * - * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` - * and the `default` trigger is not listed, all those actions will remain pending until one of the - * `updateOn` events is triggered on the DOM element. - * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} - * directive is used with a custom debounce for this particular event. - * - * Note that calling this function does not trigger a `$digest`. - * - * @param {string} value Value from the view. - * @param {string} trigger Event that triggered the update. - */ - this.$setViewValue = function(value, trigger) { - ctrl.$viewValue = value; - if (!ctrl.$options || ctrl.$options.updateOnDefault) { - ctrl.$$debounceViewValueCommit(trigger); - } - }; - - this.$$debounceViewValueCommit = function(trigger) { - var debounceDelay = 0, - options = ctrl.$options, - debounce; - - if (options && isDefined(options.debounce)) { - debounce = options.debounce; - if (isNumber(debounce)) { - debounceDelay = debounce; - } else if (isNumber(debounce[trigger])) { - debounceDelay = debounce[trigger]; - } else if (isNumber(debounce['default'])) { - debounceDelay = debounce['default']; - } - } + /** + * @ngdoc method + * @name ngModel.NgModelController#$setViewValue + * + * @description + * Update the view value. + * + * This method should be called when an input directive want to change the view value; typically, + * this is done from within a DOM event handler. + * + * For example {@link ng.directive:input input} calls it when the value of the input changes and + * {@link ng.directive:select select} calls it when an option is selected. + * + * If the new `value` is an object (rather than a string or a number), we should make a copy of the + * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep + * watch of objects, it only looks for a change of identity. If you only change the property of + * the object then ngModel will not realise that the object has changed and will not invoke the + * `$parsers` and `$validators` pipelines. + * + * For this reason, you should not change properties of the copy once it has been passed to + * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly. + * + * When this method is called, the new `value` will be staged for committing through the `$parsers` + * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged + * value sent directly for processing, finally to be applied to `$modelValue` and then the + * **expression** specified in the `ng-model` attribute. + * + * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. + * + * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` + * and the `default` trigger is not listed, all those actions will remain pending until one of the + * `updateOn` events is triggered on the DOM element. + * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} + * directive is used with a custom debounce for this particular event. + * + * Note that calling this function does not trigger a `$digest`. + * + * @param {string} value Value from the view. + * @param {string} trigger Event that triggered the update. + */ + this.$setViewValue = function (value, trigger) { + ctrl.$viewValue = value; + if (!ctrl.$options || ctrl.$options.updateOnDefault) { + ctrl.$$debounceViewValueCommit(trigger); + } + }; - $timeout.cancel(pendingDebounce); - if (debounceDelay) { - pendingDebounce = $timeout(function() { - ctrl.$commitViewValue(); - }, debounceDelay); - } else if ($rootScope.$$phase) { - ctrl.$commitViewValue(); - } else { - $scope.$apply(function() { - ctrl.$commitViewValue(); - }); - } - }; - - // model -> value - // Note: we cannot use a normal scope.$watch as we want to detect the following: - // 1. scope value is 'a' - // 2. user enters 'b' - // 3. ng-change kicks in and reverts scope value to 'a' - // -> scope value did not change since the last digest as - // ng-change executes in apply phase - // 4. view should be changed back to 'a' - $scope.$watch(function ngModelWatch() { - var modelValue = ngModelGet(); - - // if scope model value and ngModel value are out of sync - // TODO(perf): why not move this to the action fn? - if (modelValue !== ctrl.$modelValue) { - ctrl.$modelValue = modelValue; - - var formatters = ctrl.$formatters, - idx = formatters.length; - - var viewValue = modelValue; - while(idx--) { - viewValue = formatters[idx](viewValue); - } - if (ctrl.$viewValue !== viewValue) { - ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; - ctrl.$render(); + this.$$debounceViewValueCommit = function (trigger) { + var debounceDelay = 0, + options = ctrl.$options, + debounce; + + if (options && isDefined(options.debounce)) { + debounce = options.debounce; + if (isNumber(debounce)) { + debounceDelay = debounce; + } else if (isNumber(debounce[trigger])) { + debounceDelay = debounce[trigger]; + } else if (isNumber(debounce['default'])) { + debounceDelay = debounce['default']; + } + } - ctrl.$$runValidators(undefined, modelValue, viewValue, noop); - } - } + $timeout.cancel(pendingDebounce); + if (debounceDelay) { + pendingDebounce = $timeout(function () { + ctrl.$commitViewValue(); + }, debounceDelay); + } else if ($rootScope.$$phase) { + ctrl.$commitViewValue(); + } else { + $scope.$apply(function () { + ctrl.$commitViewValue(); + }); + } + }; - return modelValue; - }); -}]; + // model -> value + // Note: we cannot use a normal scope.$watch as we want to detect the following: + // 1. scope value is 'a' + // 2. user enters 'b' + // 3. ng-change kicks in and reverts scope value to 'a' + // -> scope value did not change since the last digest as + // ng-change executes in apply phase + // 4. view should be changed back to 'a' + $scope.$watch(function ngModelWatch() { + var modelValue = ngModelGet(); + + // if scope model value and ngModel value are out of sync + // TODO(perf): why not move this to the action fn? + if (modelValue !== ctrl.$modelValue) { + ctrl.$modelValue = modelValue; + + var formatters = ctrl.$formatters, + idx = formatters.length; + + var viewValue = modelValue; + while (idx--) { + viewValue = formatters[idx](viewValue); + } + if (ctrl.$viewValue !== viewValue) { + ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; + ctrl.$render(); + ctrl.$$runValidators(undefined, modelValue, viewValue, noop); + } + } -/** - * @ngdoc directive - * @name ngModel - * - * @element input - * - * @description - * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a - * property on the scope using {@link ngModel.NgModelController NgModelController}, - * which is created and exposed by this directive. - * - * `ngModel` is responsible for: - * - * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` - * require. - * - Providing validation behavior (i.e. required, number, email, url). - * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). - * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations. - * - Registering the control with its parent {@link ng.directive:form form}. - * - * Note: `ngModel` will try to bind to the property given by evaluating the expression on the - * current scope. If the property doesn't already exist on this scope, it will be created - * implicitly and added to the scope. - * - * For best practices on using `ngModel`, see: - * - * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes] - * - * For basic examples, how to use `ngModel`, see: - * - * - {@link ng.directive:input input} - * - {@link input[text] text} - * - {@link input[checkbox] checkbox} - * - {@link input[radio] radio} - * - {@link input[number] number} - * - {@link input[email] email} - * - {@link input[url] url} - * - {@link input[date] date} - * - {@link input[dateTimeLocal] dateTimeLocal} - * - {@link input[time] time} - * - {@link input[month] month} - * - {@link input[week] week} - * - {@link ng.directive:select select} - * - {@link ng.directive:textarea textarea} - * - * # CSS classes - * The following CSS classes are added and removed on the associated input/select/textarea element - * depending on the validity of the model. - * - * - `ng-valid` is set if the model is valid. - * - `ng-invalid` is set if the model is invalid. - * - `ng-pristine` is set if the model is pristine. - * - `ng-dirty` is set if the model is dirty. - * - * Keep in mind that ngAnimate can detect each of these classes when added and removed. - * - * ## Animation Hooks - * - * Animations within models are triggered when any of the associated CSS classes are added and removed - * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, - * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. - * The animations that are triggered within ngModel are similar to how they work in ngClass and - * animations can be hooked into using CSS transitions, keyframes as well as JS animations. - * - * The following example shows a simple way to utilize CSS transitions to style an input element - * that has been rendered as invalid after it has been validated: - * - *
          - * //be sure to include ngAnimate as a module to hook into more
          - * //advanced animations
          - * .my-input {
          +                return modelValue;
          +            });
          +        }];
          +
          +
          +    /**
          +     * @ngdoc directive
          +     * @name ngModel
          +     *
          +     * @element input
          +     *
          +     * @description
          +     * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
          +     * property on the scope using {@link ngModel.NgModelController NgModelController},
          +     * which is created and exposed by this directive.
          +     *
          +     * `ngModel` is responsible for:
          +     *
          +     * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
          +     *   require.
          +     * - Providing validation behavior (i.e. required, number, email, url).
          +     * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
          +     * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
          +     * - Registering the control with its parent {@link ng.directive:form form}.
          +     *
          +     * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
          +     * current scope. If the property doesn't already exist on this scope, it will be created
          +     * implicitly and added to the scope.
          +     *
          +     * For best practices on using `ngModel`, see:
          +     *
          +     *  - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
          +     *
          +     * For basic examples, how to use `ngModel`, see:
          +     *
          +     *  - {@link ng.directive:input input}
          +     *    - {@link input[text] text}
          +     *    - {@link input[checkbox] checkbox}
          +     *    - {@link input[radio] radio}
          +     *    - {@link input[number] number}
          +     *    - {@link input[email] email}
          +     *    - {@link input[url] url}
          +     *    - {@link input[date] date}
          +     *    - {@link input[dateTimeLocal] dateTimeLocal}
          +     *    - {@link input[time] time}
          +     *    - {@link input[month] month}
          +     *    - {@link input[week] week}
          +     *  - {@link ng.directive:select select}
          +     *  - {@link ng.directive:textarea textarea}
          +     *
          +     * # CSS classes
          +     * The following CSS classes are added and removed on the associated input/select/textarea element
          +     * depending on the validity of the model.
          +     *
          +     *  - `ng-valid` is set if the model is valid.
          +     *  - `ng-invalid` is set if the model is invalid.
          +     *  - `ng-pristine` is set if the model is pristine.
          +     *  - `ng-dirty` is set if the model is dirty.
          +     *
          +     * Keep in mind that ngAnimate can detect each of these classes when added and removed.
          +     *
          +     * ## Animation Hooks
          +     *
          +     * Animations within models are triggered when any of the associated CSS classes are added and removed
          +     * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
          +     * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
          +     * The animations that are triggered within ngModel are similar to how they work in ngClass and
          +     * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
          +     *
          +     * The following example shows a simple way to utilize CSS transitions to style an input element
          +     * that has been rendered as invalid after it has been validated:
          +     *
          +     * 
          +     * //be sure to include ngAnimate as a module to hook into more
          +     * //advanced animations
          +     * .my-input {
            *   transition:0.5s linear all;
            *   background: white;
            * }
          - * .my-input.ng-invalid {
          +     * .my-input.ng-invalid {
            *   background: red;
            *   color:white;
            * }
          - * 
          - * - * @example - * + *
          + * + * @example + * - - - Update input to see transitions when valid/invalid. - Integer is a valid value. -
          - -
          + + Update input to see transitions when valid/invalid. + Integer is a valid value. +
          + +
          - *
          - * - * ## Binding to a getter/setter - * - * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a - * function that returns a representation of the model when called with zero arguments, and sets - * the internal state of a model when called with an argument. It's sometimes useful to use this - * for models that have an internal representation that's different than what the model exposes - * to the view. - * - *
          - * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more - * frequently than other parts of your code. - *
          - * - * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that - * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to - * a `
          `, which will enable this behavior for all ``s within it. See - * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. - * - * The following example shows how to use `ngModel` with a getter/setter: - * - * @example - * + * + * + * ## Binding to a getter/setter + * + * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a + * function that returns a representation of the model when called with zero arguments, and sets + * the internal state of a model when called with an argument. It's sometimes useful to use this + * for models that have an internal representation that's different than what the model exposes + * to the view. + * + *
          + * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more + * frequently than other parts of your code. + *
          + * + * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that + * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to + * a ``, which will enable this behavior for all ``s within it. See + * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. + * + * The following example shows how to use `ngModel` with a getter/setter: + * + * @example + * -
          - - Name: - - -
          user.name = 
          -
          +
          +
          + Name: + +
          +
          user.name = 
          +
          - angular.module('getterSetterExample', []) - .controller('ExampleController', ['$scope', function($scope) { + angular.module('getterSetterExample', []) + .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function (newName) { @@ -20722,113 +20851,113 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$ }; }]); - *
          - */ -var ngModelDirective = function() { - return { - restrict: 'A', - require: ['ngModel', '^?form', '^?ngModelOptions'], - controller: NgModelController, - // Prelink needs to run before any input directive - // so that we can set the NgModelOptions in NgModelController - // before anyone else uses it. - priority: 1, - compile: function ngModelCompile(element) { - // Setup initial state of the control - element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); - - return { - pre: function ngModelPreLink(scope, element, attr, ctrls) { - var modelCtrl = ctrls[0], - formCtrl = ctrls[1] || nullFormCtrl; - - modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); - - // notify others, especially parent forms - formCtrl.$addControl(modelCtrl); - - attr.$observe('name', function(newValue) { - if (modelCtrl.$name !== newValue) { - formCtrl.$$renameControl(modelCtrl, newValue); + * + */ + var ngModelDirective = function () { + return { + restrict: 'A', + require: ['ngModel', '^?form', '^?ngModelOptions'], + controller: NgModelController, + // Prelink needs to run before any input directive + // so that we can set the NgModelOptions in NgModelController + // before anyone else uses it. + priority: 1, + compile: function ngModelCompile(element) { + // Setup initial state of the control + element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); + + return { + pre: function ngModelPreLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || nullFormCtrl; + + modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); + + // notify others, especially parent forms + formCtrl.$addControl(modelCtrl); + + attr.$observe('name', function (newValue) { + if (modelCtrl.$name !== newValue) { + formCtrl.$$renameControl(modelCtrl, newValue); + } + }); + + scope.$on('$destroy', function () { + formCtrl.$removeControl(modelCtrl); + }); + }, + post: function ngModelPostLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0]; + if (modelCtrl.$options && modelCtrl.$options.updateOn) { + element.on(modelCtrl.$options.updateOn, function (ev) { + modelCtrl.$$debounceViewValueCommit(ev && ev.type); + }); + } + + element.on('blur', function (ev) { + if (modelCtrl.$touched) return; + + scope.$apply(function () { + modelCtrl.$setTouched(); + }); + }); + } + }; } - }); - - scope.$on('$destroy', function() { - formCtrl.$removeControl(modelCtrl); - }); - }, - post: function ngModelPostLink(scope, element, attr, ctrls) { - var modelCtrl = ctrls[0]; - if (modelCtrl.$options && modelCtrl.$options.updateOn) { - element.on(modelCtrl.$options.updateOn, function(ev) { - modelCtrl.$$debounceViewValueCommit(ev && ev.type); - }); - } - - element.on('blur', function(ev) { - if (modelCtrl.$touched) return; - - scope.$apply(function() { - modelCtrl.$setTouched(); - }); - }); - } - }; - } - }; -}; + }; + }; -/** - * @ngdoc directive - * @name ngChange - * - * @description - * Evaluate the given expression when the user changes the input. - * The expression is evaluated immediately, unlike the JavaScript onchange event - * which only triggers at the end of a change (usually, when the user leaves the - * form element or presses the return key). - * - * The `ngChange` expression is only evaluated when a change in the input value causes - * a new value to be committed to the model. - * - * It will not be evaluated: - * * if the value returned from the `$parsers` transformation pipeline has not changed - * * if the input has continued to be invalid since the model will stay `null` - * * if the model is changed programmatically and not by a change to the input value - * - * - * Note, this directive requires `ngModel` to be present. - * - * @element input - * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change - * in input value. - * - * @example - * - * - * - *
          - * - * - *
          - * debug = {{confirmed}}
          - * counter = {{counter}}
          - *
          - *
          - * - * var counter = element(by.binding('counter')); - * var debug = element(by.binding('confirmed')); - * - * it('should evaluate the expression if changing from view', function() { + * + *
          + * + * + *
          + * debug = {{confirmed}}
          + * counter = {{counter}}
          + *
          + *
          + * + * var counter = element(by.binding('counter')); + * var debug = element(by.binding('confirmed')); + * + * it('should evaluate the expression if changing from view', function() { * expect(counter.getText()).toContain('0'); * * element(by.id('ng-change-example1')).click(); @@ -20836,170 +20965,170 @@ var ngModelDirective = function() { * expect(counter.getText()).toContain('1'); * expect(debug.getText()).toContain('true'); * }); - * - * it('should not evaluate the expression if changing from model', function() { + * + * it('should not evaluate the expression if changing from model', function() { * element(by.id('ng-change-example2')).click(); * expect(counter.getText()).toContain('0'); * expect(debug.getText()).toContain('true'); * }); - * - *
          - */ -var ngChangeDirective = valueFn({ - restrict: 'A', - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - ctrl.$viewChangeListeners.push(function() { - scope.$eval(attr.ngChange); + * + * + */ + var ngChangeDirective = valueFn({ + restrict: 'A', + require: 'ngModel', + link: function (scope, element, attr, ctrl) { + ctrl.$viewChangeListeners.push(function () { + scope.$eval(attr.ngChange); + }); + } }); - } -}); - - -var requiredDirective = function() { - return { - restrict: 'A', - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - attr.required = true; // force truthy in case we are on non input element - ctrl.$validators.required = function(value) { - return !attr.required || !ctrl.$isEmpty(value); - }; - attr.$observe('required', function() { - ctrl.$validate(); - }); - } - }; -}; + var requiredDirective = function () { + return { + restrict: 'A', + require: '?ngModel', + link: function (scope, elm, attr, ctrl) { + if (!ctrl) return; + attr.required = true; // force truthy in case we are on non input element + + ctrl.$validators.required = function (value) { + return !attr.required || !ctrl.$isEmpty(value); + }; + attr.$observe('required', function () { + ctrl.$validate(); + }); + } + }; + }; -var patternDirective = function() { - return { - restrict: 'A', - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - var regexp, patternExp = attr.ngPattern || attr.pattern; - attr.$observe('pattern', function(regex) { - if (isString(regex) && regex.length > 0) { - regex = new RegExp(regex); - } + var patternDirective = function () { + return { + restrict: 'A', + require: '?ngModel', + link: function (scope, elm, attr, ctrl) { + if (!ctrl) return; + + var regexp, patternExp = attr.ngPattern || attr.pattern; + attr.$observe('pattern', function (regex) { + if (isString(regex) && regex.length > 0) { + regex = new RegExp(regex); + } - if (regex && !regex.test) { - throw minErr('ngPattern')('noregexp', - 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, - regex, startingTag(elm)); - } + if (regex && !regex.test) { + throw minErr('ngPattern')('noregexp', + 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, + regex, startingTag(elm)); + } - regexp = regex || undefined; - ctrl.$validate(); - }); + regexp = regex || undefined; + ctrl.$validate(); + }); - ctrl.$validators.pattern = function(value) { - return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); - }; - } - }; -}; + ctrl.$validators.pattern = function (value) { + return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); + }; + } + }; + }; -var maxlengthDirective = function() { - return { - restrict: 'A', - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; + var maxlengthDirective = function () { + return { + restrict: 'A', + require: '?ngModel', + link: function (scope, elm, attr, ctrl) { + if (!ctrl) return; + + var maxlength = 0; + attr.$observe('maxlength', function (value) { + maxlength = int(value) || 0; + ctrl.$validate(); + }); + ctrl.$validators.maxlength = function (modelValue, viewValue) { + return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength; + }; + } + }; + }; - var maxlength = 0; - attr.$observe('maxlength', function(value) { - maxlength = int(value) || 0; - ctrl.$validate(); - }); - ctrl.$validators.maxlength = function(modelValue, viewValue) { - return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength; - }; - } - }; -}; - -var minlengthDirective = function() { - return { - restrict: 'A', - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - - var minlength = 0; - attr.$observe('minlength', function(value) { - minlength = int(value) || 0; - ctrl.$validate(); - }); - ctrl.$validators.minlength = function(modelValue, viewValue) { - return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength; - }; - } - }; -}; + var minlengthDirective = function () { + return { + restrict: 'A', + require: '?ngModel', + link: function (scope, elm, attr, ctrl) { + if (!ctrl) return; + + var minlength = 0; + attr.$observe('minlength', function (value) { + minlength = int(value) || 0; + ctrl.$validate(); + }); + ctrl.$validators.minlength = function (modelValue, viewValue) { + return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength; + }; + } + }; + }; -/** - * @ngdoc directive - * @name ngList - * - * @description - * Text input that converts between a delimited string and an array of strings. The default - * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom - * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. - * - * The behaviour of the directive is affected by the use of the `ngTrim` attribute. - * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each - * list item is respected. This implies that the user of the directive is responsible for - * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a - * tab or newline character. - * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected - * when joining the list items back together) and whitespace around each list item is stripped - * before it is added to the model. - * - * ### Example with Validation - * - * - * - * angular.module('listExample', []) - * .controller('ExampleController', ['$scope', function($scope) { + /** + * @ngdoc directive + * @name ngList + * + * @description + * Text input that converts between a delimited string and an array of strings. The default + * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom + * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. + * + * The behaviour of the directive is affected by the use of the `ngTrim` attribute. + * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each + * list item is respected. This implies that the user of the directive is responsible for + * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a + * tab or newline character. + * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected + * when joining the list items back together) and whitespace around each list item is stripped + * before it is added to the model. + * + * ### Example with Validation + * + * + * + * angular.module('listExample', []) + * .controller('ExampleController', ['$scope', function($scope) { * $scope.names = ['morpheus', 'neo', 'trinity']; * }]); - * - * - *
          - * List: - * - * Required! - *
          - * names = {{names}}
          - * myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
          - * myForm.namesInput.$error = {{myForm.namesInput.$error}}
          - * myForm.$valid = {{myForm.$valid}}
          - * myForm.$error.required = {{!!myForm.$error.required}}
          - *
          - *
          - * - * var listInput = element(by.model('names')); - * var names = element(by.exactBinding('names')); - * var valid = element(by.binding('myForm.namesInput.$valid')); - * var error = element(by.css('span.error')); - * - * it('should initialize to model', function() { + * + * + *
          + * List: + * + * Required! + *
          + * names = {{names}}
          + * myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
          + * myForm.namesInput.$error = {{myForm.namesInput.$error}}
          + * myForm.$valid = {{myForm.$valid}}
          + * myForm.$error.required = {{!!myForm.$error.required}}
          + *
          + *
          + * + * var listInput = element(by.model('names')); + * var names = element(by.exactBinding('names')); + * var valid = element(by.binding('myForm.namesInput.$valid')); + * var error = element(by.css('span.error')); + * + * it('should initialize to model', function() { * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); * expect(valid.getText()).toContain('true'); * expect(error.getCssValue('display')).toBe('none'); * }); - * - * it('should be invalid if empty', function() { + * + * it('should be invalid if empty', function() { * listInput.clear(); * listInput.sendKeys(''); * @@ -21007,212 +21136,212 @@ var minlengthDirective = function() { * expect(valid.getText()).toContain('false'); * expect(error.getCssValue('display')).not.toBe('none'); * }); - * - *
          - * - * ### Example - splitting on whitespace - * - * - * - *
          {{ list | json }}
          - *
          - * - * it("should split the text by newlines", function() { + * + *
          + * + * ### Example - splitting on whitespace + * + * + * + *
          {{ list | json }}
          + *
          + * + * it("should split the text by newlines", function() { * var listInput = element(by.model('list')); * var output = element(by.binding('list | json')); * listInput.sendKeys('abc\ndef\nghi'); * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); * }); - * - *
          - * - * @element input - * @param {string=} ngList optional delimiter that should be used to split the value. - */ -var ngListDirective = function() { - return { - restrict: 'A', - priority: 100, - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - // We want to control whitespace trimming so we use this convoluted approach - // to access the ngList attribute, which doesn't pre-trim the attribute - var ngList = element.attr(attr.$attr.ngList) || ', '; - var trimValues = attr.ngTrim !== 'false'; - var separator = trimValues ? trim(ngList) : ngList; - - var parse = function(viewValue) { - // If the viewValue is invalid (say required but empty) it will be `undefined` - if (isUndefined(viewValue)) return; - - var list = []; - - if (viewValue) { - forEach(viewValue.split(separator), function(value) { - if (value) list.push(trimValues ? trim(value) : value); - }); - } + *
          + *
          + * + * @element input + * @param {string=} ngList optional delimiter that should be used to split the value. + */ + var ngListDirective = function () { + return { + restrict: 'A', + priority: 100, + require: 'ngModel', + link: function (scope, element, attr, ctrl) { + // We want to control whitespace trimming so we use this convoluted approach + // to access the ngList attribute, which doesn't pre-trim the attribute + var ngList = element.attr(attr.$attr.ngList) || ', '; + var trimValues = attr.ngTrim !== 'false'; + var separator = trimValues ? trim(ngList) : ngList; + + var parse = function (viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; + + var list = []; + + if (viewValue) { + forEach(viewValue.split(separator), function (value) { + if (value) list.push(trimValues ? trim(value) : value); + }); + } - return list; - }; + return list; + }; - ctrl.$parsers.push(parse); - ctrl.$formatters.push(function(value) { - if (isArray(value)) { - return value.join(ngList); - } + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function (value) { + if (isArray(value)) { + return value.join(ngList); + } - return undefined; - }); + return undefined; + }); - // Override the standard $isEmpty because an empty array means the input is empty. - ctrl.$isEmpty = function(value) { - return !value || !value.length; - }; - } - }; -}; + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function (value) { + return !value || !value.length; + }; + } + }; + }; -var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; -/** - * @ngdoc directive - * @name ngValue - * - * @description - * Binds the given expression to the value of `input[select]` or `input[radio]`, so - * that when the element is selected, the `ngModel` of that element is set to the - * bound value. - * - * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as - * shown below. - * - * @element input - * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute - * of the `input` element - * - * @example - - - -
          -

          Which is your favorite?

          - -
          You chose {{my.favorite}}
          -
          -
          - - var favorite = element(by.binding('my.favorite')); - - it('should initialize to model', function() { + +
          +

          Which is your favorite?

          + +
          You chose {{my.favorite}}
          +
          +
          + + var favorite = element(by.binding('my.favorite')); + + it('should initialize to model', function() { expect(favorite.getText()).toContain('unicorns'); }); - it('should bind the values to the inputs', function() { + it('should bind the values to the inputs', function() { element.all(by.model('my.favorite')).get(0).click(); expect(favorite.getText()).toContain('pizza'); }); - -
          - */ -var ngValueDirective = function() { - return { - restrict: 'A', - priority: 100, - compile: function(tpl, tplAttr) { - if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { - return function ngValueConstantLink(scope, elm, attr) { - attr.$set('value', scope.$eval(attr.ngValue)); - }; - } else { - return function ngValueLink(scope, elm, attr) { - scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value); - }); + + + */ + var ngValueDirective = function () { + return { + restrict: 'A', + priority: 100, + compile: function (tpl, tplAttr) { + if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { + return function ngValueConstantLink(scope, elm, attr) { + attr.$set('value', scope.$eval(attr.ngValue)); + }; + } else { + return function ngValueLink(scope, elm, attr) { + scope.$watch(attr.ngValue, function valueWatchAction(value) { + attr.$set('value', value); + }); + }; + } + } }; - } - } - }; -}; + }; -/** - * @ngdoc directive - * @name ngModelOptions - * - * @description - * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of - * events that will trigger a model update and/or a debouncing delay so that the actual update only - * takes place when a timer expires; this timer will be reset after another change takes place. - * - * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might - * be different than the value in the actual model. This means that if you update the model you - * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in - * order to make sure it is synchronized with the model and that any debounced action is canceled. - * - * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`} - * method is by making sure the input is placed inside a form that has a `name` attribute. This is - * important because `form` controllers are published to the related scope under the name in their - * `name` attribute. - * - * Any pending changes will take place immediately when an enclosing form is submitted via the - * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` - * to have access to the updated model. - * - * `ngModelOptions` has an effect on the element it's declared on and its descendants. - * - * @param {Object} ngModelOptions options to apply to the current model. Valid keys are: - * - `updateOn`: string specifying which event should be the input bound to. You can set several - * events using an space delimited list. There is a special event called `default` that - * matches the default events belonging of the control. - * - `debounce`: integer value which contains the debounce model update value in milliseconds. A - * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a - * custom value for each event. For example: - * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"` - * - `allowInvalid`: boolean value which indicates that the model can be set with values that did - * not validate correctly instead of the default behavior of setting the model to undefined. - * - `getterSetter`: boolean value which determines whether or not to treat functions bound to - `ngModel` as getters/setters. - * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for - * ``, ``, ... . Right now, the only supported value is `'UTC'`, - * otherwise the default timezone of the browser will be used. - * - * @example - - The following example shows how to override immediate updates. Changes on the inputs within the - form will update the model only when the control loses focus (blur event). If `escape` key is - pressed while the input field is focused, the value is reset to the value in the current model. - - - -
          -
          - Name: -
          - - Other data: -
          -
          -
          user.name = 
          -
          -
          - - angular.module('optionsExample', []) - .controller('ExampleController', ['$scope', function($scope) { + /** + * @ngdoc directive + * @name ngModelOptions + * + * @description + * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of + * events that will trigger a model update and/or a debouncing delay so that the actual update only + * takes place when a timer expires; this timer will be reset after another change takes place. + * + * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might + * be different than the value in the actual model. This means that if you update the model you + * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in + * order to make sure it is synchronized with the model and that any debounced action is canceled. + * + * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`} + * method is by making sure the input is placed inside a form that has a `name` attribute. This is + * important because `form` controllers are published to the related scope under the name in their + * `name` attribute. + * + * Any pending changes will take place immediately when an enclosing form is submitted via the + * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` + * to have access to the updated model. + * + * `ngModelOptions` has an effect on the element it's declared on and its descendants. + * + * @param {Object} ngModelOptions options to apply to the current model. Valid keys are: + * - `updateOn`: string specifying which event should be the input bound to. You can set several + * events using an space delimited list. There is a special event called `default` that + * matches the default events belonging of the control. + * - `debounce`: integer value which contains the debounce model update value in milliseconds. A + * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a + * custom value for each event. For example: + * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"` + * - `allowInvalid`: boolean value which indicates that the model can be set with values that did + * not validate correctly instead of the default behavior of setting the model to undefined. + * - `getterSetter`: boolean value which determines whether or not to treat functions bound to + `ngModel` as getters/setters. + * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for + * ``, ``, ... . Right now, the only supported value is `'UTC'`, + * otherwise the default timezone of the browser will be used. + * + * @example + + The following example shows how to override immediate updates. Changes on the inputs within the + form will update the model only when the control loses focus (blur event). If `escape` key is + pressed while the input field is focused, the value is reset to the value in the current model. + + + +
          +
          + Name: +
          + + Other data: +
          +
          +
          user.name = 
          +
          +
          + + angular.module('optionsExample', []) + .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say', data: '' }; $scope.cancel = function (e) { @@ -21221,13 +21350,13 @@ var ngValueDirective = function() { } }; }]); - - - var model = element(by.binding('user.name')); - var input = element(by.model('user.name')); - var other = element(by.model('user.data')); + + + var model = element(by.binding('user.name')); + var input = element(by.model('user.name')); + var other = element(by.model('user.data')); - it('should allow custom events', function() { + it('should allow custom events', function() { input.sendKeys(' hello'); input.click(); expect(model.getText()).toEqual('say'); @@ -21235,7 +21364,7 @@ var ngValueDirective = function() { expect(model.getText()).toEqual('say hello'); }); - it('should $rollbackViewValue when model changes', function() { + it('should $rollbackViewValue when model changes', function() { input.sendKeys(' hello'); expect(input.getAttribute('value')).toEqual('say hello'); input.sendKeys(protractor.Key.ESCAPE); @@ -21243,50 +21372,50 @@ var ngValueDirective = function() { other.click(); expect(model.getText()).toEqual('say'); }); - -
          - - This one shows how to debounce model changes. Model will be updated only 1 sec after last change. - If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. - - - -
          -
          - Name: - -
          -
          -
          user.name = 
          -
          -
          - - angular.module('optionsExample', []) - .controller('ExampleController', ['$scope', function($scope) { + +
          + + This one shows how to debounce model changes. Model will be updated only 1 sec after last change. + If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. + + + +
          +
          + Name: + +
          +
          +
          user.name = 
          +
          +
          + + angular.module('optionsExample', []) + .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say' }; }]); - -
          - - This one shows how to bind to getter/setters: - - - -
          -
          - Name: - -
          -
          user.name = 
          -
          -
          - - angular.module('getterSetterExample', []) - .controller('ExampleController', ['$scope', function($scope) { + +
          + + This one shows how to bind to getter/setters: + + + +
          +
          + Name: + +
          +
          user.name = 
          +
          +
          + + angular.module('getterSetterExample', []) + .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function (newName) { @@ -21294,175 +21423,175 @@ var ngValueDirective = function() { } }; }]); - -
          - */ -var ngModelOptionsDirective = function() { - return { - restrict: 'A', - controller: ['$scope', '$attrs', function($scope, $attrs) { - var that = this; - this.$options = $scope.$eval($attrs.ngModelOptions); - // Allow adding/overriding bound events - if (this.$options.updateOn !== undefined) { - this.$options.updateOnDefault = false; - // extract "default" pseudo-event from list of events that can trigger a model update - this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() { - that.$options.updateOnDefault = true; - return ' '; - })); - } else { - this.$options.updateOnDefault = true; - } - }] - }; -}; +
          +
          + */ + var ngModelOptionsDirective = function () { + return { + restrict: 'A', + controller: ['$scope', '$attrs', function ($scope, $attrs) { + var that = this; + this.$options = $scope.$eval($attrs.ngModelOptions); + // Allow adding/overriding bound events + if (this.$options.updateOn !== undefined) { + this.$options.updateOnDefault = false; + // extract "default" pseudo-event from list of events that can trigger a model update + this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function () { + that.$options.updateOnDefault = true; + return ' '; + })); + } else { + this.$options.updateOnDefault = true; + } + }] + }; + }; // helper methods -function addSetValidityMethod(context) { - var ctrl = context.ctrl, - $element = context.$element, - classCache = {}, - set = context.set, - unset = context.unset, - parentForm = context.parentForm, - $animate = context.$animate; - - classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); - - ctrl.$setValidity = setValidity; - - function setValidity(validationErrorKey, state, options) { - if (state === undefined) { - createAndSet('$pending', validationErrorKey, options); - } else { - unsetAndCleanup('$pending', validationErrorKey, options); - } - if (!isBoolean(state)) { - unset(ctrl.$error, validationErrorKey, options); - unset(ctrl.$$success, validationErrorKey, options); - } else { - if (state) { - unset(ctrl.$error, validationErrorKey, options); - set(ctrl.$$success, validationErrorKey, options); - } else { - set(ctrl.$error, validationErrorKey, options); - unset(ctrl.$$success, validationErrorKey, options); - } - } - if (ctrl.$pending) { - cachedToggleClass(PENDING_CLASS, true); - ctrl.$valid = ctrl.$invalid = undefined; - toggleValidationCss('', null); - } else { - cachedToggleClass(PENDING_CLASS, false); - ctrl.$valid = isObjectEmpty(ctrl.$error); - ctrl.$invalid = !ctrl.$valid; - toggleValidationCss('', ctrl.$valid); - } + function addSetValidityMethod(context) { + var ctrl = context.ctrl, + $element = context.$element, + classCache = {}, + set = context.set, + unset = context.unset, + parentForm = context.parentForm, + $animate = context.$animate; + + classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); + + ctrl.$setValidity = setValidity; + + function setValidity(validationErrorKey, state, options) { + if (state === undefined) { + createAndSet('$pending', validationErrorKey, options); + } else { + unsetAndCleanup('$pending', validationErrorKey, options); + } + if (!isBoolean(state)) { + unset(ctrl.$error, validationErrorKey, options); + unset(ctrl.$$success, validationErrorKey, options); + } else { + if (state) { + unset(ctrl.$error, validationErrorKey, options); + set(ctrl.$$success, validationErrorKey, options); + } else { + set(ctrl.$error, validationErrorKey, options); + unset(ctrl.$$success, validationErrorKey, options); + } + } + if (ctrl.$pending) { + cachedToggleClass(PENDING_CLASS, true); + ctrl.$valid = ctrl.$invalid = undefined; + toggleValidationCss('', null); + } else { + cachedToggleClass(PENDING_CLASS, false); + ctrl.$valid = isObjectEmpty(ctrl.$error); + ctrl.$invalid = !ctrl.$valid; + toggleValidationCss('', ctrl.$valid); + } - // re-read the state as the set/unset methods could have - // combined state in ctrl.$error[validationError] (used for forms), - // where setting/unsetting only increments/decrements the value, - // and does not replace it. - var combinedState; - if (ctrl.$pending && ctrl.$pending[validationErrorKey]) { - combinedState = undefined; - } else if (ctrl.$error[validationErrorKey]) { - combinedState = false; - } else if (ctrl.$$success[validationErrorKey]) { - combinedState = true; - } else { - combinedState = null; - } - toggleValidationCss(validationErrorKey, combinedState); - parentForm.$setValidity(validationErrorKey, combinedState, ctrl); - } + // re-read the state as the set/unset methods could have + // combined state in ctrl.$error[validationError] (used for forms), + // where setting/unsetting only increments/decrements the value, + // and does not replace it. + var combinedState; + if (ctrl.$pending && ctrl.$pending[validationErrorKey]) { + combinedState = undefined; + } else if (ctrl.$error[validationErrorKey]) { + combinedState = false; + } else if (ctrl.$$success[validationErrorKey]) { + combinedState = true; + } else { + combinedState = null; + } + toggleValidationCss(validationErrorKey, combinedState); + parentForm.$setValidity(validationErrorKey, combinedState, ctrl); + } - function createAndSet(name, value, options) { - if (!ctrl[name]) { - ctrl[name] = {}; - } - set(ctrl[name], value, options); - } + function createAndSet(name, value, options) { + if (!ctrl[name]) { + ctrl[name] = {}; + } + set(ctrl[name], value, options); + } - function unsetAndCleanup(name, value, options) { - if (ctrl[name]) { - unset(ctrl[name], value, options); - } - if (isObjectEmpty(ctrl[name])) { - ctrl[name] = undefined; - } - } - - function cachedToggleClass(className, switchValue) { - if (switchValue && !classCache[className]) { - $animate.addClass($element, className); - classCache[className] = true; - } else if (!switchValue && classCache[className]) { - $animate.removeClass($element, className); - classCache[className] = false; - } - } + function unsetAndCleanup(name, value, options) { + if (ctrl[name]) { + unset(ctrl[name], value, options); + } + if (isObjectEmpty(ctrl[name])) { + ctrl[name] = undefined; + } + } - function toggleValidationCss(validationErrorKey, isValid) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + function cachedToggleClass(className, switchValue) { + if (switchValue && !classCache[className]) { + $animate.addClass($element, className); + classCache[className] = true; + } else if (!switchValue && classCache[className]) { + $animate.removeClass($element, className); + classCache[className] = false; + } + } - cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true); - cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false); - } -} + function toggleValidationCss(validationErrorKey, isValid) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; -function isObjectEmpty(obj) { - if (obj) { - for (var prop in obj) { - return false; + cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true); + cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false); + } } - } - return true; -} -/** - * @ngdoc directive - * @name ngBind - * @restrict AC - * - * @description - * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element - * with the value of a given expression, and to update the text content when the value of that - * expression changes. - * - * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like - * `{{ expression }}` which is similar but less verbose. - * - * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily - * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an - * element attribute, it makes the bindings invisible to the user while the page is loading. - * - * An alternative solution to this problem would be using the - * {@link ng.directive:ngCloak ngCloak} directive. - * - * - * @element ANY - * @param {expression} ngBind {@link guide/expression Expression} to evaluate. - * - * @example - * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. - + function isObjectEmpty(obj) { + if (obj) { + for (var prop in obj) { + return false; + } + } + return true; + } + + /** + * @ngdoc directive + * @name ngBind + * @restrict AC + * + * @description + * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element + * with the value of a given expression, and to update the text content when the value of that + * expression changes. + * + * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like + * `{{ expression }}` which is similar but less verbose. + * + * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily + * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. + * + * An alternative solution to this problem would be using the + * {@link ng.directive:ngCloak ngCloak} directive. + * + * + * @element ANY + * @param {expression} ngBind {@link guide/expression Expression} to evaluate. + * + * @example + * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. + - -
          - Enter name:
          - Hello ! -
          + +
          + Enter name:
          + Hello ! +
          - it('should check ng-bind', function() { + it('should check ng-bind', function() { var nameInput = element(by.model('name')); expect(element(by.binding('name')).getText()).toBe('Whirled'); @@ -21471,60 +21600,60 @@ function isObjectEmpty(obj) { expect(element(by.binding('name')).getText()).toBe('world'); }); -
          - */ -var ngBindDirective = ['$compile', function($compile) { - return { - restrict: 'AC', - compile: function ngBindCompile(templateElement) { - $compile.$$addBindingClass(templateElement); - return function ngBindLink(scope, element, attr) { - $compile.$$addBindingInfo(element, attr.ngBind); - element = element[0]; - scope.$watch(attr.ngBind, function ngBindWatchAction(value) { - element.textContent = value === undefined ? '' : value; - }); - }; - } - }; -}]; +
          + */ + var ngBindDirective = ['$compile', function ($compile) { + return { + restrict: 'AC', + compile: function ngBindCompile(templateElement) { + $compile.$$addBindingClass(templateElement); + return function ngBindLink(scope, element, attr) { + $compile.$$addBindingInfo(element, attr.ngBind); + element = element[0]; + scope.$watch(attr.ngBind, function ngBindWatchAction(value) { + element.textContent = value === undefined ? '' : value; + }); + }; + } + }; + }]; -/** - * @ngdoc directive - * @name ngBindTemplate - * - * @description - * The `ngBindTemplate` directive specifies that the element - * text content should be replaced with the interpolation of the template - * in the `ngBindTemplate` attribute. - * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` - * expressions. This directive is needed since some HTML elements - * (such as TITLE and OPTION) cannot contain SPAN elements. - * - * @element ANY - * @param {string} ngBindTemplate template of form - * {{ expression }} to eval. - * - * @example - * Try it here: enter text in text box and watch the greeting change. - + /** + * @ngdoc directive + * @name ngBindTemplate + * + * @description + * The `ngBindTemplate` directive specifies that the element + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. + * + * @element ANY + * @param {string} ngBindTemplate template of form + * {{ expression }} to eval. + * + * @example + * Try it here: enter text in text box and watch the greeting change. + - -
          - Salutation:
          - Name:
          -
          
          -       
          + +
          + Salutation:
          + Name:
          +
          
          +     
          - it('should check ng-bind', function() { + it('should check ng-bind', function() { var salutationElem = element(by.binding('salutation')); var salutationInput = element(by.model('salutation')); var nameInput = element(by.model('name')); @@ -21539,59 +21668,59 @@ var ngBindDirective = ['$compile', function($compile) { expect(salutationElem.getText()).toBe('Greetings user!'); }); -
          - */ -var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { - return { - compile: function ngBindTemplateCompile(templateElement) { - $compile.$$addBindingClass(templateElement); - return function ngBindTemplateLink(scope, element, attr) { - var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); - $compile.$$addBindingInfo(element, interpolateFn.expressions); - element = element[0]; - attr.$observe('ngBindTemplate', function(value) { - element.textContent = value === undefined ? '' : value; - }); - }; - } - }; -}]; +
          + */ + var ngBindTemplateDirective = ['$interpolate', '$compile', function ($interpolate, $compile) { + return { + compile: function ngBindTemplateCompile(templateElement) { + $compile.$$addBindingClass(templateElement); + return function ngBindTemplateLink(scope, element, attr) { + var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); + $compile.$$addBindingInfo(element, interpolateFn.expressions); + element = element[0]; + attr.$observe('ngBindTemplate', function (value) { + element.textContent = value === undefined ? '' : value; + }); + }; + } + }; + }]; -/** - * @ngdoc directive - * @name ngBindHtml - * - * @description - * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link - * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` - * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in - * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to - * include "angular-sanitize.js" in your application. - * - * You may also bypass sanitization for values you know are safe. To do so, bind to - * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example - * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. - * - * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you - * will have an exception (instead of an exploit.) - * - * @element ANY - * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. - * - * @example + /** + * @ngdoc directive + * @name ngBindHtml + * + * @description + * Creates a binding that will innerHTML the result of evaluating the `expression` into the current + * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link + * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` + * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in + * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to + * include "angular-sanitize.js" in your application. + * + * You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. + * + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) + * + * @element ANY + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + * + * @example - + -
          -

          -
          +
          +

          +
          - angular.module('bindHtmlExample', ['ngSanitize']) - .controller('ExampleController', ['$scope', function($scope) { + angular.module('bindHtmlExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { $scope.myHTML = 'I am an HTMLstring with ' + 'links! and other stuff'; @@ -21599,218 +21728,218 @@ var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate - it('should check ng-bind-html', function() { + it('should check ng-bind-html', function() { expect(element(by.binding('myHTML')).getText()).toBe( 'I am an HTMLstring with links! and other stuff'); }); -
          - */ -var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { - return { - restrict: 'A', - compile: function ngBindHtmlCompile(tElement, tAttrs) { - var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); - var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { - return (value || '').toString(); - }); - $compile.$$addBindingClass(tElement); +
          + */ + var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function ($sce, $parse, $compile) { + return { + restrict: 'A', + compile: function ngBindHtmlCompile(tElement, tAttrs) { + var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); + var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { + return (value || '').toString(); + }); + $compile.$$addBindingClass(tElement); - return function ngBindHtmlLink(scope, element, attr) { - $compile.$$addBindingInfo(element, attr.ngBindHtml); + return function ngBindHtmlLink(scope, element, attr) { + $compile.$$addBindingInfo(element, attr.ngBindHtml); - scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { - // we re-evaluate the expr because we want a TrustedValueHolderType - // for $sce, not a string - element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || ''); - }); - }; - } - }; -}]; + scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { + // we re-evaluate the expr because we want a TrustedValueHolderType + // for $sce, not a string + element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || ''); + }); + }; + } + }; + }]; -function classDirective(name, selector) { - name = 'ngClass' + name; - return ['$animate', function($animate) { - return { - restrict: 'AC', - link: function(scope, element, attr) { - var oldVal; + function classDirective(name, selector) { + name = 'ngClass' + name; + return ['$animate', function ($animate) { + return { + restrict: 'AC', + link: function (scope, element, attr) { + var oldVal; + + scope.$watch(attr[name], ngClassWatchAction, true); + + attr.$observe('class', function (value) { + ngClassWatchAction(scope.$eval(attr[name])); + }); + + + if (name !== 'ngClass') { + scope.$watch('$index', function ($index, old$index) { + // jshint bitwise: false + var mod = $index & 1; + if (mod !== (old$index & 1)) { + var classes = arrayClasses(scope.$eval(attr[name])); + mod === selector ? + addClasses(classes) : + removeClasses(classes); + } + }); + } - scope.$watch(attr[name], ngClassWatchAction, true); + function addClasses(classes) { + var newClasses = digestClassCounts(classes, 1); + attr.$addClass(newClasses); + } - attr.$observe('class', function(value) { - ngClassWatchAction(scope.$eval(attr[name])); - }); + function removeClasses(classes) { + var newClasses = digestClassCounts(classes, -1); + attr.$removeClass(newClasses); + } + function digestClassCounts(classes, count) { + var classCounts = element.data('$classCounts') || {}; + var classesToUpdate = []; + forEach(classes, function (className) { + if (count > 0 || classCounts[className]) { + classCounts[className] = (classCounts[className] || 0) + count; + if (classCounts[className] === +(count > 0)) { + classesToUpdate.push(className); + } + } + }); + element.data('$classCounts', classCounts); + return classesToUpdate.join(' '); + } - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - // jshint bitwise: false - var mod = $index & 1; - if (mod !== (old$index & 1)) { - var classes = arrayClasses(scope.$eval(attr[name])); - mod === selector ? - addClasses(classes) : - removeClasses(classes); - } - }); - } + function updateClasses(oldClasses, newClasses) { + var toAdd = arrayDifference(newClasses, oldClasses); + var toRemove = arrayDifference(oldClasses, newClasses); + toAdd = digestClassCounts(toAdd, 1); + toRemove = digestClassCounts(toRemove, -1); + if (toAdd && toAdd.length) { + $animate.addClass(element, toAdd); + } + if (toRemove && toRemove.length) { + $animate.removeClass(element, toRemove); + } + } - function addClasses(classes) { - var newClasses = digestClassCounts(classes, 1); - attr.$addClass(newClasses); - } + function ngClassWatchAction(newVal) { + if (selector === true || scope.$index % 2 === selector) { + var newClasses = arrayClasses(newVal || []); + if (!oldVal) { + addClasses(newClasses); + } else if (!equals(newVal, oldVal)) { + var oldClasses = arrayClasses(oldVal); + updateClasses(oldClasses, newClasses); + } + } + oldVal = shallowCopy(newVal); + } + } + }; - function removeClasses(classes) { - var newClasses = digestClassCounts(classes, -1); - attr.$removeClass(newClasses); - } + function arrayDifference(tokens1, tokens2) { + var values = []; - function digestClassCounts (classes, count) { - var classCounts = element.data('$classCounts') || {}; - var classesToUpdate = []; - forEach(classes, function (className) { - if (count > 0 || classCounts[className]) { - classCounts[className] = (classCounts[className] || 0) + count; - if (classCounts[className] === +(count > 0)) { - classesToUpdate.push(className); - } + outer: + for (var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for (var j = 0; j < tokens2.length; j++) { + if (token == tokens2[j]) continue outer; + } + values.push(token); + } + return values; } - }); - element.data('$classCounts', classCounts); - return classesToUpdate.join(' '); - } - - function updateClasses (oldClasses, newClasses) { - var toAdd = arrayDifference(newClasses, oldClasses); - var toRemove = arrayDifference(oldClasses, newClasses); - toAdd = digestClassCounts(toAdd, 1); - toRemove = digestClassCounts(toRemove, -1); - if (toAdd && toAdd.length) { - $animate.addClass(element, toAdd); - } - if (toRemove && toRemove.length) { - $animate.removeClass(element, toRemove); - } - } - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - var newClasses = arrayClasses(newVal || []); - if (!oldVal) { - addClasses(newClasses); - } else if (!equals(newVal,oldVal)) { - var oldClasses = arrayClasses(oldVal); - updateClasses(oldClasses, newClasses); + function arrayClasses(classVal) { + if (isArray(classVal)) { + return classVal; + } else if (isString(classVal)) { + return classVal.split(' '); + } else if (isObject(classVal)) { + var classes = [], i = 0; + forEach(classVal, function (v, k) { + if (v) { + classes = classes.concat(k.split(' ')); + } + }); + return classes; + } + return classVal; } - } - oldVal = shallowCopy(newVal); - } - } - }; - - function arrayDifference(tokens1, tokens2) { - var values = []; - - outer: - for(var i = 0; i < tokens1.length; i++) { - var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; - } - values.push(token); - } - return values; - } - - function arrayClasses (classVal) { - if (isArray(classVal)) { - return classVal; - } else if (isString(classVal)) { - return classVal.split(' '); - } else if (isObject(classVal)) { - var classes = [], i = 0; - forEach(classVal, function(v, k) { - if (v) { - classes = classes.concat(k.split(' ')); - } - }); - return classes; - } - return classVal; + }]; } - }]; -} -/** - * @ngdoc directive - * @name ngClass - * @restrict AC - * - * @description - * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding - * an expression that represents all classes to be added. - * - * The directive operates in three different ways, depending on which of three types the expression - * evaluates to: - * - * 1. If the expression evaluates to a string, the string should be one or more space-delimited class - * names. - * - * 2. If the expression evaluates to an array, each element of the array should be a string that is - * one or more space-delimited class names. - * - * 3. If the expression evaluates to an object, then for each key-value pair of the - * object with a truthy value the corresponding key is used as a class name. - * - * The directive won't add duplicate classes if a particular class was already set. - * - * When the expression changes, the previously added classes are removed and only then the - * new classes are added. - * - * @animations - * add - happens just before the class is applied to the element - * remove - happens just before the class is removed from the element - * - * @element ANY - * @param {expression} ngClass {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. In the case of a map, the - * names of the properties whose values are truthy will be added as css classes to the - * element. - * - * @example Example that demonstrates basic bindings via ngClass directive. - + /** + * @ngdoc directive + * @name ngClass + * @restrict AC + * + * @description + * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding + * an expression that represents all classes to be added. + * + * The directive operates in three different ways, depending on which of three types the expression + * evaluates to: + * + * 1. If the expression evaluates to a string, the string should be one or more space-delimited class + * names. + * + * 2. If the expression evaluates to an array, each element of the array should be a string that is + * one or more space-delimited class names. + * + * 3. If the expression evaluates to an object, then for each key-value pair of the + * object with a truthy value the corresponding key is used as a class name. + * + * The directive won't add duplicate classes if a particular class was already set. + * + * When the expression changes, the previously added classes are removed and only then the + * new classes are added. + * + * @animations + * add - happens just before the class is applied to the element + * remove - happens just before the class is removed from the element + * + * @element ANY + * @param {expression} ngClass {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. + * + * @example Example that demonstrates basic bindings via ngClass directive. + -

          Map Syntax Example

          - deleted (apply "strike" class)
          - important (apply "bold" class)
          - error (apply "red" class) -
          -

          Using String Syntax

          - -
          -

          Using Array Syntax

          -
          -
          -
          +

          Map Syntax Example

          + deleted (apply "strike" class)
          + important (apply "bold" class)
          + error (apply "red" class) +
          +

          Using String Syntax

          + +
          +

          Using Array Syntax

          +
          +
          +
          - .strike { + .strike { text-decoration: line-through; } - .bold { + .bold { font-weight: bold; } - .red { + .red { color: red; } - var ps = element.all(by.css('p')); + var ps = element.all(by.css('p')); - it('should let you toggle the class', function() { + it('should let you toggle the class', function() { expect(ps.first().getAttribute('class')).not.toMatch(/bold/); expect(ps.first().getAttribute('class')).not.toMatch(/red/); @@ -21822,14 +21951,14 @@ function classDirective(name, selector) { expect(ps.first().getAttribute('class')).toMatch(/red/); }); - it('should let you toggle string example', function() { + it('should let you toggle string example', function() { expect(ps.get(1).getAttribute('class')).toBe(''); element(by.model('style')).clear(); element(by.model('style')).sendKeys('red'); expect(ps.get(1).getAttribute('class')).toBe('red'); }); - it('array example should have 3 classes', function() { + it('array example should have 3 classes', function() { expect(ps.last().getAttribute('class')).toBe(''); element(by.model('style1')).sendKeys('bold'); element(by.model('style2')).sendKeys('strike'); @@ -21837,32 +21966,32 @@ function classDirective(name, selector) { expect(ps.last().getAttribute('class')).toBe('bold strike red'); }); -
          +
          - ## Animations + ## Animations - The example below demonstrates how to perform animations using ngClass. + The example below demonstrates how to perform animations using ngClass. - + - - -
          - Sample Text + + +
          + Sample Text
          - .base-class { + .base-class { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } - .base-class.my-class { + .base-class.my-class { color: red; font-size:3em; } - it('should check ng-class', function() { + it('should check ng-class', function() { expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); @@ -21877,289 +22006,289 @@ function classDirective(name, selector) { toMatch(/my-class/); }); -
          +
          - ## ngClass and pre-existing CSS3 Transitions/Animations - The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. - Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder - any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure - to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and - {@link ng.$animate#removeClass $animate.removeClass}. - */ -var ngClassDirective = classDirective('', true); + ## ngClass and pre-existing CSS3 Transitions/Animations + The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. + Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder + any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure + to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and + {@link ng.$animate#removeClass $animate.removeClass}. + */ + var ngClassDirective = classDirective('', true); -/** - * @ngdoc directive - * @name ngClassOdd - * @restrict AC - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. - * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class names or an array. - * - * @example - + /** + * @ngdoc directive + * @name ngClassOdd + * @restrict AC + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class names or an array. + * + * @example + -
            -
          1. - - {{name}} - -
          2. -
          +
            +
          1. + + {{name}} + +
          2. +
          - .odd { + .odd { color: red; } - .even { + .even { color: blue; } - it('should check ng-class-odd and ng-class-even', function() { + it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); -
          - */ -var ngClassOddDirective = classDirective('Odd', 0); +
          + */ + var ngClassOddDirective = classDirective('Odd', 0); -/** - * @ngdoc directive - * @name ngClassEven - * @restrict AC - * - * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. - * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The - * result of the evaluation can be a string representing space delimited class names or an array. - * - * @example - + /** + * @ngdoc directive + * @name ngClassEven + * @restrict AC + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The + * result of the evaluation can be a string representing space delimited class names or an array. + * + * @example + -
            -
          1. - - {{name}}       - -
          2. -
          +
            +
          1. + + {{name}}       + +
          2. +
          - .odd { + .odd { color: red; } - .even { + .even { color: blue; } - it('should check ng-class-odd and ng-class-even', function() { + it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); -
          - */ -var ngClassEvenDirective = classDirective('Even', 1); +
          + */ + var ngClassEvenDirective = classDirective('Even', 1); -/** - * @ngdoc directive - * @name ngCloak - * @restrict AC - * - * @description - * The `ngCloak` directive is used to prevent the Angular html template from being briefly - * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this - * directive to avoid the undesirable flicker effect caused by the html template display. - * - * The directive can be applied to the `` element, but the preferred usage is to apply - * multiple `ngCloak` directives to small portions of the page to permit progressive rendering - * of the browser view. - * - * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and - * `angular.min.js`. - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). - * - * ```css - * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { + /** + * @ngdoc directive + * @name ngCloak + * @restrict AC + * + * @description + * The `ngCloak` directive is used to prevent the Angular html template from being briefly + * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this + * directive to avoid the undesirable flicker effect caused by the html template display. + * + * The directive can be applied to the `` element, but the preferred usage is to apply + * multiple `ngCloak` directives to small portions of the page to permit progressive rendering + * of the browser view. + * + * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and + * `angular.min.js`. + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```css + * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none !important; * } - * ``` - * - * When this css rule is loaded by the browser, all html elements (including their children) that - * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive - * during the compilation of the template it deletes the `ngCloak` element attribute, making - * the compiled element visible. - * - * For the best result, the `angular.js` script must be loaded in the head section of the html - * document; alternatively, the css rule above must be included in the external stylesheet of the - * application. - * - * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they - * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css - * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. - * - * @element ANY - * - * @example - + * ``` + * + * When this css rule is loaded by the browser, all html elements (including their children) that + * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive + * during the compilation of the template it deletes the `ngCloak` element attribute, making + * the compiled element visible. + * + * For the best result, the `angular.js` script must be loaded in the head section of the html + * document; alternatively, the css rule above must be included in the external stylesheet of the + * application. + * + * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they + * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css + * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. + * + * @element ANY + * + * @example + -
          {{ 'hello' }}
          -
          {{ 'hello IE7' }}
          +
          {{ 'hello' }}
          +
          {{ 'hello IE7' }}
          - it('should remove the template directive and css class', function() { + it('should remove the template directive and css class', function() { expect($('#template1').getAttribute('ng-cloak')). toBeNull(); expect($('#template2').getAttribute('ng-cloak')). toBeNull(); }); -
          - * - */ -var ngCloakDirective = ngDirective({ - compile: function(element, attr) { - attr.$set('ngCloak', undefined); - element.removeClass('ng-cloak'); - } -}); +
          + * + */ + var ngCloakDirective = ngDirective({ + compile: function (element, attr) { + attr.$set('ngCloak', undefined); + element.removeClass('ng-cloak'); + } + }); -/** - * @ngdoc directive - * @name ngController - * - * @description - * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular - * supports the principles behind the Model-View-Controller design pattern. - * - * MVC components in angular: - * - * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties - * are accessed through bindings. - * * View — The template (HTML with data bindings) that is rendered into the View. - * * Controller — The `ngController` directive specifies a Controller class; the class contains business - * logic behind the application to decorate the scope with functions and values - * - * Note that you can also attach controllers to the DOM by declaring it in a route definition - * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller - * again using `ng-controller` in the template itself. This will cause the controller to be attached - * and executed twice. - * - * @element ANY - * @scope - * @priority 500 - * @param {expression} ngController Name of a constructor function registered with the current - * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} - * that on the current scope evaluates to a constructor function. - * - * The controller instance can be published into a scope property by specifying - * `ng-controller="as propertyName"`. - * - * If the current `$controllerProvider` is configured to use globals (via - * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may - * also be the name of a globally accessible constructor function (not recommended). - * - * @example - * Here is a simple form for editing user contact information. Adding, removing, clearing, and - * greeting are methods declared on the controller (see source tab). These methods can - * easily be called from the angular markup. Any changes to the data are automatically reflected - * in the View without the need for a manual update. - * - * Two different declaration styles are included below: - * - * * one binds methods and properties directly onto the controller using `this`: - * `ng-controller="SettingsController1 as settings"` - * * one injects `$scope` into the controller: - * `ng-controller="SettingsController2"` - * - * The second option is more common in the Angular community, and is generally used in boilerplates - * and in this guide. However, there are advantages to binding properties directly to the controller - * and avoiding scope. - * - * * Using `controller as` makes it obvious which controller you are accessing in the template when - * multiple controllers apply to an element. - * * If you are writing your controllers as classes you have easier access to the properties and - * methods, which will appear on the scope, from inside the controller code. - * * Since there is always a `.` in the bindings, you don't have to worry about prototypal - * inheritance masking primitives. - * - * This example demonstrates the `controller as` syntax. - * - * - * - *
          - * Name: - * [ greet ]
          - * Contact: - *
            - *
          • - * - * - * [ clear - * | X ] - *
          • - *
          • [ add ]
          • - *
          - *
          - *
          - * - * angular.module('controllerAsExample', []) - * .controller('SettingsController1', SettingsController1); - * - * function SettingsController1() { + /** + * @ngdoc directive + * @name ngController + * + * @description + * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular + * supports the principles behind the Model-View-Controller design pattern. + * + * MVC components in angular: + * + * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties + * are accessed through bindings. + * * View — The template (HTML with data bindings) that is rendered into the View. + * * Controller — The `ngController` directive specifies a Controller class; the class contains business + * logic behind the application to decorate the scope with functions and values + * + * Note that you can also attach controllers to the DOM by declaring it in a route definition + * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller + * again using `ng-controller` in the template itself. This will cause the controller to be attached + * and executed twice. + * + * @element ANY + * @scope + * @priority 500 + * @param {expression} ngController Name of a constructor function registered with the current + * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} + * that on the current scope evaluates to a constructor function. + * + * The controller instance can be published into a scope property by specifying + * `ng-controller="as propertyName"`. + * + * If the current `$controllerProvider` is configured to use globals (via + * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may + * also be the name of a globally accessible constructor function (not recommended). + * + * @example + * Here is a simple form for editing user contact information. Adding, removing, clearing, and + * greeting are methods declared on the controller (see source tab). These methods can + * easily be called from the angular markup. Any changes to the data are automatically reflected + * in the View without the need for a manual update. + * + * Two different declaration styles are included below: + * + * * one binds methods and properties directly onto the controller using `this`: + * `ng-controller="SettingsController1 as settings"` + * * one injects `$scope` into the controller: + * `ng-controller="SettingsController2"` + * + * The second option is more common in the Angular community, and is generally used in boilerplates + * and in this guide. However, there are advantages to binding properties directly to the controller + * and avoiding scope. + * + * * Using `controller as` makes it obvious which controller you are accessing in the template when + * multiple controllers apply to an element. + * * If you are writing your controllers as classes you have easier access to the properties and + * methods, which will appear on the scope, from inside the controller code. + * * Since there is always a `.` in the bindings, you don't have to worry about prototypal + * inheritance masking primitives. + * + * This example demonstrates the `controller as` syntax. + * + * + * + *
          + * Name: + * [ greet ]
          + * Contact: + *
            + *
          • + * + * + * [ clear + * | X ] + *
          • + *
          • [ add ]
          • + *
          + *
          + *
          + * + * angular.module('controllerAsExample', []) + * .controller('SettingsController1', SettingsController1); + * + * function SettingsController1() { * this.name = "John Smith"; * this.contacts = [ * {type: 'phone', value: '408 555 1212'}, * {type: 'email', value: 'john.smith@example.org'} ]; * } - * - * SettingsController1.prototype.greet = function() { + * + * SettingsController1.prototype.greet = function() { * alert(this.name); * }; - * - * SettingsController1.prototype.addContact = function() { + * + * SettingsController1.prototype.addContact = function() { * this.contacts.push({type: 'email', value: 'yourname@example.org'}); * }; - * - * SettingsController1.prototype.removeContact = function(contactToRemove) { + * + * SettingsController1.prototype.removeContact = function(contactToRemove) { * var index = this.contacts.indexOf(contactToRemove); * this.contacts.splice(index, 1); * }; - * - * SettingsController1.prototype.clearContact = function(contact) { + * + * SettingsController1.prototype.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; - * - * - * it('should check controller as', function() { + * + * + * it('should check controller as', function() { * var container = element(by.id('ctrl-as-exmpl')); * expect(container.element(by.model('settings.name')) * .getAttribute('value')).toBe('John Smith'); @@ -22187,36 +22316,36 @@ var ngCloakDirective = ngDirective({ * .getAttribute('value')) * .toBe('yourname@example.org'); * }); - * - *
          - * - * This example demonstrates the "attach to `$scope`" style of controller. - * - * - * - *
          - * Name: - * [ greet ]
          - * Contact: - *
            - *
          • - * - * - * [ clear - * | X ] - *
          • - *
          • [ add ]
          • - *
          - *
          - *
          - * - * angular.module('controllerExample', []) - * .controller('SettingsController2', ['$scope', SettingsController2]); - * - * function SettingsController2($scope) { + * + *
          + * + * This example demonstrates the "attach to `$scope`" style of controller. + * + * + * + *
          + * Name: + * [ greet ]
          + * Contact: + *
            + *
          • + * + * + * [ clear + * | X ] + *
          • + *
          • [ add ]
          • + *
          + *
          + *
          + * + * angular.module('controllerExample', []) + * .controller('SettingsController2', ['$scope', SettingsController2]); + * + * function SettingsController2($scope) { * $scope.name = "John Smith"; * $scope.contacts = [ * {type:'phone', value:'408 555 1212'}, @@ -22240,9 +22369,9 @@ var ngCloakDirective = ngDirective({ * contact.value = ''; * }; * } - * - * - * it('should check controller', function() { + * + * + * it('should check controller', function() { * var container = element(by.id('ctrl-exmpl')); * * expect(container.element(by.model('name')) @@ -22270,92 +22399,92 @@ var ngCloakDirective = ngDirective({ * .getAttribute('value')) * .toBe('yourname@example.org'); * }); - * - *
          + *
          + *
          - */ -var ngControllerDirective = [function() { - return { - restrict: 'A', - scope: true, - controller: '@', - priority: 500 - }; -}]; + */ + var ngControllerDirective = [function () { + return { + restrict: 'A', + scope: true, + controller: '@', + priority: 500 + }; + }]; -/** - * @ngdoc directive - * @name ngCsp - * - * @element html - * @description - * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. - * - * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. - * - * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). - * For Angular to be CSP compatible there are only two things that we need to do differently: - * - * - don't use `Function` constructor to generate optimized value getters - * - don't inject custom stylesheet into the document - * - * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` - * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will - * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will - * be raised. - * - * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically - * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). - * To make those directives work in CSP mode, include the `angular-csp.css` manually. - * - * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This - * autodetection however triggers a CSP error to be logged in the console: - * - * ``` - * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of - * script in the following Content Security Policy directive: "default-src 'self'". Note that - * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. - * ``` - * - * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` - * directive on the root element of the application or on the `angular.js` script tag, whichever - * appears first in the html document. - * - * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* - * - * @example - * This example shows how to apply the `ngCsp` directive to the `html` tag. - ```html + /** + * @ngdoc directive + * @name ngCsp + * + * @element html + * @description + * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. + * + * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. + * + * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). + * For Angular to be CSP compatible there are only two things that we need to do differently: + * + * - don't use `Function` constructor to generate optimized value getters + * - don't inject custom stylesheet into the document + * + * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` + * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will + * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will + * be raised. + * + * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically + * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). + * To make those directives work in CSP mode, include the `angular-csp.css` manually. + * + * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This + * autodetection however triggers a CSP error to be logged in the console: + * + * ``` + * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of + * script in the following Content Security Policy directive: "default-src 'self'". Note that + * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. + * ``` + * + * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` + * directive on the root element of the application or on the `angular.js` script tag, whichever + * appears first in the html document. + * + * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* + * + * @example + * This example shows how to apply the `ngCsp` directive to the `html` tag. + ```html ... ... - ``` - * @example - // Note: the suffix `.csp` in the example name triggers - // csp mode in our http server! - - -
          -
          - - - {{ctrl.counter}} - -
          - -
          - - - {{ctrl.evilError}} - -
          -
          -
          - - angular.module('cspExample', []) - .controller('MainController', function() { + ``` + * @example + // Note: the suffix `.csp` in the example name triggers + // csp mode in our http server! + + +
          +
          + + + {{ctrl.counter}} + +
          + +
          + + + {{ctrl.evilError}} + +
          +
          +
          + + angular.module('cspExample', []) + .controller('MainController', function() { this.counter = 0; this.inc = function() { this.counter++; @@ -22369,16 +22498,16 @@ var ngControllerDirective = [function() { } }; }); - - - var util, webdriver; + + + var util, webdriver; - var incBtn = element(by.id('inc')); - var counter = element(by.id('counter')); - var evilBtn = element(by.id('evil')); - var evilError = element(by.id('evilError')); + var incBtn = element(by.id('inc')); + var counter = element(by.id('counter')); + var evilBtn = element(by.id('evil')); + var evilError = element(by.id('evilError')); - function getAndClearSevereErrors() { + function getAndClearSevereErrors() { return browser.manage().logs().get('browser').then(function(browserLog) { return browserLog.filter(function(logEntry) { return logEntry.level.value > webdriver.logging.Level.WARNING.value; @@ -22386,11 +22515,11 @@ var ngControllerDirective = [function() { }); } - function clearErrors() { + function clearErrors() { getAndClearSevereErrors(); } - function expectNoErrors() { + function expectNoErrors() { getAndClearSevereErrors().then(function(filteredLog) { expect(filteredLog.length).toEqual(0); if (filteredLog.length) { @@ -22399,7 +22528,7 @@ var ngControllerDirective = [function() { }); } - function expectError(regex) { + function expectError(regex) { getAndClearSevereErrors().then(function(filteredLog) { var found = false; filteredLog.forEach(function(log) { @@ -22413,19 +22542,19 @@ var ngControllerDirective = [function() { }); } - beforeEach(function() { + beforeEach(function() { util = require('util'); webdriver = require('protractor/node_modules/selenium-webdriver'); }); - // For now, we only test on Chrome, - // as Safari does not load the page with Protractor's injected scripts, - // and Firefox webdriver always disables content security policy (#6358) - if (browser.params.browser !== 'chrome') { + // For now, we only test on Chrome, + // as Safari does not load the page with Protractor's injected scripts, + // and Firefox webdriver always disables content security policy (#6358) + if (browser.params.browser !== 'chrome') { return; } - it('should not report errors when the page is loaded', function() { + it('should not report errors when the page is loaded', function() { // clear errors so we are not dependent on previous tests clearErrors(); // Need to reload the page as the page is already loaded when @@ -22436,367 +22565,367 @@ var ngControllerDirective = [function() { expectNoErrors(); }); - it('should evaluate expressions', function() { + it('should evaluate expressions', function() { expect(counter.getText()).toEqual('0'); incBtn.click(); expect(counter.getText()).toEqual('1'); expectNoErrors(); }); - it('should throw and report an error when using "eval"', function() { + it('should throw and report an error when using "eval"', function() { evilBtn.click(); expect(evilError.getText()).toMatch(/Content Security Policy/); expectError(/Content Security Policy/); }); - -
          - */ +
          +
          + */ // ngCsp is not implemented as a proper directive any more, because we need it be processed while we // bootstrap the system (before $parse is instantiated), for this reason we just have // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc -/** - * @ngdoc directive - * @name ngClick - * - * @description - * The ngClick directive allows you to specify custom behavior when - * an element is clicked. - * - * @element ANY - * @priority 0 - * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon - * click. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngClick + * + * @description + * The ngClick directive allows you to specify custom behavior when + * an element is clicked. + * + * @element ANY + * @priority 0 + * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon + * click. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - - count: {{count}} - + + + count: {{count}} + - it('should check ng-click', function() { + it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); - - */ -/* - * A directive that allows creation of custom onclick handlers that are defined as angular - * expressions and are compiled and executed within the current scope. - * - * Events that are handled via these handler are always configured not to propagate further. - */ -var ngEventDirectives = {}; + + */ + /* + * A directive that allows creation of custom onclick handlers that are defined as angular + * expressions and are compiled and executed within the current scope. + * + * Events that are handled via these handler are always configured not to propagate further. + */ + var ngEventDirectives = {}; // For events that might fire synchronously during DOM manipulation // we need to execute their event handlers asynchronously using $evalAsync, // so that they are not executed in an inconsistent state. -var forceAsyncEvents = { - 'blur': true, - 'focus': true -}; -forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), - function(eventName) { - var directiveName = directiveNormalize('ng-' + eventName); - ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { - return { - restrict: 'A', - compile: function($element, attr) { - var fn = $parse(attr[directiveName]); - return function ngEventHandler(scope, element) { - element.on(eventName, function(event) { - var callback = function() { - fn(scope, {$event:event}); - }; - if (forceAsyncEvents[eventName] && $rootScope.$$phase) { - scope.$evalAsync(callback); - } else { - scope.$apply(callback); - } - }); - }; + var forceAsyncEvents = { + 'blur': true, + 'focus': true + }; + forEach( + 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), + function (eventName) { + var directiveName = directiveNormalize('ng-' + eventName); + ngEventDirectives[directiveName] = ['$parse', '$rootScope', function ($parse, $rootScope) { + return { + restrict: 'A', + compile: function ($element, attr) { + var fn = $parse(attr[directiveName]); + return function ngEventHandler(scope, element) { + element.on(eventName, function (event) { + var callback = function () { + fn(scope, {$event: event}); + }; + if (forceAsyncEvents[eventName] && $rootScope.$$phase) { + scope.$evalAsync(callback); + } else { + scope.$apply(callback); + } + }); + }; + } + }; + }]; } - }; - }]; - } -); + ); -/** - * @ngdoc directive - * @name ngDblclick - * - * @description - * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. - * - * @element ANY - * @priority 0 - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * a dblclick. (The Event object is available as `$event`) - * - * @example - + /** + * @ngdoc directive + * @name ngDblclick + * + * @description + * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. + * + * @element ANY + * @priority 0 + * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon + * a dblclick. (The Event object is available as `$event`) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMousedown - * - * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon - * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMousedown + * + * @description + * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon + * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMouseup - * - * @description - * Specify custom behavior on mouseup event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon - * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMouseup + * + * @description + * Specify custom behavior on mouseup event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon + * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMouseover - * - * @description - * Specify custom behavior on mouseover event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon - * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMouseover + * + * @description + * Specify custom behavior on mouseover event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon + * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMouseenter - * - * @description - * Specify custom behavior on mouseenter event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon - * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMouseenter + * + * @description + * Specify custom behavior on mouseenter event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon + * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMouseleave - * - * @description - * Specify custom behavior on mouseleave event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon - * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMouseleave + * + * @description + * Specify custom behavior on mouseleave event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon + * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngMousemove - * - * @description - * Specify custom behavior on mousemove event. - * - * @element ANY - * @priority 0 - * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon - * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngMousemove + * + * @description + * Specify custom behavior on mousemove event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon + * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - count: {{count}} + + count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngKeydown - * - * @description - * Specify custom behavior on keydown event. - * - * @element ANY - * @priority 0 - * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon - * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) - * - * @example - + /** + * @ngdoc directive + * @name ngKeydown + * + * @description + * Specify custom behavior on keydown event. + * + * @element ANY + * @priority 0 + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + - - key down count: {{count}} + + key down count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngKeyup - * - * @description - * Specify custom behavior on keyup event. - * - * @element ANY - * @priority 0 - * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon - * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) - * - * @example - + /** + * @ngdoc directive + * @name ngKeyup + * + * @description + * Specify custom behavior on keyup event. + * + * @element ANY + * @priority 0 + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + -

          Typing in the input box below updates the key count

          - key up count: {{count}} +

          Typing in the input box below updates the key count

          + key up count: {{count}} -

          Typing in the input box below updates the keycode

          - -

          event keyCode: {{ event.keyCode }}

          -

          event altKey: {{ event.altKey }}

          +

          Typing in the input box below updates the keycode

          + +

          event keyCode: {{ event.keyCode }}

          +

          event altKey: {{ event.altKey }}

          -
          - */ +
          + */ -/** - * @ngdoc directive - * @name ngKeypress - * - * @description - * Specify custom behavior on keypress event. - * - * @element ANY - * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon - * keypress. ({@link guide/expression#-event- Event object is available as `$event`} - * and can be interrogated for keyCode, altKey, etc.) - * - * @example - + /** + * @ngdoc directive + * @name ngKeypress + * + * @description + * Specify custom behavior on keypress event. + * + * @element ANY + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. ({@link guide/expression#-event- Event object is available as `$event`} + * and can be interrogated for keyCode, altKey, etc.) + * + * @example + - - key press count: {{count}} + + key press count: {{count}} - - */ + + */ -/** - * @ngdoc directive - * @name ngSubmit - * - * @description - * Enables binding angular expressions to onsubmit events. - * - * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page), but only if the form does not contain `action`, - * `data-action`, or `x-action` attributes. - * - *
          - * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and - * `ngSubmit` handlers together. See the - * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} - * for a detailed discussion of when `ngSubmit` may be triggered. - *
          - * - * @element form - * @priority 0 - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. - * ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngSubmit + * + * @description + * Enables binding angular expressions to onsubmit events. + * + * Additionally it prevents the default action (which for form means sending the request to the + * server and reloading the current page), but only if the form does not contain `action`, + * `data-action`, or `x-action` attributes. + * + *
          + * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and + * `ngSubmit` handlers together. See the + * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} + * for a detailed discussion of when `ngSubmit` may be triggered. + *
          + * + * @element form + * @priority 0 + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - -
          - Enter text and hit enter: - - -
          list={{list}}
          -
          + +
          + Enter text and hit enter: + + +
          list={{list}}
          +
          - it('should check ng-submit', function() { + it('should check ng-submit', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); expect(element(by.model('text')).getAttribute('value')).toBe(''); }); - it('should ignore empty strings', function() { + it('should ignore empty strings', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); }); -
          - */ +
          + */ -/** - * @ngdoc directive - * @name ngFocus - * - * @description - * Specify custom behavior on focus event. - * - * Note: As the `focus` event is executed synchronously when calling `input.focus()` - * AngularJS executes the expression using `scope.$evalAsync` if the event is fired - * during an `$apply` to ensure a consistent state. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon - * focus. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ + /** + * @ngdoc directive + * @name ngFocus + * + * @description + * Specify custom behavior on focus event. + * + * Note: As the `focus` event is executed synchronously when calling `input.focus()` + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ -/** - * @ngdoc directive - * @name ngBlur - * - * @description - * Specify custom behavior on blur event. - * - * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when - * an element has lost focus. - * - * Note: As the `blur` event is executed synchronously also during DOM manipulations - * (e.g. removing a focussed input), - * AngularJS executes the expression using `scope.$evalAsync` if the event is fired - * during an `$apply` to ensure a consistent state. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon - * blur. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ + /** + * @ngdoc directive + * @name ngBlur + * + * @description + * Specify custom behavior on blur event. + * + * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when + * an element has lost focus. + * + * Note: As the `blur` event is executed synchronously also during DOM manipulations + * (e.g. removing a focussed input), + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ -/** - * @ngdoc directive - * @name ngCopy - * - * @description - * Specify custom behavior on copy event. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon - * copy. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngCopy + * + * @description + * Specify custom behavior on copy event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon + * copy. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - copied: {{copied}} + + copied: {{copied}} - - */ + + */ -/** - * @ngdoc directive - * @name ngCut - * - * @description - * Specify custom behavior on cut event. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon - * cut. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngCut + * + * @description + * Specify custom behavior on cut event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon + * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - cut: {{cut}} + + cut: {{cut}} - - */ + + */ -/** - * @ngdoc directive - * @name ngPaste - * - * @description - * Specify custom behavior on paste event. - * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon - * paste. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - + /** + * @ngdoc directive + * @name ngPaste + * + * @description + * Specify custom behavior on paste event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon + * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + - - pasted: {{paste}} + + pasted: {{paste}} - - */ + + */ -/** - * @ngdoc directive - * @name ngIf - * @restrict A - * - * @description - * The `ngIf` directive removes or recreates a portion of the DOM tree based on an - * {expression}. If the expression assigned to `ngIf` evaluates to a false - * value then the element is removed from the DOM, otherwise a clone of the - * element is reinserted into the DOM. - * - * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the - * element in the DOM rather than changing its visibility via the `display` css property. A common - * case when this difference is significant is when using css selectors that rely on an element's - * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. - * - * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope - * is created when the element is restored. The scope created within `ngIf` inherits from - * its parent scope using - * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). - * An important implication of this is if `ngModel` is used within `ngIf` to bind to - * a javascript primitive defined in the parent scope. In this case any modifications made to the - * variable within the child scope will override (hide) the value in the parent scope. - * - * Also, `ngIf` recreates elements using their compiled state. An example of this behavior - * is if an element's class attribute is directly modified after it's compiled, using something like - * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element - * the added class will be lost because the original compiled state is used to regenerate the element. - * - * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` - * and `leave` effects. - * - * @animations - * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container - * leave - happens just before the `ngIf` contents are removed from the DOM - * - * @element ANY - * @scope - * @priority 600 - * @param {expression} ngIf If the {@link guide/expression expression} is falsy then - * the element is removed from the DOM tree. If it is truthy a copy of the compiled - * element is added to the DOM tree. - * - * @example - - - Click me:
          - Show when checked: - - This is removed when the checkbox is unchecked. - -
          - - .animate-if { + /** + * @ngdoc directive + * @name ngIf + * @restrict A + * + * @description + * The `ngIf` directive removes or recreates a portion of the DOM tree based on an + * {expression}. If the expression assigned to `ngIf` evaluates to a false + * value then the element is removed from the DOM, otherwise a clone of the + * element is reinserted into the DOM. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope + * is created when the element is restored. The scope created within `ngIf` inherits from + * its parent scope using + * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` + * and `leave` effects. + * + * @animations + * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container + * leave - happens just before the `ngIf` contents are removed from the DOM + * + * @element ANY + * @scope + * @priority 600 + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree. If it is truthy a copy of the compiled + * element is added to the DOM tree. + * + * @example + + + Click me:
          + Show when checked: + + This is removed when the checkbox is unchecked. + +
          + + .animate-if { background:white; border:1px solid black; padding:10px; } - .animate-if.ng-enter, .animate-if.ng-leave { + .animate-if.ng-enter, .animate-if.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } - .animate-if.ng-enter, - .animate-if.ng-leave.ng-leave-active { + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { opacity:0; } - .animate-if.ng-leave, - .animate-if.ng-enter.ng-enter-active { + .animate-if.ng-leave, + .animate-if.ng-enter.ng-enter-active { opacity:1; } - -
          - */ -var ngIfDirective = ['$animate', function($animate) { - return { - multiElement: true, - transclude: 'element', - priority: 600, - terminal: true, - restrict: 'A', - $$tlb: true, - link: function ($scope, $element, $attr, ctrl, $transclude) { - var block, childScope, previousElements; - $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { - - if (value) { - if (!childScope) { - $transclude(function (clone, newScope) { - childScope = newScope; - clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); - // Note: We only need the first/last node of the cloned nodes. - // However, we need to keep the reference to the jqlite wrapper as it might be changed later - // by a directive with templateUrl when its template arrives. - block = { - clone: clone - }; - $animate.enter(clone, $element.parent(), $element); - }); - } - } else { - if (previousElements) { - previousElements.remove(); - previousElements = null; - } - if (childScope) { - childScope.$destroy(); - childScope = null; - } - if (block) { - previousElements = getBlockNodes(block.clone); - $animate.leave(previousElements).then(function() { - previousElements = null; - }); - block = null; +
          +
          + */ + var ngIfDirective = ['$animate', function ($animate) { + return { + multiElement: true, + transclude: 'element', + priority: 600, + terminal: true, + restrict: 'A', + $$tlb: true, + link: function ($scope, $element, $attr, ctrl, $transclude) { + var block, childScope, previousElements; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + + if (value) { + if (!childScope) { + $transclude(function (clone, newScope) { + childScope = newScope; + clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block = { + clone: clone + }; + $animate.enter(clone, $element.parent(), $element); + }); + } + } else { + if (previousElements) { + previousElements.remove(); + previousElements = null; + } + if (childScope) { + childScope.$destroy(); + childScope = null; + } + if (block) { + previousElements = getBlockNodes(block.clone); + $animate.leave(previousElements).then(function () { + previousElements = null; + }); + block = null; + } + } + }); } - } - }); - } - }; -}]; + }; + }]; -/** - * @ngdoc directive - * @name ngInclude - * @restrict ECA - * - * @description - * Fetches, compiles and includes an external HTML fragment. - * - * By default, the template URL is restricted to the same domain and protocol as the - * application document. This is done by calling {@link $sce#getTrustedResourceUrl + /** + * @ngdoc directive + * @name ngInclude + * @restrict ECA + * + * @description + * Fetches, compiles and includes an external HTML fragment. + * + * By default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link $sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols - * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or - * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link - * ng.$sce Strict Contextual Escaping}. - * - * In addition, the browser's - * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) - * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) - * policy may further restrict whether the template is successfully loaded. - * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` - * access on some browsers. - * - * @animations - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. - * - * The enter and leave animation occur concurrently. - * - * @scope - * @priority 400 - * - * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, - * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. - * @param {string=} onload Expression to evaluate when a new partial is loaded. - * - * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll + * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or + * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link + * ng.$sce Strict Contextual Escaping}. + * + * In addition, the browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy may further restrict whether the template is successfully loaded. + * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * @priority 400 + * + * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, + * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. + * @param {string=} onload Expression to evaluate when a new partial is loaded. + * + * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. - * - * - If the attribute is not set, disable scrolling. - * - If the attribute is set without value, enable scrolling. - * - Otherwise enable scrolling only if the expression evaluates to truthy value. - * - * @example - - + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the expression evaluates to truthy value. + * + * @example + +
          - - url of the template: {{template.url}} -
          -
          -
          -
          + + url of the template: {{template.url}} +
          +
          +
          +
          -
          - - angular.module('includeExample', ['ngAnimate']) - .controller('ExampleController', ['$scope', function($scope) { + + + angular.module('includeExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; }]); - - Content of template1.html - - - Content of template2.html - - - .slide-animate-container { + + Content of template1.html + + + Content of template2.html + + + .slide-animate-container { position:relative; background:white; border:1px solid black; @@ -23142,11 +23271,11 @@ var ngIfDirective = ['$animate', function($animate) { overflow:hidden; } - .slide-animate { + .slide-animate { padding:10px; } - .slide-animate.ng-enter, .slide-animate.ng-leave { + .slide-animate.ng-enter, .slide-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; @@ -23159,29 +23288,29 @@ var ngIfDirective = ['$animate', function($animate) { padding:10px; } - .slide-animate.ng-enter { + .slide-animate.ng-enter { top:-50px; } - .slide-animate.ng-enter.ng-enter-active { + .slide-animate.ng-enter.ng-enter-active { top:0; } - .slide-animate.ng-leave { + .slide-animate.ng-leave { top:0; } - .slide-animate.ng-leave.ng-leave-active { + .slide-animate.ng-leave.ng-leave-active { top:50px; } - - - var templateSelect = element(by.model('template')); - var includeElem = element(by.css('[ng-include]')); + + + var templateSelect = element(by.model('template')); + var includeElem = element(by.css('[ng-include]')); - it('should load template1.html', function() { + it('should load template1.html', function() { expect(includeElem.getText()).toMatch(/Content of template1.html/); }); - it('should load template2.html', function() { + it('should load template2.html', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects // See https://github.com/angular/protractor/issues/480 @@ -23192,7 +23321,7 @@ var ngIfDirective = ['$animate', function($animate) { expect(includeElem.getText()).toMatch(/Content of template2.html/); }); - it('should change to blank', function() { + it('should change to blank', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects return; @@ -23201,208 +23330,208 @@ var ngIfDirective = ['$animate', function($animate) { templateSelect.all(by.css('option')).get(0).click(); expect(includeElem.isPresent()).toBe(false); }); - -
          - */ - - -/** - * @ngdoc event - * @name ngInclude#$includeContentRequested - * @eventType emit on the scope ngInclude was declared in - * @description - * Emitted every time the ngInclude content is requested. - * - * @param {Object} angularEvent Synthetic event object. - * @param {String} src URL of content to load. - */ - +
          +
          + */ -/** - * @ngdoc event - * @name ngInclude#$includeContentLoaded - * @eventType emit on the current ngInclude scope - * @description - * Emitted every time the ngInclude content is reloaded. - * - * @param {Object} angularEvent Synthetic event object. - * @param {String} src URL of content to load. - */ + /** + * @ngdoc event + * @name ngInclude#$includeContentRequested + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ -/** - * @ngdoc event - * @name ngInclude#$includeContentError - * @eventType emit on the scope ngInclude was declared in - * @description - * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299) - * - * @param {Object} angularEvent Synthetic event object. - * @param {String} src URL of content to load. - */ -var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce', - function($templateRequest, $anchorScroll, $animate, $sce) { - return { - restrict: 'ECA', - priority: 400, - terminal: true, - transclude: 'element', - controller: angular.noop, - compile: function(element, attr) { - var srcExp = attr.ngInclude || attr.src, - onloadExp = attr.onload || '', - autoScrollExp = attr.autoscroll; - - return function(scope, $element, $attr, ctrl, $transclude) { - var changeCounter = 0, - currentScope, - previousElement, - currentElement; - - var cleanupLastIncludeContent = function() { - if(previousElement) { - previousElement.remove(); - previousElement = null; - } - if(currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if(currentElement) { - $animate.leave(currentElement).then(function() { - previousElement = null; - }); - previousElement = currentElement; - currentElement = null; - } - }; - scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { - var afterAnimation = function() { - if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); - } - }; - var thisChangeId = ++changeCounter; - - if (src) { - //set the 2nd param to true to ignore the template request error so that the inner - //contents and scope can be cleaned up. - $templateRequest(src, true).then(function(response) { - if (thisChangeId !== changeCounter) return; - var newScope = scope.$new(); - ctrl.template = response; - - // Note: This will also link all children of ng-include that were contained in the original - // html. If that content contains controllers, ... they could pollute/change the scope. - // However, using ng-include on an element with additional content does not make sense... - // Note: We can't remove them in the cloneAttchFn of $transclude as that - // function is called before linking the content, which would apply child - // directives to non existing elements. - var clone = $transclude(newScope, function(clone) { - cleanupLastIncludeContent(); - $animate.enter(clone, null, $element).then(afterAnimation); - }); + /** + * @ngdoc event + * @name ngInclude#$includeContentLoaded + * @eventType emit on the current ngInclude scope + * @description + * Emitted every time the ngInclude content is reloaded. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ - currentScope = newScope; - currentElement = clone; - currentScope.$emit('$includeContentLoaded', src); - scope.$eval(onloadExp); - }, function() { - if (thisChangeId === changeCounter) { - cleanupLastIncludeContent(); - scope.$emit('$includeContentError', src); - } - }); - scope.$emit('$includeContentRequested', src); - } else { - cleanupLastIncludeContent(); - ctrl.template = null; - } - }); - }; - } - }; -}]; + /** + * @ngdoc event + * @name ngInclude#$includeContentError + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299) + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce', + function ($templateRequest, $anchorScroll, $animate, $sce) { + return { + restrict: 'ECA', + priority: 400, + terminal: true, + transclude: 'element', + controller: angular.noop, + compile: function (element, attr) { + var srcExp = attr.ngInclude || attr.src, + onloadExp = attr.onload || '', + autoScrollExp = attr.autoscroll; + + return function (scope, $element, $attr, ctrl, $transclude) { + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function () { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement).then(function () { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { + var afterAnimation = function () { + if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }; + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function (response) { + if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + ctrl.template = response; + + // Note: This will also link all children of ng-include that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-include on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function (clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, null, $element).then(afterAnimation); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + scope.$eval(onloadExp); + }, function () { + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + ctrl.template = null; + } + }); + }; + } + }; + }]; // This directive is called during the $transclude call of the first `ngInclude` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngInclude // is called. -var ngIncludeFillContentDirective = ['$compile', - function($compile) { - return { - restrict: 'ECA', - priority: -400, - require: 'ngInclude', - link: function(scope, $element, $attr, ctrl) { - if (/SVG/.test($element[0].toString())) { - // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not - // support innerHTML, so detect this here and try to generate the contents - // specially. - $element.empty(); - $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope, - function namespaceAdaptedClone(clone) { - $element.append(clone); - }, undefined, undefined, $element); - return; - } + var ngIncludeFillContentDirective = ['$compile', + function ($compile) { + return { + restrict: 'ECA', + priority: -400, + require: 'ngInclude', + link: function (scope, $element, $attr, ctrl) { + if (/SVG/.test($element[0].toString())) { + // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not + // support innerHTML, so detect this here and try to generate the contents + // specially. + $element.empty(); + $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope, + function namespaceAdaptedClone(clone) { + $element.append(clone); + }, undefined, undefined, $element); + return; + } - $element.html(ctrl.template); - $compile($element.contents())(scope); - } - }; - }]; + $element.html(ctrl.template); + $compile($element.contents())(scope); + } + }; + }]; -/** - * @ngdoc directive - * @name ngInit - * @restrict AC - * - * @description - * The `ngInit` directive allows you to evaluate an expression in the - * current scope. - * - *
          - * The only appropriate use of `ngInit` is for aliasing special properties of - * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you - * should use {@link guide/controller controllers} rather than `ngInit` - * to initialize values on a scope. - *
          - *
          - * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make - * sure you have parenthesis for correct precedence: - *
          - *   
          - *
          - *
          - * - * @priority 450 - * - * @element ANY - * @param {expression} ngInit {@link guide/expression Expression} to eval. - * - * @example - + /** + * @ngdoc directive + * @name ngInit + * @restrict AC + * + * @description + * The `ngInit` directive allows you to evaluate an expression in the + * current scope. + * + *
          + * The only appropriate use of `ngInit` is for aliasing special properties of + * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you + * should use {@link guide/controller controllers} rather than `ngInit` + * to initialize values on a scope. + *
          + *
          + * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make + * sure you have parenthesis for correct precedence: + *
          +     *   
          + *
          + *
          + * + * @priority 450 + * + * @element ANY + * @param {expression} ngInit {@link guide/expression Expression} to eval. + * + * @example + - -
          + +
          -
          - list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; -
          +
          + list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; +
          +
          -
          - it('should alias index positions', function() { + it('should alias index positions', function() { var elements = element.all(by.css('.example-init')); expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); @@ -23410,178 +23539,178 @@ var ngIncludeFillContentDirective = ['$compile', expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); -
          - */ -var ngInitDirective = ngDirective({ - priority: 450, - compile: function() { - return { - pre: function(scope, element, attrs) { - scope.$eval(attrs.ngInit); - } - }; - } -}); +
          + */ + var ngInitDirective = ngDirective({ + priority: 450, + compile: function () { + return { + pre: function (scope, element, attrs) { + scope.$eval(attrs.ngInit); + } + }; + } + }); -/** - * @ngdoc directive - * @name ngNonBindable - * @restrict AC - * @priority 1000 - * - * @description - * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current - * DOM element. This is useful if the element contains what appears to be Angular directives and - * bindings but which should be ignored by Angular. This could be the case if you have a site that - * displays snippets of code, for instance. - * - * @element ANY - * - * @example - * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, - * but the one wrapped in `ngNonBindable` is left alone. - * - * @example - - -
          Normal: {{1 + 2}}
          -
          Ignored: {{1 + 2}}
          -
          - - it('should check ng-non-bindable', function() { + /** + * @ngdoc directive + * @name ngNonBindable + * @restrict AC + * @priority 1000 + * + * @description + * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current + * DOM element. This is useful if the element contains what appears to be Angular directives and + * bindings but which should be ignored by Angular. This could be the case if you have a site that + * displays snippets of code, for instance. + * + * @element ANY + * + * @example + * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, + * but the one wrapped in `ngNonBindable` is left alone. + * + * @example + + +
          Normal: {{1 + 2}}
          +
          Ignored: {{1 + 2}}
          +
          + + it('should check ng-non-bindable', function() { expect(element(by.binding('1 + 2')).getText()).toContain('3'); expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); }); - -
          - */ -var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); +
          +
          + */ + var ngNonBindableDirective = ngDirective({terminal: true, priority: 1000}); -/** - * @ngdoc directive - * @name ngPluralize - * @restrict EA - * - * @description - * `ngPluralize` is a directive that displays messages according to en-US localization rules. - * These rules are bundled with angular.js, but can be overridden - * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive - * by specifying the mappings between - * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) - * and the strings to be displayed. - * - * # Plural categories and explicit number rules - * There are two - * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) - * in Angular's default en-US locale: "one" and "other". - * - * While a plural category may match many numbers (for example, in en-US locale, "other" can match - * any number that is not 1), an explicit number rule can only match one number. For example, the - * explicit number rule for "3" matches the number 3. There are examples of plural categories - * and explicit number rules throughout the rest of this documentation. - * - * # Configuring ngPluralize - * You configure ngPluralize by providing 2 attributes: `count` and `when`. - * You can also provide an optional attribute, `offset`. - * - * The value of the `count` attribute can be either a string or an {@link guide/expression + /** + * @ngdoc directive + * @name ngPluralize + * @restrict EA + * + * @description + * `ngPluralize` is a directive that displays messages according to en-US localization rules. + * These rules are bundled with angular.js, but can be overridden + * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive + * by specifying the mappings between + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * and the strings to be displayed. + * + * # Plural categories and explicit number rules + * There are two + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * in Angular's default en-US locale: "one" and "other". + * + * While a plural category may match many numbers (for example, in en-US locale, "other" can match + * any number that is not 1), an explicit number rule can only match one number. For example, the + * explicit number rule for "3" matches the number 3. There are examples of plural categories + * and explicit number rules throughout the rest of this documentation. + * + * # Configuring ngPluralize + * You configure ngPluralize by providing 2 attributes: `count` and `when`. + * You can also provide an optional attribute, `offset`. + * + * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. - * - * The `when` attribute specifies the mappings between plural categories and the actual - * string to be displayed. The value of the attribute should be a JSON object. - * - * The following example shows how to configure ngPluralize: - * - * ```html - * - * - *``` - * - * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not - * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" - * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for - * other numbers, for example 12, so that instead of showing "12 people are viewing", you can - * show "a dozen people are viewing". - * - * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted - * into pluralized strings. In the previous example, Angular will replace `{}` with - * `{{personCount}}`. The closed braces `{}` is a placeholder - * for {{numberExpression}}. - * - * # Configuring ngPluralize with offset - * The `offset` attribute allows further customization of pluralized text, which can result in - * a better user experience. For example, instead of the message "4 people are viewing this document", - * you might display "John, Kate and 2 others are viewing this document". - * The offset attribute allows you to offset a number by any desired value. - * Let's take a look at an example: - * - * ```html - * `{{personCount}}`
          . The closed braces `{}` is a placeholder + * for {{numberExpression}}. + * + * # Configuring ngPluralize with offset + * The `offset` attribute allows further customization of pluralized text, which can result in + * a better user experience. For example, instead of the message "4 people are viewing this document", + * you might display "John, Kate and 2 others are viewing this document". + * The offset attribute allows you to offset a number by any desired value. + * Let's take a look at an example: + * + * ```html + * - * - * ``` - * - * Notice that we are still using two plural categories(one, other), but we added - * three explicit number rules 0, 1 and 2. - * When one person, perhaps John, views the document, "John is viewing" will be shown. - * When three people view the document, no explicit number rule is found, so - * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. - * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" - * is shown. - * - * Note that when you specify offsets, you must provide explicit number rules for - * numbers from 0 up to and including the offset. If you use an offset of 3, for example, - * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for - * plural categories "one" and "other". - * - * @param {string|expression} count The variable to be bound to. - * @param {string} when The mapping between plural category to its corresponding strings. - * @param {number=} offset Offset to deduct from the total number. - * - * @example - - - -
          - Person 1:
          - Person 2:
          - Number of People:
          - - - Without Offset: - + Person 1:
          + Person 2:
          + Number of People:
          + + + Without Offset: + -
          +

          - - With Offset(2): - - -
          -
          - - it('should show correct pluralized string', function() { + + + + + it('should show correct pluralized string', function() { var withoutOffset = element.all(by.css('ng-pluralize')).get(0); var withOffset = element.all(by.css('ng-pluralize')).get(1); var countInput = element(by.model('personCount')); @@ -23613,7 +23742,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); expect(withoutOffset.getText()).toEqual('4 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); }); - it('should show data-bound names', function() { + it('should show data-bound names', function() { var withOffset = element.all(by.css('ng-pluralize')).get(1); var personCount = element(by.model('personCount')); var person1 = element(by.model('person1')); @@ -23626,203 +23755,203 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); person2.sendKeys('Vojta'); expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); - -
          - */ -var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { - var BRACE = /{}/g; - return { - restrict: 'EA', - link: function(scope, element, attr) { - var numberExp = attr.count, - whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs - offset = attr.offset || 0, - whens = scope.$eval(whenExp) || {}, - whensExpFns = {}, - startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(), - isWhen = /^when(Minus)?(.+)$/; - - forEach(attr, function(expression, attributeName) { - if (isWhen.test(attributeName)) { - whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = - element.attr(attr.$attr[attributeName]); - } - }); - forEach(whens, function(expression, key) { - whensExpFns[key] = - $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + - offset + endSymbol)); - }); + + + */ + var ngPluralizeDirective = ['$locale', '$interpolate', function ($locale, $interpolate) { + var BRACE = /{}/g; + return { + restrict: 'EA', + link: function (scope, element, attr) { + var numberExp = attr.count, + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs + offset = attr.offset || 0, + whens = scope.$eval(whenExp) || {}, + whensExpFns = {}, + startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + isWhen = /^when(Minus)?(.+)$/; + + forEach(attr, function (expression, attributeName) { + if (isWhen.test(attributeName)) { + whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = + element.attr(attr.$attr[attributeName]); + } + }); + forEach(whens, function (expression, key) { + whensExpFns[key] = + $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + + offset + endSymbol)); + }); - scope.$watch(function ngPluralizeWatch() { - var value = parseFloat(scope.$eval(numberExp)); + scope.$watch(function ngPluralizeWatch() { + var value = parseFloat(scope.$eval(numberExp)); - if (!isNaN(value)) { - //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, - //check it against pluralization rules in $locale service - if (!(value in whens)) value = $locale.pluralCat(value - offset); - return whensExpFns[value](scope); - } else { - return ''; - } - }, function ngPluralizeWatchAction(newVal) { - element.text(newVal); - }); - } - }; -}]; + if (!isNaN(value)) { + //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, + //check it against pluralization rules in $locale service + if (!(value in whens)) value = $locale.pluralCat(value - offset); + return whensExpFns[value](scope); + } else { + return ''; + } + }, function ngPluralizeWatchAction(newVal) { + element.text(newVal); + }); + } + }; + }]; -/** - * @ngdoc directive - * @name ngRepeat - * - * @description - * The `ngRepeat` directive instantiates a template once per item from a collection. Each template - * instance gets its own scope, where the given loop variable is set to the current collection item, - * and `$index` is set to the item index or key. - * - * Special properties are exposed on the local scope of each template instance, including: - * - * | Variable | Type | Details | - * |-----------|-----------------|-----------------------------------------------------------------------------| - * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | - * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | - * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | - * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | - * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | - * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | - * - * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. - * This may be useful when, for instance, nesting ngRepeats. - * - * # Special repeat start and end points - * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending - * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. - * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) - * up to and including the ending HTML tag where **ng-repeat-end** is placed. - * - * The example below makes use of this feature: - * ```html - *
          - * Header {{ item }} - *
          - *
          - * Body {{ item }} - *
          - *
          - * Footer {{ item }} - *
          - * ``` - * - * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: - * ```html - *
          - * Header A - *
          - *
          - * Body A - *
          - *
          - * Footer A - *
          - *
          - * Header B - *
          - *
          - * Body B - *
          - *
          - * Footer B - *
          - * ``` - * - * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such - * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). - * - * @animations - * **.enter** - when a new item is added to the list or when an item is revealed after a filter - * - * **.leave** - when an item is removed from the list or when an item is filtered out - * - * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered - * - * @element ANY - * @scope - * @priority 1000 - * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These - * formats are currently supported: - * - * * `variable in expression` – where variable is the user defined loop variable and `expression` - * is a scope expression giving the collection to enumerate. - * - * For example: `album in artist.albums`. - * - * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, - * and `expression` is the scope expression giving the collection to enumerate. - * - * For example: `(name, age) in {'adam':10, 'amalie':12}`. - * - * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function - * which can be used to associate the objects in the collection with the DOM elements. If no tracking function - * is specified the ng-repeat associates elements by identity in the collection. It is an error to have - * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are - * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, - * before specifying a tracking expression. - * - * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements - * will be associated by item identity in the array. - * - * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique - * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements - * with the corresponding item in the array by identity. Moving the same object in array would move the DOM - * element in the same way in the DOM. - * - * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this - * case the object identity does not matter. Two objects are considered equivalent as long as their `id` - * property is same. - * - * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter - * to items in conjunction with a tracking expression. - * - * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the - * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message - * when a filter is active on the repeater, but the filtered result set is empty. - * - * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after - * the items have been processed through the filter. - * - * @example - * This example initializes the scope to a list of names and - * then uses `ngRepeat` to display every person: - - -
          - I have {{friends.length}} friends. They are: - -
            -
          • - [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. -
          • -
          • - No results found... -
          • -
          -
          -
          - - .example-animate-container { + /** + * @ngdoc directive + * @name ngRepeat + * + * @description + * The `ngRepeat` directive instantiates a template once per item from a collection. Each template + * instance gets its own scope, where the given loop variable is set to the current collection item, + * and `$index` is set to the item index or key. + * + * Special properties are exposed on the local scope of each template instance, including: + * + * | Variable | Type | Details | + * |-----------|-----------------|-----------------------------------------------------------------------------| + * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | + * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | + * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | + * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | + * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | + * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | + * + * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. + * This may be useful when, for instance, nesting ngRepeats. + * + * # Special repeat start and end points + * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending + * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. + * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) + * up to and including the ending HTML tag where **ng-repeat-end** is placed. + * + * The example below makes use of this feature: + * ```html + *
          + * Header {{ item }} + *
          + *
          + * Body {{ item }} + *
          + *
          + * Footer {{ item }} + *
          + * ``` + * + * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: + * ```html + *
          + * Header A + *
          + *
          + * Body A + *
          + *
          + * Footer A + *
          + *
          + * Header B + *
          + *
          + * Body B + *
          + *
          + * Footer B + *
          + * ``` + * + * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such + * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). + * + * @animations + * **.enter** - when a new item is added to the list or when an item is revealed after a filter + * + * **.leave** - when an item is removed from the list or when an item is filtered out + * + * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered + * + * @element ANY + * @scope + * @priority 1000 + * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These + * formats are currently supported: + * + * * `variable in expression` – where variable is the user defined loop variable and `expression` + * is a scope expression giving the collection to enumerate. + * + * For example: `album in artist.albums`. + * + * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, + * and `expression` is the scope expression giving the collection to enumerate. + * + * For example: `(name, age) in {'adam':10, 'amalie':12}`. + * + * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function + * which can be used to associate the objects in the collection with the DOM elements. If no tracking function + * is specified the ng-repeat associates elements by identity in the collection. It is an error to have + * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are + * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, + * before specifying a tracking expression. + * + * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements + * will be associated by item identity in the array. + * + * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements + * with the corresponding item in the array by identity. Moving the same object in array would move the DOM + * element in the same way in the DOM. + * + * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this + * case the object identity does not matter. Two objects are considered equivalent as long as their `id` + * property is same. + * + * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter + * to items in conjunction with a tracking expression. + * + * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the + * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message + * when a filter is active on the repeater, but the filtered result set is empty. + * + * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after + * the items have been processed through the filter. + * + * @example + * This example initializes the scope to a list of names and + * then uses `ngRepeat` to display every person: + + +
          + I have {{friends.length}} friends. They are: + +
            +
          • + [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. +
          • +
          • + No results found... +
          • +
          +
          +
          + + .example-animate-container { background:white; border:1px solid black; list-style:none; @@ -23830,37 +23959,37 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp padding:0 10px; } - .animate-repeat { + .animate-repeat { line-height:40px; list-style:none; box-sizing:border-box; } - .animate-repeat.ng-move, - .animate-repeat.ng-enter, - .animate-repeat.ng-leave { + .animate-repeat.ng-move, + .animate-repeat.ng-enter, + .animate-repeat.ng-leave { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } - .animate-repeat.ng-leave.ng-leave-active, - .animate-repeat.ng-move, - .animate-repeat.ng-enter { + .animate-repeat.ng-leave.ng-leave-active, + .animate-repeat.ng-move, + .animate-repeat.ng-enter { opacity:0; max-height:0; } - .animate-repeat.ng-leave, - .animate-repeat.ng-move.ng-move-active, - .animate-repeat.ng-enter.ng-enter-active { + .animate-repeat.ng-leave, + .animate-repeat.ng-move.ng-move-active, + .animate-repeat.ng-enter.ng-enter-active { opacity:1; max-height:40px; } - - - var friends = element.all(by.repeater('friend in friends')); + + + var friends = element.all(by.repeater('friend in friends')); - it('should render initial data set', function() { + it('should render initial data set', function() { expect(friends.count()).toBe(10); expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); @@ -23869,365 +23998,365 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp .toMatch("I have 10 friends. They are:"); }); - it('should update repeater when filter predicate changes', function() { + it('should update repeater when filter predicate changes', function() { expect(friends.count()).toBe(10); element(by.model('q')).sendKeys('ma'); expect(friends.count()).toBe(2); expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); - expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); - }); - -
          - */ -var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { - var NG_REMOVED = '$$NG_REMOVED'; - var ngRepeatMinErr = minErr('ngRepeat'); - - var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { - // TODO(perf): generate setters to shave off ~40ms or 1-1.5% - scope[valueIdentifier] = value; - if (keyIdentifier) scope[keyIdentifier] = key; - scope.$index = index; - scope.$first = (index === 0); - scope.$last = (index === (arrayLength - 1)); - scope.$middle = !(scope.$first || scope.$last); - // jshint bitwise: false - scope.$odd = !(scope.$even = (index&1) === 0); - // jshint bitwise: true - }; - - var getBlockStart = function(block) { - return block.clone[0]; - }; - - var getBlockEnd = function(block) { - return block.clone[block.clone.length - 1]; - }; - - - return { - restrict: 'A', - multiElement: true, - transclude: 'element', - priority: 1000, - terminal: true, - $$tlb: true, - compile: function ngRepeatCompile($element, $attr) { - var expression = $attr.ngRepeat; - var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); - - var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); - - if (!match) { - throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", - expression); - } - - var lhs = match[1]; - var rhs = match[2]; - var aliasAs = match[3]; - var trackByExp = match[4]; - - match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); - - if (!match) { - throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", - lhs); - } - var valueIdentifier = match[3] || match[1]; - var keyIdentifier = match[2]; - - if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || - /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) { - throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.", - aliasAs); - } - - var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; - var hashFnLocals = {$id: hashKey}; + expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); + }); +
          +
          + */ + var ngRepeatDirective = ['$parse', '$animate', function ($parse, $animate) { + var NG_REMOVED = '$$NG_REMOVED'; + var ngRepeatMinErr = minErr('ngRepeat'); + + var updateScope = function (scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { + // TODO(perf): generate setters to shave off ~40ms or 1-1.5% + scope[valueIdentifier] = value; + if (keyIdentifier) scope[keyIdentifier] = key; + scope.$index = index; + scope.$first = (index === 0); + scope.$last = (index === (arrayLength - 1)); + scope.$middle = !(scope.$first || scope.$last); + // jshint bitwise: false + scope.$odd = !(scope.$even = (index & 1) === 0); + // jshint bitwise: true + }; - if (trackByExp) { - trackByExpGetter = $parse(trackByExp); - } else { - trackByIdArrayFn = function (key, value) { - return hashKey(value); + var getBlockStart = function (block) { + return block.clone[0]; }; - trackByIdObjFn = function (key) { - return key; + + var getBlockEnd = function (block) { + return block.clone[block.clone.length - 1]; }; - } - return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { - if (trackByExpGetter) { - trackByIdExpFn = function(key, value, index) { - // assign key, value, and $index to the locals so that they can be used in hash functions - if (keyIdentifier) hashFnLocals[keyIdentifier] = key; - hashFnLocals[valueIdentifier] = value; - hashFnLocals.$index = index; - return trackByExpGetter($scope, hashFnLocals); - }; - } + return { + restrict: 'A', + multiElement: true, + transclude: 'element', + priority: 1000, + terminal: true, + $$tlb: true, + compile: function ngRepeatCompile($element, $attr) { + var expression = $attr.ngRepeat; + var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); + + var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); + + if (!match) { + throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } - // Store a list of elements from previous run. This is a hash where key is the item from the - // iterator, and the value is objects with following properties. - // - scope: bound scope - // - element: previous element. - // - index: position - // - // We are using no-proto object so that we don't need to guard against inherited props via - // hasOwnProperty. - var lastBlockMap = createMap(); - - //watch props - $scope.$watchCollection(rhs, function ngRepeatAction(collection) { - var index, length, - previousNode = $element[0], // node that cloned nodes should be inserted after - // initialized to the comment node anchor - nextNode, - // Same as lastBlockMap but it has the current state. It will become the - // lastBlockMap on the next iteration. - nextBlockMap = createMap(), - collectionLength, - key, value, // key/value of iteration - trackById, - trackByIdFn, - collectionKeys, - block, // last object information {scope, element, id} - nextBlockOrder, - elementsToRemove; - - if (aliasAs) { - $scope[aliasAs] = collection; - } + var lhs = match[1]; + var rhs = match[2]; + var aliasAs = match[3]; + var trackByExp = match[4]; - if (isArrayLike(collection)) { - collectionKeys = collection; - trackByIdFn = trackByIdExpFn || trackByIdArrayFn; - } else { - trackByIdFn = trackByIdExpFn || trackByIdObjFn; - // if object, extract keys, sort them and use to determine order of iteration over obj props - collectionKeys = []; - for (var itemKey in collection) { - if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { - collectionKeys.push(itemKey); - } - } - collectionKeys.sort(); - } + match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); - collectionLength = collectionKeys.length; - nextBlockOrder = new Array(collectionLength); - - // locate existing items - for (index = 0; index < collectionLength; index++) { - key = (collection === collectionKeys) ? index : collectionKeys[index]; - value = collection[key]; - trackById = trackByIdFn(key, value, index); - if (lastBlockMap[trackById]) { - // found previously seen block - block = lastBlockMap[trackById]; - delete lastBlockMap[trackById]; - nextBlockMap[trackById] = block; - nextBlockOrder[index] = block; - } else if (nextBlockMap[trackById]) { - // if collision detected. restore lastBlockMap and throw an error - forEach(nextBlockOrder, function (block) { - if (block && block.scope) lastBlockMap[block.id] = block; - }); - throw ngRepeatMinErr('dupes', - "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", - expression, trackById, toJson(value)); - } else { - // new never before seen block - nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; - nextBlockMap[trackById] = true; - } - } + if (!match) { + throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + lhs); + } + var valueIdentifier = match[3] || match[1]; + var keyIdentifier = match[2]; - // remove leftover items - for (var blockKey in lastBlockMap) { - block = lastBlockMap[blockKey]; - elementsToRemove = getBlockNodes(block.clone); - $animate.leave(elementsToRemove); - if (elementsToRemove[0].parentNode) { - // if the element was not removed yet because of pending animation, mark it as deleted - // so that we can ignore it later - for (index = 0, length = elementsToRemove.length; index < length; index++) { - elementsToRemove[index][NG_REMOVED] = true; - } - } - block.scope.$destroy(); - } + if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || + /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) { + throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.", + aliasAs); + } - // we are not using forEach for perf reasons (trying to avoid #call) - for (index = 0; index < collectionLength; index++) { - key = (collection === collectionKeys) ? index : collectionKeys[index]; - value = collection[key]; - block = nextBlockOrder[index]; + var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; + var hashFnLocals = {$id: hashKey}; - if (block.scope) { - // if we have already seen this object, then we need to reuse the - // associated scope/element + if (trackByExp) { + trackByExpGetter = $parse(trackByExp); + } else { + trackByIdArrayFn = function (key, value) { + return hashKey(value); + }; + trackByIdObjFn = function (key) { + return key; + }; + } - nextNode = previousNode; + return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { - // skip nodes that are already pending removal via leave animation - do { - nextNode = nextNode.nextSibling; - } while (nextNode && nextNode[NG_REMOVED]); + if (trackByExpGetter) { + trackByIdExpFn = function (key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); + }; + } - if (getBlockStart(block) != nextNode) { - // existing item which got moved - $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode)); - } - previousNode = getBlockEnd(block); - updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); - } else { - // new item which we don't know about - $transclude(function ngRepeatTransclude(clone, scope) { - block.scope = scope; - // http://jsperf.com/clone-vs-createcomment - var endNode = ngRepeatEndComment.cloneNode(false); - clone[clone.length++] = endNode; - - // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper? - $animate.enter(clone, null, jqLite(previousNode)); - previousNode = endNode; - // Note: We only need the first/last node of the cloned nodes. - // However, we need to keep the reference to the jqlite wrapper as it might be changed later - // by a directive with templateUrl when its template arrives. - block.clone = clone; - nextBlockMap[block.id] = block; - updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); - }); + // Store a list of elements from previous run. This is a hash where key is the item from the + // iterator, and the value is objects with following properties. + // - scope: bound scope + // - element: previous element. + // - index: position + // + // We are using no-proto object so that we don't need to guard against inherited props via + // hasOwnProperty. + var lastBlockMap = createMap(); + + //watch props + $scope.$watchCollection(rhs, function ngRepeatAction(collection) { + var index, length, + previousNode = $element[0], // node that cloned nodes should be inserted after + // initialized to the comment node anchor + nextNode, + // Same as lastBlockMap but it has the current state. It will become the + // lastBlockMap on the next iteration. + nextBlockMap = createMap(), + collectionLength, + key, value, // key/value of iteration + trackById, + trackByIdFn, + collectionKeys, + block, // last object information {scope, element, id} + nextBlockOrder, + elementsToRemove; + + if (aliasAs) { + $scope[aliasAs] = collection; + } + + if (isArrayLike(collection)) { + collectionKeys = collection; + trackByIdFn = trackByIdExpFn || trackByIdArrayFn; + } else { + trackByIdFn = trackByIdExpFn || trackByIdObjFn; + // if object, extract keys, sort them and use to determine order of iteration over obj props + collectionKeys = []; + for (var itemKey in collection) { + if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { + collectionKeys.push(itemKey); + } + } + collectionKeys.sort(); + } + + collectionLength = collectionKeys.length; + nextBlockOrder = new Array(collectionLength); + + // locate existing items + for (index = 0; index < collectionLength; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + trackById = trackByIdFn(key, value, index); + if (lastBlockMap[trackById]) { + // found previously seen block + block = lastBlockMap[trackById]; + delete lastBlockMap[trackById]; + nextBlockMap[trackById] = block; + nextBlockOrder[index] = block; + } else if (nextBlockMap[trackById]) { + // if collision detected. restore lastBlockMap and throw an error + forEach(nextBlockOrder, function (block) { + if (block && block.scope) lastBlockMap[block.id] = block; + }); + throw ngRepeatMinErr('dupes', + "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", + expression, trackById, toJson(value)); + } else { + // new never before seen block + nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; + nextBlockMap[trackById] = true; + } + } + + // remove leftover items + for (var blockKey in lastBlockMap) { + block = lastBlockMap[blockKey]; + elementsToRemove = getBlockNodes(block.clone); + $animate.leave(elementsToRemove); + if (elementsToRemove[0].parentNode) { + // if the element was not removed yet because of pending animation, mark it as deleted + // so that we can ignore it later + for (index = 0, length = elementsToRemove.length; index < length; index++) { + elementsToRemove[index][NG_REMOVED] = true; + } + } + block.scope.$destroy(); + } + + // we are not using forEach for perf reasons (trying to avoid #call) + for (index = 0; index < collectionLength; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + block = nextBlockOrder[index]; + + if (block.scope) { + // if we have already seen this object, then we need to reuse the + // associated scope/element + + nextNode = previousNode; + + // skip nodes that are already pending removal via leave animation + do { + nextNode = nextNode.nextSibling; + } while (nextNode && nextNode[NG_REMOVED]); + + if (getBlockStart(block) != nextNode) { + // existing item which got moved + $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode)); + } + previousNode = getBlockEnd(block); + updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); + } else { + // new item which we don't know about + $transclude(function ngRepeatTransclude(clone, scope) { + block.scope = scope; + // http://jsperf.com/clone-vs-createcomment + var endNode = ngRepeatEndComment.cloneNode(false); + clone[clone.length++] = endNode; + + // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper? + $animate.enter(clone, null, jqLite(previousNode)); + previousNode = endNode; + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block.clone = clone; + nextBlockMap[block.id] = block; + updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); + }); + } + } + lastBlockMap = nextBlockMap; + }); + }; } - } - lastBlockMap = nextBlockMap; - }); - }; - } - }; -}]; + }; + }]; -var NG_HIDE_CLASS = 'ng-hide'; -var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; -/** - * @ngdoc directive - * @name ngShow - * - * @description - * The `ngShow` directive shows or hides the given HTML element based on the expression - * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding - * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined - * in AngularJS and sets the display style to none (using an !important flag). - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). - * - * ```html - * - *
          - * - * - *
          - * ``` - * - * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class - * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed - * from the element causing the element not to appear hidden. - * - * ## Why is !important used? - * - * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. - * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. - * - * ### Overriding `.ng-hide` - * - * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change - * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` - * class in CSS: - * - * ```css - * .ng-hide { + var NG_HIDE_CLASS = 'ng-hide'; + var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; + /** + * @ngdoc directive + * @name ngShow + * + * @description + * The `ngShow` directive shows or hides the given HTML element based on the expression + * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding + * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
          + * + * + *
          + * ``` + * + * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class + * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding `.ng-hide` + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { * /* this is just another form of hiding an element */ * display:block!important; * position:absolute; * top:-9999px; * left:-9999px; * } - * ``` - * - * By default you don't need to override in CSS anything and the animations will work around the display style. - * - * ## A note about animations with `ngShow` - * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works like the animation system present with ngClass except that - * you must also include the !important flag to override the display property - * so that you can perform an animation when the element is hidden during the time of the animation. - * - * ```css - * // - * //a working example can be found at the bottom of this page - * // - * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with `ngShow` + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass except that + * you must also include the !important flag to override the display property + * so that you can perform an animation when the element is hidden during the time of the animation. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { * /* this is required as of 1.3x to properly * apply all styling in a show/hide animation */ * transition:0s linear all; * } - * - * .my-element.ng-hide-add-active, - * .my-element.ng-hide-remove-active { + * + * .my-element.ng-hide-add-active, + * .my-element.ng-hide-remove-active { * /* the transition is defined in the active class */ * transition:1s linear all; * } - * - * .my-element.ng-hide-add { ... } - * .my-element.ng-hide-add.ng-hide-add-active { ... } - * .my-element.ng-hide-remove { ... } - * .my-element.ng-hide-remove.ng-hide-remove-active { ... } - * ``` - * - * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display - * property to block during animation states--ngAnimate will handle the style toggling automatically for you. - * - * @animations - * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible - * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden - * - * @element ANY - * @param {expression} ngShow If the {@link guide/expression expression} is truthy - * then the element is shown or hidden respectively. - * - * @example - - - Click me:
          -
          - Show: -
          - I show up when your checkbox is checked. -
          -
          -
          - Hide: -
          - I hide when your checkbox is checked. -
          -
          -
          - - @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); - - - .animate-show { + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible + * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden + * + * @element ANY + * @param {expression} ngShow If the {@link guide/expression expression} is truthy + * then the element is shown or hidden respectively. + * + * @example + + + Click me:
          +
          + Show: +
          + I show up when your checkbox is checked. +
          +
          +
          + Hide: +
          + I hide when your checkbox is checked. +
          +
          +
          + + @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-show { line-height:20px; opacity:1; padding:10px; @@ -24235,29 +24364,29 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; background:white; } - .animate-show.ng-hide-add.ng-hide-add-active, - .animate-show.ng-hide-remove.ng-hide-remove-active { + .animate-show.ng-hide-add.ng-hide-add-active, + .animate-show.ng-hide-remove.ng-hide-remove-active { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } - .animate-show.ng-hide { + .animate-show.ng-hide { line-height:0; opacity:0; padding:0 10px; } - .check-element { + .check-element { padding:10px; border:1px solid black; background:white; } - - - var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); - var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); - it('should check ng-show / ng-hide', function() { + it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); @@ -24266,133 +24395,133 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); - -
          - */ -var ngShowDirective = ['$animate', function($animate) { - return { - restrict: 'A', - multiElement: true, - link: function(scope, element, attr) { - scope.$watch(attr.ngShow, function ngShowWatchAction(value){ - // we're adding a temporary, animation-specific class for ng-hide since this way - // we can control when the element is actually displayed on screen without having - // to have a global/greedy CSS selector that breaks when other animations are run. - // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 - $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { - tempClasses : NG_HIDE_IN_PROGRESS_CLASS - }); - }); - } - }; -}]; +
          +
          + */ + var ngShowDirective = ['$animate', function ($animate) { + return { + restrict: 'A', + multiElement: true, + link: function (scope, element, attr) { + scope.$watch(attr.ngShow, function ngShowWatchAction(value) { + // we're adding a temporary, animation-specific class for ng-hide since this way + // we can control when the element is actually displayed on screen without having + // to have a global/greedy CSS selector that breaks when other animations are run. + // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 + $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { + tempClasses: NG_HIDE_IN_PROGRESS_CLASS + }); + }); + } + }; + }]; -/** - * @ngdoc directive - * @name ngHide - * - * @description - * The `ngHide` directive shows or hides the given HTML element based on the expression - * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding - * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined - * in AngularJS and sets the display style to none (using an !important flag). - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). - * - * ```html - * - *
          - * - * - *
          - * ``` - * - * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class - * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed - * from the element causing the element not to appear hidden. - * - * ## Why is !important used? - * - * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. - * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. - * - * ### Overriding `.ng-hide` - * - * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change - * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` - * class in CSS: - * - * ```css - * .ng-hide { + /** + * @ngdoc directive + * @name ngHide + * + * @description + * The `ngHide` directive shows or hides the given HTML element based on the expression + * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
          + * + * + *
          + * ``` + * + * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class + * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed + * from the element causing the element not to appear hidden. + * + * ## Why is !important used? + * + * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding `.ng-hide` + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { * /* this is just another form of hiding an element */ * display:block!important; * position:absolute; * top:-9999px; * left:-9999px; * } - * ``` - * - * By default you don't need to override in CSS anything and the animations will work around the display style. - * - * ## A note about animations with `ngHide` - * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` - * CSS class is added and removed for you instead of your own CSS class. - * - * ```css - * // - * //a working example can be found at the bottom of this page - * // - * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with `ngHide` + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` + * CSS class is added and removed for you instead of your own CSS class. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { * transition:0.5s linear all; * } - * - * .my-element.ng-hide-add { ... } - * .my-element.ng-hide-add.ng-hide-add-active { ... } - * .my-element.ng-hide-remove { ... } - * .my-element.ng-hide-remove.ng-hide-remove-active { ... } - * ``` - * - * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display - * property to block during animation states--ngAnimate will handle the style toggling automatically for you. - * - * @animations - * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden - * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible - * - * @element ANY - * @param {expression} ngHide If the {@link guide/expression expression} is truthy then - * the element is shown or hidden respectively. - * - * @example - - - Click me:
          -
          - Show: -
          - I show up when your checkbox is checked. -
          -
          -
          - Hide: -
          - I hide when your checkbox is checked. -
          -
          -
          - - @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); - - - .animate-hide { + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden + * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible + * + * @element ANY + * @param {expression} ngHide If the {@link guide/expression expression} is truthy then + * the element is shown or hidden respectively. + * + * @example + + + Click me:
          +
          + Show: +
          + I show up when your checkbox is checked. +
          +
          +
          + Hide: +
          + I hide when your checkbox is checked. +
          +
          +
          + + @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-hide { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; line-height:20px; @@ -24402,23 +24531,23 @@ var ngShowDirective = ['$animate', function($animate) { background:white; } - .animate-hide.ng-hide { + .animate-hide.ng-hide { line-height:0; opacity:0; padding:0 10px; } - .check-element { + .check-element { padding:10px; border:1px solid black; background:white; } - - - var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); - var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); - it('should check ng-show / ng-hide', function() { + it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); @@ -24427,62 +24556,62 @@ var ngShowDirective = ['$animate', function($animate) { expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); - -
          - */ -var ngHideDirective = ['$animate', function($animate) { - return { - restrict: 'A', - multiElement: true, - link: function(scope, element, attr) { - scope.$watch(attr.ngHide, function ngHideWatchAction(value){ - // The comment inside of the ngShowDirective explains why we add and - // remove a temporary class for the show/hide animation - $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, { - tempClasses : NG_HIDE_IN_PROGRESS_CLASS - }); - }); - } - }; -}]; +
          +
          + */ + var ngHideDirective = ['$animate', function ($animate) { + return { + restrict: 'A', + multiElement: true, + link: function (scope, element, attr) { + scope.$watch(attr.ngHide, function ngHideWatchAction(value) { + // The comment inside of the ngShowDirective explains why we add and + // remove a temporary class for the show/hide animation + $animate[value ? 'addClass' : 'removeClass'](element, NG_HIDE_CLASS, { + tempClasses: NG_HIDE_IN_PROGRESS_CLASS + }); + }); + } + }; + }]; -/** - * @ngdoc directive - * @name ngStyle - * @restrict AC - * - * @description - * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. - * - * @element ANY - * @param {expression} ngStyle - * - * {@link guide/expression Expression} which evals to an - * object whose keys are CSS style names and values are corresponding values for those CSS - * keys. - * - * Since some CSS style names are not valid keys for an object, they must be quoted. - * See the 'background-color' style in the example below. - * - * @example - + /** + * @ngdoc directive + * @name ngStyle + * @restrict AC + * + * @description + * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. + * + * @element ANY + * @param {expression} ngStyle + * + * {@link guide/expression Expression} which evals to an + * object whose keys are CSS style names and values are corresponding values for those CSS + * keys. + * + * Since some CSS style names are not valid keys for an object, they must be quoted. + * See the 'background-color' style in the example below. + * + * @example + - - - -
          - Sample Text -
          myStyle={{myStyle}}
          + + + +
          + Sample Text +
          myStyle={{myStyle}}
          - span { + span { color: black; } - var colorSpan = element(by.css('span')); + var colorSpan = element(by.css('span')); - it('should check ng-style', function() { + it('should check ng-style', function() { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); element(by.css('input[value=\'set color\']')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); @@ -24490,96 +24619,98 @@ var ngHideDirective = ['$animate', function($animate) { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); }); -
          - */ -var ngStyleDirective = ngDirective(function(scope, element, attr) { - scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { - if (oldStyles && (newStyles !== oldStyles)) { - forEach(oldStyles, function(val, style) { element.css(style, '');}); - } - if (newStyles) element.css(newStyles); - }, true); -}); +
          + */ + var ngStyleDirective = ngDirective(function (scope, element, attr) { + scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { + if (oldStyles && (newStyles !== oldStyles)) { + forEach(oldStyles, function (val, style) { + element.css(style, ''); + }); + } + if (newStyles) element.css(newStyles); + }, true); + }); -/** - * @ngdoc directive - * @name ngSwitch - * @restrict EA - * - * @description - * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. - * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location - * as specified in the template. - * - * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it - * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element - * matches the value obtained from the evaluated expression. In other words, you define a container element - * (where you place the directive), place an expression on the **`on="..."` attribute** - * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place - * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on - * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default - * attribute is displayed. - * - *
          - * Be aware that the attribute values to match against cannot be expressions. They are interpreted - * as literal string values to match against. - * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the - * value of the expression `$scope.someVal`. - *
          - - * @animations - * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container - * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM - * - * @usage - * - * ``` - * - * ... - * ... - * ... - * - * ``` - * - * - * @scope - * @priority 1200 - * @param {*} ngSwitch|on expression to match against ng-switch-when. - * On child elements add: - * - * * `ngSwitchWhen`: the case statement to match against. If match then this - * case will be displayed. If the same match appears multiple times, all the - * elements will be displayed. - * * `ngSwitchDefault`: the default case when no other case match. If there - * are multiple default cases, all of them will be displayed when no other - * case match. - * - * - * @example - - -
          - - selection={{selection}} -
          -
          -
          Settings Div
          -
          Home Span
          -
          default
          -
          -
          -
          - - angular.module('switchExample', ['ngAnimate']) - .controller('ExampleController', ['$scope', function($scope) { + /** + * @ngdoc directive + * @name ngSwitch + * @restrict EA + * + * @description + * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. + * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location + * as specified in the template. + * + * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it + * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element + * matches the value obtained from the evaluated expression. In other words, you define a container element + * (where you place the directive), place an expression on the **`on="..."` attribute** + * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place + * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on + * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default + * attribute is displayed. + * + *
          + * Be aware that the attribute values to match against cannot be expressions. They are interpreted + * as literal string values to match against. + * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the + * value of the expression `$scope.someVal`. + *
          + + * @animations + * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container + * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM + * + * @usage + * + * ``` + * + * ... + * ... + * ... + * + * ``` + * + * + * @scope + * @priority 1200 + * @param {*} ngSwitch|on expression to match against ng-switch-when. + * On child elements add: + * + * * `ngSwitchWhen`: the case statement to match against. If match then this + * case will be displayed. If the same match appears multiple times, all the + * elements will be displayed. + * * `ngSwitchDefault`: the default case when no other case match. If there + * are multiple default cases, all of them will be displayed when no other + * case match. + * + * + * @example + + +
          + + selection={{selection}} +
          +
          +
          Settings Div
          +
          Home Span
          +
          default
          +
          +
          +
          + + angular.module('switchExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; }]); - - - .animate-switch-container { + + + .animate-switch-container { position:relative; background:white; border:1px solid black; @@ -24587,11 +24718,11 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { overflow:hidden; } - .animate-switch { + .animate-switch { padding:10px; } - .animate-switch.ng-animate { + .animate-switch.ng-animate { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; @@ -24602,128 +24733,130 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { bottom:0; } - .animate-switch.ng-leave.ng-leave-active, - .animate-switch.ng-enter { + .animate-switch.ng-leave.ng-leave-active, + .animate-switch.ng-enter { top:-50px; } - .animate-switch.ng-leave, - .animate-switch.ng-enter.ng-enter-active { + .animate-switch.ng-leave, + .animate-switch.ng-enter.ng-enter-active { top:0; } - - - var switchElem = element(by.css('[ng-switch]')); - var select = element(by.model('selection')); + + + var switchElem = element(by.css('[ng-switch]')); + var select = element(by.model('selection')); - it('should start in settings', function() { + it('should start in settings', function() { expect(switchElem.getText()).toMatch(/Settings Div/); }); - it('should change to home', function() { + it('should change to home', function() { select.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); - it('should select default', function() { + it('should select default', function() { select.all(by.css('option')).get(2).click(); expect(switchElem.getText()).toMatch(/default/); }); - -
          - */ -var ngSwitchDirective = ['$animate', function($animate) { - return { - restrict: 'EA', - require: 'ngSwitch', - - // asks for $scope to fool the BC controller module - controller: ['$scope', function ngSwitchController() { - this.cases = {}; - }], - link: function(scope, element, attr, ngSwitchController) { - var watchExpr = attr.ngSwitch || attr.on, - selectedTranscludes = [], - selectedElements = [], - previousLeaveAnimations = [], - selectedScopes = []; - - var spliceFactory = function(array, index) { - return function() { array.splice(index, 1); }; - }; +
          +
          + */ + var ngSwitchDirective = ['$animate', function ($animate) { + return { + restrict: 'EA', + require: 'ngSwitch', + + // asks for $scope to fool the BC controller module + controller: ['$scope', function ngSwitchController() { + this.cases = {}; + }], + link: function (scope, element, attr, ngSwitchController) { + var watchExpr = attr.ngSwitch || attr.on, + selectedTranscludes = [], + selectedElements = [], + previousLeaveAnimations = [], + selectedScopes = []; + + var spliceFactory = function (array, index) { + return function () { + array.splice(index, 1); + }; + }; - scope.$watch(watchExpr, function ngSwitchWatchAction(value) { - var i, ii; - for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) { - $animate.cancel(previousLeaveAnimations[i]); - } - previousLeaveAnimations.length = 0; + scope.$watch(watchExpr, function ngSwitchWatchAction(value) { + var i, ii; + for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) { + $animate.cancel(previousLeaveAnimations[i]); + } + previousLeaveAnimations.length = 0; - for (i = 0, ii = selectedScopes.length; i < ii; ++i) { - var selected = getBlockNodes(selectedElements[i].clone); - selectedScopes[i].$destroy(); - var promise = previousLeaveAnimations[i] = $animate.leave(selected); - promise.then(spliceFactory(previousLeaveAnimations, i)); - } + for (i = 0, ii = selectedScopes.length; i < ii; ++i) { + var selected = getBlockNodes(selectedElements[i].clone); + selectedScopes[i].$destroy(); + var promise = previousLeaveAnimations[i] = $animate.leave(selected); + promise.then(spliceFactory(previousLeaveAnimations, i)); + } - selectedElements.length = 0; - selectedScopes.length = 0; + selectedElements.length = 0; + selectedScopes.length = 0; + + if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { + forEach(selectedTranscludes, function (selectedTransclude) { + selectedTransclude.transclude(function (caseElement, selectedScope) { + selectedScopes.push(selectedScope); + var anchor = selectedTransclude.element; + caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: '); + var block = {clone: caseElement}; + + selectedElements.push(block); + $animate.enter(caseElement, anchor.parent(), anchor); + }); + }); + } + }); + } + }; + }]; - if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { - forEach(selectedTranscludes, function(selectedTransclude) { - selectedTransclude.transclude(function(caseElement, selectedScope) { - selectedScopes.push(selectedScope); - var anchor = selectedTransclude.element; - caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: '); - var block = { clone: caseElement }; + var ngSwitchWhenDirective = ngDirective({ + transclude: 'element', + priority: 1200, + require: '^ngSwitch', + multiElement: true, + link: function (scope, element, attrs, ctrl, $transclude) { + ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); + ctrl.cases['!' + attrs.ngSwitchWhen].push({transclude: $transclude, element: element}); + } + }); - selectedElements.push(block); - $animate.enter(caseElement, anchor.parent(), anchor); - }); - }); + var ngSwitchDefaultDirective = ngDirective({ + transclude: 'element', + priority: 1200, + require: '^ngSwitch', + multiElement: true, + link: function (scope, element, attr, ctrl, $transclude) { + ctrl.cases['?'] = (ctrl.cases['?'] || []); + ctrl.cases['?'].push({transclude: $transclude, element: element}); } - }); - } - }; -}]; - -var ngSwitchWhenDirective = ngDirective({ - transclude: 'element', - priority: 1200, - require: '^ngSwitch', - multiElement: true, - link: function(scope, element, attrs, ctrl, $transclude) { - ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); - ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); - } -}); - -var ngSwitchDefaultDirective = ngDirective({ - transclude: 'element', - priority: 1200, - require: '^ngSwitch', - multiElement: true, - link: function(scope, element, attr, ctrl, $transclude) { - ctrl.cases['?'] = (ctrl.cases['?'] || []); - ctrl.cases['?'].push({ transclude: $transclude, element: element }); - } -}); + }); -/** - * @ngdoc directive - * @name ngTransclude - * @restrict EAC - * - * @description - * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. - * - * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. - * - * @element ANY - * - * @example - + /** + * @ngdoc directive + * @name ngTransclude + * @restrict EAC + * + * @description + * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. + * + * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. + * + * @element ANY + * + * @example + - -
          -
          -
          - {{text}} -
          + +
          +
          +
          + {{text}} +
          - it('should have transcluded', function() { + it('should have transcluded', function() { var titleElement = element(by.model('title')); titleElement.clear(); titleElement.sendKeys('TITLE'); @@ -24757,174 +24890,174 @@ var ngSwitchDefaultDirective = ngDirective({ expect(element(by.binding('text')).getText()).toEqual('TEXT'); }); -
          - * - */ -var ngTranscludeDirective = ngDirective({ - restrict: 'EAC', - link: function($scope, $element, $attrs, controller, $transclude) { - if (!$transclude) { - throw minErr('ngTransclude')('orphan', - 'Illegal use of ngTransclude directive in the template! ' + - 'No parent directive that requires a transclusion found. ' + - 'Element: {0}', - startingTag($element)); - } +
          + * + */ + var ngTranscludeDirective = ngDirective({ + restrict: 'EAC', + link: function ($scope, $element, $attrs, controller, $transclude) { + if (!$transclude) { + throw minErr('ngTransclude')('orphan', + 'Illegal use of ngTransclude directive in the template! ' + + 'No parent directive that requires a transclusion found. ' + + 'Element: {0}', + startingTag($element)); + } - $transclude(function(clone) { - $element.empty(); - $element.append(clone); + $transclude(function (clone) { + $element.empty(); + $element.append(clone); + }); + } }); - } -}); -/** - * @ngdoc directive - * @name script - * @restrict E - * - * @description - * Load the content of a ` - - Load inlined template -
          - - - it('should load template defined inside script tag', function() { + /** + * @ngdoc directive + * @name script + * @restrict E + * + * @description + * Load the content of a ` + + Load inlined template +
          +
          + + it('should load template defined inside script tag', function() { element(by.css('#tpl-link')).click(); expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); - - - */ -var scriptDirective = ['$templateCache', function($templateCache) { - return { - restrict: 'E', - terminal: true, - compile: function(element, attr) { - if (attr.type == 'text/ng-template') { - var templateUrl = attr.id, - // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent - text = element[0].text; - - $templateCache.put(templateUrl, text); - } - } - }; -}]; + + + */ + var scriptDirective = ['$templateCache', function ($templateCache) { + return { + restrict: 'E', + terminal: true, + compile: function (element, attr) { + if (attr.type == 'text/ng-template') { + var templateUrl = attr.id, + // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent + text = element[0].text; + + $templateCache.put(templateUrl, text); + } + } + }; + }]; -var ngOptionsMinErr = minErr('ngOptions'); -/** - * @ngdoc directive - * @name select - * @restrict E - * - * @description - * HTML `SELECT` element with angular data-binding. - * - * # `ngOptions` - * - * The `ngOptions` attribute can be used to dynamically generate a list of `